@ai-development-environment/server 0.0.94 → 0.0.95

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 (141) hide show
  1. package/package.json +1 -1
  2. package/prisma-runtime/prisma/migrations/20260827120000_add_command_repository_targets/migration.sql +61 -0
  3. package/prisma-runtime/prisma/schema.prisma +13 -4
  4. package/standalone/.next/BUILD_ID +1 -1
  5. package/standalone/.next/build-manifest.json +3 -3
  6. package/standalone/.next/prerender-manifest.json +3 -3
  7. package/standalone/.next/server/app/[locale]/(auth)/register/page_client-reference-manifest.js +1 -1
  8. package/standalone/.next/server/app/[locale]/(auth)/sign-in/page_client-reference-manifest.js +1 -1
  9. package/standalone/.next/server/app/[locale]/(dashboard)/actions/page_client-reference-manifest.js +1 -1
  10. package/standalone/.next/server/app/[locale]/(dashboard)/actions-cache/page_client-reference-manifest.js +1 -1
  11. package/standalone/.next/server/app/[locale]/(dashboard)/agents/[id]/page_client-reference-manifest.js +1 -1
  12. package/standalone/.next/server/app/[locale]/(dashboard)/agents/page_client-reference-manifest.js +1 -1
  13. package/standalone/.next/server/app/[locale]/(dashboard)/analytics-events/page_client-reference-manifest.js +1 -1
  14. package/standalone/.next/server/app/[locale]/(dashboard)/api-keys/page_client-reference-manifest.js +1 -1
  15. package/standalone/.next/server/app/[locale]/(dashboard)/apps/[appId]/page_client-reference-manifest.js +1 -1
  16. package/standalone/.next/server/app/[locale]/(dashboard)/apps/page_client-reference-manifest.js +1 -1
  17. package/standalone/.next/server/app/[locale]/(dashboard)/build-data/page_client-reference-manifest.js +1 -1
  18. package/standalone/.next/server/app/[locale]/(dashboard)/builds/[buildId]/coverage/page_client-reference-manifest.js +1 -1
  19. package/standalone/.next/server/app/[locale]/(dashboard)/builds/[buildId]/page_client-reference-manifest.js +1 -1
  20. package/standalone/.next/server/app/[locale]/(dashboard)/builds/page_client-reference-manifest.js +1 -1
  21. package/standalone/.next/server/app/[locale]/(dashboard)/changes/page_client-reference-manifest.js +1 -1
  22. package/standalone/.next/server/app/[locale]/(dashboard)/codebases/[codebaseId]/page_client-reference-manifest.js +1 -1
  23. package/standalone/.next/server/app/[locale]/(dashboard)/codebases/page_client-reference-manifest.js +1 -1
  24. package/standalone/.next/server/app/[locale]/(dashboard)/codebases/repositories/[repositoryId]/page_client-reference-manifest.js +1 -1
  25. package/standalone/.next/server/app/[locale]/(dashboard)/commands/[commandId]/edit/page_client-reference-manifest.js +1 -1
  26. package/standalone/.next/server/app/[locale]/(dashboard)/commands/new/page_client-reference-manifest.js +1 -1
  27. package/standalone/.next/server/app/[locale]/(dashboard)/commands/page_client-reference-manifest.js +1 -1
  28. package/standalone/.next/server/app/[locale]/(dashboard)/commands/runs/[runId]/page_client-reference-manifest.js +1 -1
  29. package/standalone/.next/server/app/[locale]/(dashboard)/comments/page_client-reference-manifest.js +1 -1
  30. package/standalone/.next/server/app/[locale]/(dashboard)/console-logs/page_client-reference-manifest.js +1 -1
  31. package/standalone/.next/server/app/[locale]/(dashboard)/costs/page_client-reference-manifest.js +1 -1
  32. package/standalone/.next/server/app/[locale]/(dashboard)/credentials/page_client-reference-manifest.js +1 -1
  33. package/standalone/.next/server/app/[locale]/(dashboard)/devices/[id]/page_client-reference-manifest.js +1 -1
  34. package/standalone/.next/server/app/[locale]/(dashboard)/devices/enroll/page_client-reference-manifest.js +1 -1
  35. package/standalone/.next/server/app/[locale]/(dashboard)/devices/page_client-reference-manifest.js +1 -1
  36. package/standalone/.next/server/app/[locale]/(dashboard)/drafts/page_client-reference-manifest.js +1 -1
  37. package/standalone/.next/server/app/[locale]/(dashboard)/github-cache/entries/[id]/page_client-reference-manifest.js +1 -1
  38. package/standalone/.next/server/app/[locale]/(dashboard)/github-cache/page_client-reference-manifest.js +1 -1
  39. package/standalone/.next/server/app/[locale]/(dashboard)/gitlab/cache/page_client-reference-manifest.js +1 -1
  40. package/standalone/.next/server/app/[locale]/(dashboard)/gitlab/comments/page_client-reference-manifest.js +1 -1
  41. package/standalone/.next/server/app/[locale]/(dashboard)/gitlab/merge-requests/[projectId]/[iid]/page_client-reference-manifest.js +1 -1
  42. package/standalone/.next/server/app/[locale]/(dashboard)/gitlab/merge-requests/page_client-reference-manifest.js +1 -1
  43. package/standalone/.next/server/app/[locale]/(dashboard)/gitlab/pipelines/page_client-reference-manifest.js +1 -1
  44. package/standalone/.next/server/app/[locale]/(dashboard)/gitlab/webhooks/page_client-reference-manifest.js +1 -1
  45. package/standalone/.next/server/app/[locale]/(dashboard)/jira/tickets/[issueKey]/page_client-reference-manifest.js +1 -1
  46. package/standalone/.next/server/app/[locale]/(dashboard)/jira/tickets/page_client-reference-manifest.js +1 -1
  47. package/standalone/.next/server/app/[locale]/(dashboard)/jira-cache/page_client-reference-manifest.js +1 -1
  48. package/standalone/.next/server/app/[locale]/(dashboard)/jira-cache/tickets/[issueKey]/page_client-reference-manifest.js +1 -1
  49. package/standalone/.next/server/app/[locale]/(dashboard)/jira-webhooks/page_client-reference-manifest.js +1 -1
  50. package/standalone/.next/server/app/[locale]/(dashboard)/jobs/[jobId]/page_client-reference-manifest.js +1 -1
  51. package/standalone/.next/server/app/[locale]/(dashboard)/notifications/page_client-reference-manifest.js +1 -1
  52. package/standalone/.next/server/app/[locale]/(dashboard)/page_client-reference-manifest.js +1 -1
  53. package/standalone/.next/server/app/[locale]/(dashboard)/plans/[runId]/page_client-reference-manifest.js +1 -1
  54. package/standalone/.next/server/app/[locale]/(dashboard)/plans/page_client-reference-manifest.js +1 -1
  55. package/standalone/.next/server/app/[locale]/(dashboard)/polling/page_client-reference-manifest.js +1 -1
  56. package/standalone/.next/server/app/[locale]/(dashboard)/prepare/page_client-reference-manifest.js +1 -1
  57. package/standalone/.next/server/app/[locale]/(dashboard)/provisioning-profiles/[profileId]/page_client-reference-manifest.js +1 -1
  58. package/standalone/.next/server/app/[locale]/(dashboard)/provisioning-profiles/page_client-reference-manifest.js +1 -1
  59. package/standalone/.next/server/app/[locale]/(dashboard)/pull-requests/[owner]/[repository]/[number]/page_client-reference-manifest.js +1 -1
  60. package/standalone/.next/server/app/[locale]/(dashboard)/pull-requests/page_client-reference-manifest.js +1 -1
  61. package/standalone/.next/server/app/[locale]/(dashboard)/push-notifications/page_client-reference-manifest.js +1 -1
  62. package/standalone/.next/server/app/[locale]/(dashboard)/runs/new/page_client-reference-manifest.js +1 -1
  63. package/standalone/.next/server/app/[locale]/(dashboard)/sessions/[runId]/page_client-reference-manifest.js +1 -1
  64. package/standalone/.next/server/app/[locale]/(dashboard)/sessions/page_client-reference-manifest.js +1 -1
  65. package/standalone/.next/server/app/[locale]/(dashboard)/settings/page_client-reference-manifest.js +1 -1
  66. package/standalone/.next/server/app/[locale]/(dashboard)/skills/[skillId]/page_client-reference-manifest.js +1 -1
  67. package/standalone/.next/server/app/[locale]/(dashboard)/skills/groups/[groupId]/page_client-reference-manifest.js +1 -1
  68. package/standalone/.next/server/app/[locale]/(dashboard)/skills/groups/page_client-reference-manifest.js +1 -1
  69. package/standalone/.next/server/app/[locale]/(dashboard)/skills/page_client-reference-manifest.js +1 -1
  70. package/standalone/.next/server/app/[locale]/(dashboard)/skills/sync/[runId]/page_client-reference-manifest.js +1 -1
  71. package/standalone/.next/server/app/[locale]/(dashboard)/status/page_client-reference-manifest.js +1 -1
  72. package/standalone/.next/server/app/[locale]/(dashboard)/tools/page_client-reference-manifest.js +1 -1
  73. package/standalone/.next/server/app/[locale]/(dashboard)/unified-events/page_client-reference-manifest.js +1 -1
  74. package/standalone/.next/server/app/[locale]/(dashboard)/usage/page_client-reference-manifest.js +1 -1
  75. package/standalone/.next/server/app/[locale]/(dashboard)/users/page_client-reference-manifest.js +1 -1
  76. package/standalone/.next/server/app/[locale]/(dashboard)/webhooks/page_client-reference-manifest.js +1 -1
  77. package/standalone/.next/server/app/[locale]/(dashboard)/workflows/[workflowId]/edit/page_client-reference-manifest.js +1 -1
  78. package/standalone/.next/server/app/[locale]/(dashboard)/workflows/[workflowId]/page_client-reference-manifest.js +1 -1
  79. package/standalone/.next/server/app/[locale]/(dashboard)/workflows/new/page_client-reference-manifest.js +1 -1
  80. package/standalone/.next/server/app/[locale]/(dashboard)/workflows/page_client-reference-manifest.js +1 -1
  81. package/standalone/.next/server/app/[locale]/(dashboard)/workflows/runs/[runId]/page_client-reference-manifest.js +1 -1
  82. package/standalone/.next/server/app/[locale]/(dashboard)/worktrees/[worktreeId]/page_client-reference-manifest.js +1 -1
  83. package/standalone/.next/server/app/[locale]/(dashboard)/worktrees/page_client-reference-manifest.js +1 -1
  84. package/standalone/.next/server/app/_global-error.html +1 -1
  85. package/standalone/.next/server/app/_global-error.rsc +1 -1
  86. package/standalone/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
  87. package/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  88. package/standalone/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  89. package/standalone/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  90. package/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  91. package/standalone/.next/server/app/_not-found.html +1 -1
  92. package/standalone/.next/server/app/_not-found.rsc +1 -1
  93. package/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +1 -1
  94. package/standalone/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
  95. package/standalone/.next/server/app/_not-found.segments/_index.segment.rsc +1 -1
  96. package/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  97. package/standalone/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
  98. package/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
  99. package/standalone/.next/server/chunks/_086z24j._.js +4 -4
  100. package/standalone/.next/server/chunks/_0_3-lke._.js +11 -4
  101. package/standalone/.next/server/chunks/_0ssmikd._.js +4 -4
  102. package/standalone/.next/server/chunks/_0u02u5f._.js +4 -4
  103. package/standalone/.next/server/chunks/_10b12ij._.js +4 -4
  104. package/standalone/.next/server/chunks/_13gs0b4._.js +4 -4
  105. package/standalone/.next/server/chunks/_16-237k._.js +135 -128
  106. package/standalone/.next/server/chunks/_1exzvxq._.js +4 -4
  107. package/standalone/.next/server/chunks/src_07wif-p._.js +2 -2
  108. package/standalone/.next/server/chunks/src_16int4d._.js +2 -2
  109. package/standalone/.next/server/chunks/ssr/_02a3qdp._.js +2 -2
  110. package/standalone/.next/server/chunks/ssr/_0aaxviu._.js +2 -2
  111. package/standalone/.next/server/chunks/ssr/_0hwiy81._.js +2 -2
  112. package/standalone/.next/server/chunks/ssr/_0s9ey-t._.js +2 -2
  113. package/standalone/.next/server/chunks/ssr/_1-nj75c._.js +2 -2
  114. package/standalone/.next/server/chunks/ssr/_1hmpmb1._.js +2 -2
  115. package/standalone/.next/server/chunks/ssr/_1sy7lqy._.js +2 -2
  116. package/standalone/.next/server/chunks/ssr/_1x0b0dt._.js +2 -2
  117. package/standalone/.next/server/chunks/ssr/messages_de_json_[json]_cjs_1uig1ud._.js +1 -1
  118. package/standalone/.next/server/chunks/ssr/messages_en_json_[json]_cjs_206072-._.js +1 -1
  119. package/standalone/.next/server/chunks/ssr/messages_es_json_[json]_cjs_082yukd._.js +1 -1
  120. package/standalone/.next/server/chunks/ssr/messages_fr_json_[json]_cjs_0j6-w0i._.js +1 -1
  121. package/standalone/.next/server/chunks/ssr/src_components_commands_command-editor_tsx_1xv-unm._.js +2 -2
  122. package/standalone/.next/server/chunks/ssr/src_components_commands_commands-page_tsx_06_w_zo._.js +2 -2
  123. package/standalone/.next/server/chunks/ssr/src_services_auth_index_ts_05c0kh-._.js +1 -1
  124. package/standalone/.next/server/middleware-build-manifest.js +3 -3
  125. package/standalone/.next/server/pages/404.html +1 -1
  126. package/standalone/.next/server/pages/500.html +1 -1
  127. package/standalone/.next/server/server-reference-manifest.js +1 -1
  128. package/standalone/.next/server/server-reference-manifest.json +1 -1
  129. package/standalone/.next/static/chunks/{1uxc996684ia1.js → 0cx5t3vfr-76n.js} +2 -2
  130. package/standalone/.next/static/chunks/{2p5g8a3zowf0_.js → 0epqzwsph7fdf.js} +2 -2
  131. package/standalone/.next/static/chunks/{26b-zxdasv4v9.js → 0nkbgudch1obg.js} +2 -2
  132. package/standalone/.next/static/chunks/{1swfpvhyd8z1z.js → 1a26_z1grse1l.js} +2 -2
  133. package/standalone/.next/static/chunks/1n0fml45e5vyl.js +31 -0
  134. package/standalone/.next/static/chunks/{129bde2z8lln5.js → 1z1h9cni0d-da.js} +2 -2
  135. package/standalone/.next/static/chunks/{0cjz_fvsomcij.js → 210ob5-ghxnkd.js} +5 -5
  136. package/standalone/.next/static/chunks/{31wms4oyajl8q.css → 2dgcd672a-1c9.css} +1 -1
  137. package/standalone/.next/static/chunks/{3--_z6xb9410n.js → 2nhcdoxes77wu.js} +2 -2
  138. package/standalone/.next/static/chunks/01jm7btgy5r3c.js +0 -31
  139. /package/standalone/.next/static/{8PhM4-pUbAs13ht19ZVGl → P2FsAusgn7qhvImDnyMF_}/_buildManifest.js +0 -0
  140. /package/standalone/.next/static/{8PhM4-pUbAs13ht19ZVGl → P2FsAusgn7qhvImDnyMF_}/_clientMiddlewareManifest.js +0 -0
  141. /package/standalone/.next/static/{8PhM4-pUbAs13ht19ZVGl → P2FsAusgn7qhvImDnyMF_}/_ssgManifest.js +0 -0
@@ -629,7 +629,7 @@ ${n}`,d++}else eb(e,r,a)?p=e.slice(32===e.charCodeAt(r+6)?r+7:r+6,i)||void 0:g(e
629
629
  `,r),a=-1;if(-1!==t&&-1!==i?a=t<i?t:i:-1!==t?a=t===e.length-1?-1:t:-1!==i&&(a=i),-1===a)break;g(e,r,a),r=a+1,13===e.charCodeAt(r-1)&&10===e.charCodeAt(r)&&r++}return e.slice(r)}function g(e,r,i){if(r===i)return void(d>0&&t({id:c,event:p,data:u}),c=void 0,u="",d=0,p=void 0);let n=e.charCodeAt(r);if(ew(e,r,n)){let t=32===e.charCodeAt(r+5)?r+6:r+5,a=e.slice(t,i);u=0===d?a:`${u}
630
630
  ${a}`,d++;return}if(eb(e,r,n)){p=e.slice(32===e.charCodeAt(r+6)?r+7:r+6,i)||void 0;return}if(105===n&&100===e.charCodeAt(r+1)&&58===e.charCodeAt(r+2)){let t=e.slice(32===e.charCodeAt(r+3)?r+4:r+3,i);c=t.includes("\0")?void 0:t;return}if(58===n){a&&a(e.slice(r,i).slice(32===e.charCodeAt(r+1)?2:1));return}let s=e.slice(r,i),o=s.indexOf(":");if(-1===o)return void y(s,"",s);let l=s.slice(0,o),h=32===s.charCodeAt(o+1)?2:1;y(l,s.slice(o+h),s)}function y(e,t,a){switch(e){case"event":p=t||void 0;break;case"data":u=0===d?t:`${u}
631
631
  ${t}`,d++;break;case"id":c=t.includes("\0")?void 0:t;break;case"retry":/^\d+$/.test(t)?i(parseInt(t,10)):r(new ef(`Invalid \`retry\` value: "${t}"`,{type:"invalid-retry",value:t,line:a}));break;default:r(new ef(`Unknown field "${e.length>20?`${e.slice(0,20)}\u2026`:e}"`,{type:"unknown-field",field:e,value:t,line:a}))}}return{feed:function(e){if(h)throw Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(l&&(l=!1,239===e.charCodeAt(0)&&187===e.charCodeAt(1)&&191===e.charCodeAt(2)&&(e=e.slice(3))),0===s.length){let t=f(e);""!==t&&(s.push(t),o=t.length),m();return}if(-1===e.indexOf(`
632
- `)&&-1===e.indexOf("\r")){s.push(e),o+=e.length,m();return}s.push(e);let t=s.join("");s.length=0,o=0;let r=f(t);""!==r&&(s.push(r),o=r.length),m()},reset:function(e={}){if(e.consume&&s.length>0){let e=s.join("");g(e,0,e.length)}l=!0,c=void 0,u="",d=0,p=void 0,s.length=0,o=0,h=!1}}}function ew(e,t,r){return 100===r&&97===e.charCodeAt(t+1)&&116===e.charCodeAt(t+2)&&97===e.charCodeAt(t+3)&&58===e.charCodeAt(t+4)}function eb(e,t,r){return 101===r&&118===e.charCodeAt(t+1)&&101===e.charCodeAt(t+2)&&110===e.charCodeAt(t+3)&&116===e.charCodeAt(t+4)&&58===e.charCodeAt(t+5)}class ev extends Event{constructor(e,t){var r,i;super(e),this.code=null!=(r=null==t?void 0:t.code)?r:void 0,this.message=null!=(i=null==t?void 0:t.message)?i:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,t,r){return r(ek(this),t)}[Symbol.for("Deno.customInspect")](e,t){return e(ek(this),t)}}function ek(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var eE,eS,eI,eA,ex,e_,eC,eR,eT,eD,eN,eO,eP,eL,eB,eU,ej,eM,eq,e$,eF,eG,eK,eH=e=>{throw TypeError(e)},eV=(e,t,r)=>t.has(e)||eH("Cannot "+r),eW=(e,t,r)=>(eV(e,t,"read from private field"),r?r.call(e):t.get(e)),eJ=(e,t,r)=>t.has(e)?eH("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),ez=(e,t,r,i)=>(eV(e,t,"write to private field"),t.set(e,r),r),eY=(e,t,r)=>(eV(e,t,"access private method"),r);class eZ extends EventTarget{constructor(e,t){var r,i;super(),eJ(this,eL),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,eJ(this,eE),eJ(this,eS),eJ(this,eI),eJ(this,eA),eJ(this,ex),eJ(this,e_),eJ(this,eC),eJ(this,eR,null),eJ(this,eT),eJ(this,eD),eJ(this,eN,null),eJ(this,eO,null),eJ(this,eP,null),eJ(this,eU,async e=>{var t;eW(this,eD).reset();let{body:r,redirected:i,status:a,headers:n}=e;if(204===a){eY(this,eL,eF).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(i?ez(this,eI,new URL(e.url)):ez(this,eI,void 0),200!==a)return void eY(this,eL,eF).call(this,`Non-200 status code (${a})`,a);if(!(n.get("content-type")||"").startsWith("text/event-stream"))return void eY(this,eL,eF).call(this,'Invalid content type, expected "text/event-stream"',a);if(eW(this,eE)===this.CLOSED)return;ez(this,eE,this.OPEN);let s=new Event("open");if(null==(t=eW(this,eP))||t.call(this,s),this.dispatchEvent(s),"object"!=typeof r||!r||!("getReader"in r)){eY(this,eL,eF).call(this,"Invalid response body, expected a web ReadableStream",a),this.close();return}let o=new TextDecoder,l=r.getReader(),c=!0;do{let{done:e,value:t}=await l.read();t&&eW(this,eD).feed(o.decode(t,{stream:!e})),e&&(c=!1,eW(this,eD).reset(),eY(this,eL,eG).call(this))}while(c)}),eJ(this,ej,e=>{ez(this,eT,void 0),"AbortError"!==e.name&&"aborted"!==e.type&&eY(this,eL,eG).call(this,function e(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(e).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${e(t.cause)}`:t.message:`${t}`}(e))}),eJ(this,eq,e=>{"string"==typeof e.id&&ez(this,eR,e.id);let t=new MessageEvent(e.event||"message",{data:e.data,origin:eW(this,eI)?eW(this,eI).origin:eW(this,eS).origin,lastEventId:e.id||""});eW(this,eO)&&(!e.event||"message"===e.event)&&eW(this,eO).call(this,t),this.dispatchEvent(t)}),eJ(this,e$,e=>{ez(this,e_,e)}),eJ(this,eK,()=>{ez(this,eC,void 0),eW(this,eE)===this.CONNECTING&&eY(this,eL,eB).call(this)});try{if(e instanceof URL)ez(this,eS,e);else if("string"==typeof e)ez(this,eS,new URL(e,function(){let e="document"in globalThis?globalThis.document:void 0;return e&&"object"==typeof e&&"baseURI"in e&&"string"==typeof e.baseURI?e.baseURI:void 0}()));else throw Error("Invalid URL")}catch{throw function(e){let t=globalThis.DOMException;return"function"==typeof t?new t(e,"SyntaxError"):SyntaxError(e)}("An invalid or illegal string was specified")}ez(this,eD,ey({onEvent:eW(this,eq),onRetry:eW(this,e$)})),ez(this,eE,this.CONNECTING),ez(this,e_,3e3),ez(this,ex,null!=(r=null==t?void 0:t.fetch)?r:globalThis.fetch),ez(this,eA,null!=(i=null==t?void 0:t.withCredentials)&&i),eY(this,eL,eB).call(this)}get readyState(){return eW(this,eE)}get url(){return eW(this,eS).href}get withCredentials(){return eW(this,eA)}get onerror(){return eW(this,eN)}set onerror(e){ez(this,eN,e)}get onmessage(){return eW(this,eO)}set onmessage(e){ez(this,eO,e)}get onopen(){return eW(this,eP)}set onopen(e){ez(this,eP,e)}addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}close(){eW(this,eC)&&clearTimeout(eW(this,eC)),eW(this,eE)!==this.CLOSED&&(eW(this,eT)&&eW(this,eT).abort(),ez(this,eE,this.CLOSED),ez(this,eT,void 0))}}function eQ(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function eX(e=fetch,t){return t?async(r,i)=>e(r,{...t,...i,headers:i?.headers?{...eQ(t.headers),...eQ(i.headers)}:t.headers}):e}async function e0(e){return(await t).getRandomValues(new Uint8Array(e))}async function e1(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=256-256%t.length,i="";for(;i.length<e;)for(let a of(await e0(e-i.length)))a<r&&(i+=t[a%t.length]);return i}async function e2(e){return await e1(e)}async function e3(e){return btoa(String.fromCharCode(...new Uint8Array(await (await t).subtle.digest("SHA-256",new TextEncoder().encode(e))))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function e4(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await e2(e),r=await e3(t);return{code_verifier:t,code_challenge:r}}eE=new WeakMap,eS=new WeakMap,eI=new WeakMap,eA=new WeakMap,ex=new WeakMap,e_=new WeakMap,eC=new WeakMap,eR=new WeakMap,eT=new WeakMap,eD=new WeakMap,eN=new WeakMap,eO=new WeakMap,eP=new WeakMap,eL=new WeakSet,eB=function(){ez(this,eE,this.CONNECTING),ez(this,eT,new AbortController),eW(this,ex)(eW(this,eS),eY(this,eL,eM).call(this)).then(eW(this,eU)).catch(eW(this,ej))},eU=new WeakMap,ej=new WeakMap,eM=function(){var e;let t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...eW(this,eR)?{"Last-Event-ID":eW(this,eR)}:void 0},cache:"no-store",signal:null==(e=eW(this,eT))?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},eq=new WeakMap,e$=new WeakMap,eF=function(e,t){var r;eW(this,eE)!==this.CLOSED&&ez(this,eE,this.CLOSED);let i=new ev("error",{code:t,message:e});null==(r=eW(this,eN))||r.call(this,i),this.dispatchEvent(i)},eG=function(e,t){var r;if(eW(this,eE)===this.CLOSED)return;ez(this,eE,this.CONNECTING);let i=new ev("error",{code:t,message:e});null==(r=eW(this,eN))||r.call(this,i),this.dispatchEvent(i),ez(this,eC,setTimeout(eW(this,eK),eW(this,e_)))},eK=new WeakMap,eZ.CONNECTING=0,eZ.OPEN=1,eZ.CLOSED=2,t=globalThis.crypto?.webcrypto??globalThis.crypto??e.A(70729).then(e=>e.webcrypto);var e6=e.i(907855),e8=e.i(733137),e5=e.i(127438),e9=e.i(754257);let e7=e6.url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:e8.ZodIssueCode.custom,message:"URL must be parseable",fatal:!0}),e5.NEVER}).refine(e=>{let t=new URL(e);return"javascript:"!==t.protocol&&"data:"!==t.protocol&&"vbscript:"!==t.protocol},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),te=e6.looseObject({resource:e6.string().url(),authorization_servers:e6.array(e7).optional(),jwks_uri:e6.string().url().optional(),scopes_supported:e6.array(e6.string()).optional(),bearer_methods_supported:e6.array(e6.string()).optional(),resource_signing_alg_values_supported:e6.array(e6.string()).optional(),resource_name:e6.string().optional(),resource_documentation:e6.string().optional(),resource_policy_uri:e6.string().url().optional(),resource_tos_uri:e6.string().url().optional(),tls_client_certificate_bound_access_tokens:e6.boolean().optional(),authorization_details_types_supported:e6.array(e6.string()).optional(),dpop_signing_alg_values_supported:e6.array(e6.string()).optional(),dpop_bound_access_tokens_required:e6.boolean().optional()}),tt=e6.looseObject({issuer:e6.string(),authorization_endpoint:e7,token_endpoint:e7,registration_endpoint:e7.optional(),scopes_supported:e6.array(e6.string()).optional(),response_types_supported:e6.array(e6.string()),response_modes_supported:e6.array(e6.string()).optional(),grant_types_supported:e6.array(e6.string()).optional(),token_endpoint_auth_methods_supported:e6.array(e6.string()).optional(),token_endpoint_auth_signing_alg_values_supported:e6.array(e6.string()).optional(),service_documentation:e7.optional(),revocation_endpoint:e7.optional(),revocation_endpoint_auth_methods_supported:e6.array(e6.string()).optional(),revocation_endpoint_auth_signing_alg_values_supported:e6.array(e6.string()).optional(),introspection_endpoint:e6.string().optional(),introspection_endpoint_auth_methods_supported:e6.array(e6.string()).optional(),introspection_endpoint_auth_signing_alg_values_supported:e6.array(e6.string()).optional(),code_challenge_methods_supported:e6.array(e6.string()).optional(),client_id_metadata_document_supported:e6.boolean().optional()}),tr=e6.looseObject({issuer:e6.string(),authorization_endpoint:e7,token_endpoint:e7,userinfo_endpoint:e7.optional(),jwks_uri:e7,registration_endpoint:e7.optional(),scopes_supported:e6.array(e6.string()).optional(),response_types_supported:e6.array(e6.string()),response_modes_supported:e6.array(e6.string()).optional(),grant_types_supported:e6.array(e6.string()).optional(),acr_values_supported:e6.array(e6.string()).optional(),subject_types_supported:e6.array(e6.string()),id_token_signing_alg_values_supported:e6.array(e6.string()),id_token_encryption_alg_values_supported:e6.array(e6.string()).optional(),id_token_encryption_enc_values_supported:e6.array(e6.string()).optional(),userinfo_signing_alg_values_supported:e6.array(e6.string()).optional(),userinfo_encryption_alg_values_supported:e6.array(e6.string()).optional(),userinfo_encryption_enc_values_supported:e6.array(e6.string()).optional(),request_object_signing_alg_values_supported:e6.array(e6.string()).optional(),request_object_encryption_alg_values_supported:e6.array(e6.string()).optional(),request_object_encryption_enc_values_supported:e6.array(e6.string()).optional(),token_endpoint_auth_methods_supported:e6.array(e6.string()).optional(),token_endpoint_auth_signing_alg_values_supported:e6.array(e6.string()).optional(),display_values_supported:e6.array(e6.string()).optional(),claim_types_supported:e6.array(e6.string()).optional(),claims_supported:e6.array(e6.string()).optional(),service_documentation:e6.string().optional(),claims_locales_supported:e6.array(e6.string()).optional(),ui_locales_supported:e6.array(e6.string()).optional(),claims_parameter_supported:e6.boolean().optional(),request_parameter_supported:e6.boolean().optional(),request_uri_parameter_supported:e6.boolean().optional(),require_request_uri_registration:e6.boolean().optional(),op_policy_uri:e7.optional(),op_tos_uri:e7.optional(),client_id_metadata_document_supported:e6.boolean().optional()}),ti=e6.object({...tr.shape,...tt.pick({code_challenge_methods_supported:!0}).shape}),ta=e6.object({access_token:e6.string(),id_token:e6.string().optional(),token_type:e6.string(),expires_in:e9.coerce.number().optional(),scope:e6.string().optional(),refresh_token:e6.string().optional()}).strip(),tn=e6.object({error:e6.string(),error_description:e6.string().optional(),error_uri:e6.string().optional()}),ts=e7.optional().or(e6.literal("").transform(()=>void 0)),to=e6.object({redirect_uris:e6.array(e7),token_endpoint_auth_method:e6.string().optional(),grant_types:e6.array(e6.string()).optional(),response_types:e6.array(e6.string()).optional(),client_name:e6.string().optional(),client_uri:e7.optional(),logo_uri:ts,scope:e6.string().optional(),contacts:e6.array(e6.string()).optional(),tos_uri:ts,policy_uri:e6.string().optional(),jwks_uri:e7.optional(),jwks:e6.any().optional(),software_id:e6.string().optional(),software_version:e6.string().optional(),software_statement:e6.string().optional()}).strip(),tl=e6.object({client_id:e6.string(),client_secret:e6.string().optional(),client_id_issued_at:e6.number().optional(),client_secret_expires_at:e6.number().optional()}).strip(),tc=to.merge(tl);e6.object({error:e6.string(),error_description:e6.string().optional()}).strip(),e6.object({token:e6.string(),token_type_hint:e6.string().optional()}).strip();class tu extends Error{constructor(e,t){super(e),this.errorUri=t,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}}class td extends tu{}td.errorCode="invalid_request";class tp extends tu{}tp.errorCode="invalid_client";class th extends tu{}th.errorCode="invalid_grant";class tm extends tu{}tm.errorCode="unauthorized_client";class tf extends tu{}tf.errorCode="unsupported_grant_type";class tg extends tu{}tg.errorCode="invalid_scope";class ty extends tu{}ty.errorCode="access_denied";class tw extends tu{}tw.errorCode="server_error";class tb extends tu{}tb.errorCode="temporarily_unavailable";class tv extends tu{}tv.errorCode="unsupported_response_type";class tk extends tu{}tk.errorCode="unsupported_token_type";class tE extends tu{}tE.errorCode="invalid_token";class tS extends tu{}tS.errorCode="method_not_allowed";class tI extends tu{}tI.errorCode="too_many_requests";class tA extends tu{}tA.errorCode="invalid_client_metadata";class tx extends tu{}tx.errorCode="insufficient_scope";class t_ extends tu{}t_.errorCode="invalid_target";let tC={[td.errorCode]:td,[tp.errorCode]:tp,[th.errorCode]:th,[tm.errorCode]:tm,[tf.errorCode]:tf,[tg.errorCode]:tg,[ty.errorCode]:ty,[tw.errorCode]:tw,[tb.errorCode]:tb,[tv.errorCode]:tv,[tk.errorCode]:tk,[tE.errorCode]:tE,[tS.errorCode]:tS,[tI.errorCode]:tI,[tA.errorCode]:tA,[tx.errorCode]:tx,[t_.errorCode]:t_};class tR extends Error{constructor(e){super(e??"Unauthorized")}}let tT="code",tD="S256";async function tN(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let{error:e,error_description:t,error_uri:i}=tn.parse(JSON.parse(r));return new(tC[e]||tw)(t||"",i)}catch(e){return new tw(`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${e}. Raw body: ${r}`)}}async function tO(e,t){try{return await tP(e,t)}catch(r){if(r instanceof tp||r instanceof tm)return await e.invalidateCredentials?.("all"),await tP(e,t);if(r instanceof th)return await e.invalidateCredentials?.("tokens"),await tP(e,t);throw r}}async function tP(e,{serverUrl:t,authorizationCode:r,scope:i,resourceMetadataUrl:a,fetchFn:n}){let s,o,l,c=await e.discoveryState?.(),u=a;if(!u&&c?.resourceMetadataUrl&&(u=new URL(c.resourceMetadataUrl)),c?.authorizationServerUrl){if(o=c.authorizationServerUrl,s=c.resourceMetadata,l=c.authorizationServerMetadata??await tF(o,{fetchFn:n}),!s)try{s=await tj(t,{resourceMetadataUrl:u},n)}catch{}(l!==c.authorizationServerMetadata||s!==c.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(o),resourceMetadataUrl:u?.toString(),resourceMetadata:s,authorizationServerMetadata:l})}else{let r=await tG(t,{resourceMetadataUrl:u,fetchFn:n});o=r.authorizationServerUrl,l=r.authorizationServerMetadata,s=r.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(o),resourceMetadataUrl:u?.toString(),resourceMetadata:s,authorizationServerMetadata:l})}let d=await tL(t,e,s),p=i||s?.scopes_supported?.join(" ")||e.clientMetadata.scope,h=await Promise.resolve(e.clientInformation());if(!h){if(void 0!==r)throw Error("Existing OAuth client information is required when exchanging an authorization code");let t=l?.client_id_metadata_document_supported===!0,i=e.clientMetadataUrl;if(i&&!function(e){if(!e)return!1;try{let t=new URL(e);return"https:"===t.protocol&&"/"!==t.pathname}catch{return!1}}(i))throw new tA(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${i}`);if(t&&i)h={client_id:i},await e.saveClientInformation?.(h);else{if(!e.saveClientInformation)throw Error("OAuth client information must be saveable for dynamic registration");let t=await tJ(o,{metadata:l,clientMetadata:e.clientMetadata,scope:p,fetchFn:n});await e.saveClientInformation(t),h=t}}let m=!e.redirectUrl;if(void 0!==r||m){let t=await tW(e,o,{metadata:l,resource:d,authorizationCode:r,fetchFn:n});return await e.saveTokens(t),"AUTHORIZED"}let f=await e.tokens();if(f?.refresh_token)try{let t=await tV(o,{metadata:l,clientInformation:h,refreshToken:f.refresh_token,resource:d,addClientAuthentication:e.addClientAuthentication,fetchFn:n});return await e.saveTokens(t),"AUTHORIZED"}catch(e){if(!(e instanceof tu)||e instanceof tw);else throw e}let g=e.state?await e.state():void 0,{authorizationUrl:y,codeVerifier:w}=await tK(o,{metadata:l,clientInformation:h,state:g,redirectUrl:e.redirectUrl,scope:p,resource:d});return await e.saveCodeVerifier(w),await e.redirectToAuthorization(y),"REDIRECT"}async function tL(e,t,r){let i,a=((i=new URL("string"==typeof e?e:e.href)).hash="",i);if(t.validateResourceURL)return await t.validateResourceURL(a,r?.resource);if(r){if(!function({requestedResource:e,configuredResource:t}){let r=new URL("string"==typeof e?e:e.href),i=new URL("string"==typeof t?t:t.href);if(r.origin!==i.origin||r.pathname.length<i.pathname.length)return!1;let a=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",n=i.pathname.endsWith("/")?i.pathname:i.pathname+"/";return a.startsWith(n)}({requestedResource:a,configuredResource:r.resource}))throw Error(`Protected resource ${r.resource} does not match expected ${a} (or origin)`);return new URL(r.resource)}}function tB(e){let t,r=e.headers.get("WWW-Authenticate");if(!r)return{};let[i,a]=r.split(" ");if("bearer"!==i.toLowerCase()||!a)return{};let n=tU(e,"resource_metadata")||void 0;if(n)try{t=new URL(n)}catch{}return{resourceMetadataUrl:t,scope:tU(e,"scope")||void 0,error:tU(e,"error")||void 0}}function tU(e,t){let r=e.headers.get("WWW-Authenticate");if(!r)return null;let i=RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),a=r.match(i);return a?a[1]||a[2]:null}async function tj(e,t,r=fetch){let i=await t$(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!i||404===i.status)throw await i?.body?.cancel(),Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!i.ok)throw await i.body?.cancel(),Error(`HTTP ${i.status} trying to load well-known OAuth protected resource metadata.`);return te.parse(await i.json())}async function tM(e,t,r=fetch){try{return await r(e,{headers:t})}catch(i){if(i instanceof TypeError)if(t)return tM(e,void 0,r);else return;throw i}}async function tq(e,t,r=fetch){return await tM(e,{"MCP-Protocol-Version":t},r)}async function t$(e,t,r,i){var a,n;let s,o=new URL(e),l=i?.protocolVersion??E.LATEST_PROTOCOL_VERSION;i?.metadataUrl?s=new URL(i.metadataUrl):(s=new URL(function(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}(t,o.pathname),i?.metadataServerUrl??o)).search=o.search;let c=await tq(s,l,r);if(!i?.metadataUrl&&(a=c,n=o.pathname,!a||a.status>=400&&a.status<500&&"/"!==n)){let e=new URL(`/.well-known/${t}`,o);c=await tq(e,l,r)}return c}async function tF(e,{fetchFn:t=fetch,protocolVersion:r=E.LATEST_PROTOCOL_VERSION}={}){let i={"MCP-Protocol-Version":r,Accept:"application/json"};for(let{url:r,type:a}of function(e){let t="string"==typeof e?new URL(e):e,r="/"!==t.pathname,i=[];if(!r)return i.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),i.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),i;let a=t.pathname;return a.endsWith("/")&&(a=a.slice(0,-1)),i.push({url:new URL(`/.well-known/oauth-authorization-server${a}`,t.origin),type:"oauth"}),i.push({url:new URL(`/.well-known/openid-configuration${a}`,t.origin),type:"oidc"}),i.push({url:new URL(`${a}/.well-known/openid-configuration`,t.origin),type:"oidc"}),i}(e)){let e=await tM(r,i,t);if(e){if(!e.ok){if(await e.body?.cancel(),e.status>=400&&e.status<500)continue;throw Error(`HTTP ${e.status} trying to load ${"oauth"===a?"OAuth":"OpenID provider"} metadata from ${r}`)}if("oauth"===a)return tt.parse(await e.json());return ti.parse(await e.json())}}}async function tG(e,t){let r,i;try{(r=await tj(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn)).authorization_servers&&r.authorization_servers.length>0&&(i=r.authorization_servers[0])}catch{}i||(i=String(new URL("/",e)));let a=await tF(i,{fetchFn:t?.fetchFn});return{authorizationServerUrl:i,authorizationServerMetadata:a,resourceMetadata:r}}async function tK(e,{metadata:t,clientInformation:r,redirectUrl:i,scope:a,state:n,resource:s}){let o;if(t){if(o=new URL(t.authorization_endpoint),!t.response_types_supported.includes(tT))throw Error(`Incompatible auth server: does not support response type ${tT}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(tD))throw Error(`Incompatible auth server: does not support code challenge method ${tD}`)}else o=new URL("/authorize",e);let l=await e4(),c=l.code_verifier,u=l.code_challenge;return o.searchParams.set("response_type",tT),o.searchParams.set("client_id",r.client_id),o.searchParams.set("code_challenge",u),o.searchParams.set("code_challenge_method",tD),o.searchParams.set("redirect_uri",String(i)),n&&o.searchParams.set("state",n),a&&o.searchParams.set("scope",a),a?.includes("offline_access")&&o.searchParams.append("prompt","consent"),s&&o.searchParams.set("resource",s.href),{authorizationUrl:o,codeVerifier:c}}async function tH(e,{metadata:t,tokenRequestParams:r,clientInformation:i,addClientAuthentication:a,resource:n,fetchFn:s}){var o,l;let c,u=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),d=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});n&&r.set("resource",n.href),a?await a(d,r,u,t):i&&function(e,t,r,i){let{client_id:a,client_secret:n}=t;switch(e){case"client_secret_basic":var s,o,l,c,u=a,d=n,p=r;if(!d)throw Error("client_secret_basic authentication requires a client_secret");let h=btoa(`${u}:${d}`);p.set("Authorization",`Basic ${h}`);return;case"client_secret_post":s=a,o=n,(l=i).set("client_id",s),o&&l.set("client_secret",o);return;case"none":c=a,i.set("client_id",c);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}((o=i,l=t?.token_endpoint_auth_methods_supported??[],c=void 0!==o.client_secret,"token_endpoint_auth_method"in o&&o.token_endpoint_auth_method&&["client_secret_basic","client_secret_post","none"].includes(o.token_endpoint_auth_method)&&(0===l.length||l.includes(o.token_endpoint_auth_method))?o.token_endpoint_auth_method:0===l.length?c?"client_secret_basic":"none":c&&l.includes("client_secret_basic")?"client_secret_basic":c&&l.includes("client_secret_post")?"client_secret_post":l.includes("none")?"none":c?"client_secret_post":"none"),i,d,r);let p=await (s??fetch)(u,{method:"POST",headers:d,body:r});if(!p.ok)throw await tN(p);return ta.parse(await p.json())}async function tV(e,{metadata:t,clientInformation:r,refreshToken:i,resource:a,addClientAuthentication:n,fetchFn:s}){let o=new URLSearchParams({grant_type:"refresh_token",refresh_token:i});return{refresh_token:i,...await tH(e,{metadata:t,tokenRequestParams:o,clientInformation:r,addClientAuthentication:n,resource:a,fetchFn:s})}}async function tW(e,t,{metadata:r,resource:i,authorizationCode:a,fetchFn:n}={}){let s,o=e.clientMetadata.scope;if(e.prepareTokenRequest&&(s=await e.prepareTokenRequest(o)),!s){if(!a)throw Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw Error("redirectUrl is required for authorization_code flow");s=new URLSearchParams({grant_type:"authorization_code",code:a,code_verifier:await e.codeVerifier(),redirect_uri:String(e.redirectUrl)})}return tH(t,{metadata:r,tokenRequestParams:s,clientInformation:await e.clientInformation()??void 0,addClientAuthentication:e.addClientAuthentication,resource:i,fetchFn:n})}async function tJ(e,{metadata:t,clientMetadata:r,scope:i,fetchFn:a}){let n;if(t){if(!t.registration_endpoint)throw Error("Incompatible auth server: does not support dynamic client registration");n=new URL(t.registration_endpoint)}else n=new URL("/register",e);let s=await (a??fetch)(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...void 0!==i?{scope:i}:{}})});if(!s.ok)throw await tN(s);return tc.parse(await s.json())}class tz extends Error{constructor(e,t,r){super(`SSE error: ${t}`),this.code=e,this.event=r}}class tY{constructor(e,t){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=t?.eventSourceInit,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=eX(t?.fetch,t?.requestInit)}async _authThenStart(){let e;if(!this._authProvider)throw new tR("No auth provider");try{e=await tO(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(e){throw this.onerror?.(e),e}if("AUTHORIZED"!==e)throw new tR;return await this._startOrAuth()}async _commonHeaders(){let e={};if(this._authProvider){let t=await this._authProvider.tokens();t&&(e.Authorization=`Bearer ${t.access_token}`)}this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let t=eQ(this._requestInit?.headers);return new Headers({...e,...t})}_startOrAuth(){let e=this?._eventSourceInit?.fetch??this._fetch??fetch;return new Promise((t,r)=>{this._eventSource=new eZ(this._url.href,{...this._eventSourceInit,fetch:async(t,r)=>{let i=await this._commonHeaders();i.set("Accept","text/event-stream");let a=await e(t,{...r,headers:i});if(401===a.status&&a.headers.has("www-authenticate")){let{resourceMetadataUrl:e,scope:t}=tB(a);this._resourceMetadataUrl=e,this._scope=t}return a}}),this._abortController=new AbortController,this._eventSource.onerror=e=>{if(401===e.code&&this._authProvider)return void this._authThenStart().then(t,r);let i=new tz(e.code,e.message,e);r(i),this.onerror?.(i)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",e=>{try{if(this._endpoint=new URL(e.data,this._url),this._endpoint.origin!==this._url.origin)throw Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(e){r(e),this.onerror?.(e),this.close();return}t()}),this._eventSource.onmessage=e=>{let t;try{t=E.JSONRPCMessageSchema.parse(JSON.parse(e.data))}catch(e){this.onerror?.(e);return}this.onmessage?.(t)}})}async start(){if(this._eventSource)throw Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new tR("No auth provider");if("AUTHORIZED"!==await tO(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit}))throw new tR("Failed to authorize")}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(e){if(!this._endpoint)throw Error("Not connected");try{let t=await this._commonHeaders();t.set("content-type","application/json");let r={...this._requestInit,method:"POST",headers:t,body:JSON.stringify(e),signal:this._abortController?.signal},i=await (this._fetch??fetch)(this._endpoint,r);if(!i.ok){let t=await i.text().catch(()=>null);if(401===i.status&&this._authProvider){let{resourceMetadataUrl:t,scope:r}=tB(i);this._resourceMetadataUrl=t,this._scope=r;let a=await tO(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit});if("AUTHORIZED"!==a)throw new tR;return this.send(e)}throw Error(`Error POSTing to endpoint (HTTP ${i.status}): ${t}`)}await i.body?.cancel()}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}}class tZ extends TransformStream{constructor({onError:e,onRetry:t,onComment:r,maxBufferSize:i}={}){let a;super({start(n){a=ey({onEvent:e=>{n.enqueue(e)},onError(t){"function"==typeof e&&e(t),("terminate"===e||"max-buffer-size-exceeded"===t.type)&&n.error(t)},onRetry:t,onComment:r,maxBufferSize:i})},transform(e){a.feed(e)}})}}let tQ={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class tX extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}}class t0{constructor(e,t){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=eX(t?.fetch,t?.requestInit),this._sessionId=t?.sessionId,this._reconnectionOptions=t?.reconnectionOptions??tQ}async _authThenStart(){let e;if(!this._authProvider)throw new tR("No auth provider");try{e=await tO(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(e){throw this.onerror?.(e),e}if("AUTHORIZED"!==e)throw new tR;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let t=await this._authProvider.tokens();t&&(e.Authorization=`Bearer ${t.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let t=eQ(this._requestInit?.headers);return new Headers({...e,...t})}async _startOrAuthSse(e){let{resumptionToken:t}=e;try{let r=await this._commonHeaders();r.set("Accept","text/event-stream"),t&&r.set("last-event-id",t);let i=await (this._fetch??fetch)(this._url,{method:"GET",headers:r,signal:this._abortController?.signal});if(!i.ok){if(await i.body?.cancel(),401===i.status&&this._authProvider)return await this._authThenStart();if(405===i.status)return;throw new tX(i.status,`Failed to open SSE stream: ${i.statusText}`)}this._handleSseStream(i.body,e,!0)}catch(e){throw this.onerror?.(e),e}}_getNextReconnectionDelay(e){return void 0!==this._serverRetryMs?this._serverRetryMs:Math.min(this._reconnectionOptions.initialReconnectionDelay*Math.pow(this._reconnectionOptions.reconnectionDelayGrowFactor,e),this._reconnectionOptions.maxReconnectionDelay)}_scheduleReconnection(e,t=0){let r=this._reconnectionOptions.maxRetries;if(t>=r)return void this.onerror?.(Error(`Maximum reconnection attempts (${r}) exceeded.`));let i=this._getNextReconnectionDelay(t);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(r=>{this.onerror?.(Error(`Failed to reconnect SSE stream: ${r instanceof Error?r.message:String(r)}`)),this._scheduleReconnection(e,t+1)})},i)}_handleSseStream(e,t,r){let i;if(!e)return;let{onresumptiontoken:a,replayMessageId:n}=t,s=!1,o=!1;(async()=>{try{let t=e.pipeThrough(new TextDecoderStream).pipeThrough(new tZ({onRetry:e=>{this._serverRetryMs=e}})).getReader();for(;;){let{value:e,done:r}=await t.read();if(r)break;if((e.id&&(i=e.id,s=!0,a?.(e.id)),e.data)&&(!e.event||"message"===e.event))try{let t=E.JSONRPCMessageSchema.parse(JSON.parse(e.data));(0,E.isJSONRPCResultResponse)(t)&&(o=!0,void 0!==n&&(t.id=n)),this.onmessage?.(t)}catch(e){this.onerror?.(e)}}(r||s)&&!o&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:i,onresumptiontoken:a,replayMessageId:n},0)}catch(e){if(this.onerror?.(Error(`SSE stream disconnected: ${e}`)),(r||s)&&!o&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:i,onresumptiontoken:a,replayMessageId:n},0)}catch(e){this.onerror?.(Error(`Failed to reconnect: ${e instanceof Error?e.message:String(e)}`))}}})()}async start(){if(this._abortController)throw Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new tR("No auth provider");if("AUTHORIZED"!==await tO(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit}))throw new tR("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(e,t){try{let{resumptionToken:r,onresumptiontoken:i}=t||{};if(r)return void this._startOrAuthSse({resumptionToken:r,replayMessageId:(0,E.isJSONRPCRequest)(e)?e.id:void 0}).catch(e=>this.onerror?.(e));let a=await this._commonHeaders();a.set("content-type","application/json"),a.set("accept","application/json, text/event-stream");let n={...this._requestInit,method:"POST",headers:a,body:JSON.stringify(e),signal:this._abortController?.signal},s=await (this._fetch??fetch)(this._url,n),o=s.headers.get("mcp-session-id");if(o&&(this._sessionId=o),!s.ok){let t=await s.text().catch(()=>null);if(401===s.status&&this._authProvider){if(this._hasCompletedAuthFlow)throw new tX(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:t,scope:r}=tB(s);this._resourceMetadataUrl=t,this._scope=r;let i=await tO(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit});if("AUTHORIZED"!==i)throw new tR;return this._hasCompletedAuthFlow=!0,this.send(e)}if(403===s.status&&this._authProvider){let{resourceMetadataUrl:t,scope:r,error:i}=tB(s);if("insufficient_scope"===i){let i=s.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===i)throw new tX(403,"Server returned 403 after trying upscoping");r&&(this._scope=r),t&&(this._resourceMetadataUrl=t),this._lastUpscopingHeader=i??void 0;let a=await tO(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch});if("AUTHORIZED"!==a)throw new tR;return this.send(e)}}throw new tX(s.status,`Error POSTing to endpoint: ${t}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,202===s.status){await s.body?.cancel(),(0,E.isInitializedNotification)(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(e=>this.onerror?.(e));return}let l=(Array.isArray(e)?e:[e]).filter(e=>"method"in e&&"id"in e&&void 0!==e.id).length>0,c=s.headers.get("content-type");if(l)if(c?.includes("text/event-stream"))this._handleSseStream(s.body,{onresumptiontoken:i},!1);else if(c?.includes("application/json")){let e=await s.json();for(let t of Array.isArray(e)?e.map(e=>E.JSONRPCMessageSchema.parse(e)):[E.JSONRPCMessageSchema.parse(e)])this.onmessage?.(t)}else throw await s.body?.cancel(),new tX(-1,`Unexpected content type: ${c}`);else await s.body?.cancel()}catch(e){throw this.onerror?.(e),e}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),t={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},r=await (this._fetch??fetch)(this._url,t);if(await r.body?.cancel(),!r.ok&&405!==r.status)throw new tX(r.status,`Failed to terminate session: ${r.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}}var t1=e.i(243783);e.i(582482);var t2=e.i(318905),t3=e.i(91022),t4=e.i(971619);function t6(e){if("string"!=typeof e)return e??null;try{return JSON.parse(e)}catch{return null}}function t8(e){return e instanceof Date?e.toISOString():"string"==typeof e&&Number.isFinite(Date.parse(e))?new Date(e).toISOString():null}function t5(e){let t;return{id:String(e.id),name:String(e.name),hostname:String(e.hostname),version:String(e.version),osVersion:String(e.osVersion),architecture:String(e.architecture),cpuModel:"string"==typeof e.cpuModel?e.cpuModel:null,memoryTotalBytes:"number"==typeof e.memoryTotalBytes?e.memoryTotalBytes:null,memoryFreeBytes:"number"==typeof e.memoryFreeBytes?e.memoryFreeBytes:null,diskTotalBytes:"number"==typeof e.diskTotalBytes?e.diskTotalBytes:null,diskFreeBytes:"number"==typeof e.diskFreeBytes?e.diskFreeBytes:null,capabilities:Array.isArray(e.capabilities)?e.capabilities:t6(e.capabilitiesJson)??[],baseRepoDirectory:"string"==typeof e.baseRepoDirectory?e.baseRepoDirectory:null,derivedDataLocationMode:String(e.derivedDataLocationMode),derivedDataPath:"string"==typeof e.derivedDataPath?e.derivedDataPath:null,buildsDirectory:"string"==typeof e.buildsDirectory?e.buildsDirectory:null,defaultBuildsDirectory:"string"==typeof e.defaultBuildsDirectory?e.defaultBuildsDirectory:null,effectiveBuildsDirectory:(0,t4.effectiveBuildsDirectory)(e),connectionStatus:null!==(t=t8(e.lastSeenAt))&&Date.now()-Date.parse(t)<=(0,a.agentOnlineWindowMs)(e)&&!e.disconnectedAt?"ONLINE":"OFFLINE",ipAddress:"string"==typeof e.ipAddress?e.ipAddress:null,lastSeenAt:t8(e.lastSeenAt),disconnectedAt:t8(e.disconnectedAt),createdAt:t8(e.createdAt),updatedAt:t8(e.updatedAt)}}function t9(e){let t=t5(e);return{agentId:t.id,baseRepoDirectory:t.baseRepoDirectory,buildsDirectory:t.buildsDirectory,defaultBuildsDirectory:t.defaultBuildsDirectory,effectiveBuildsDirectory:t.effectiveBuildsDirectory,derivedDataLocationMode:t.derivedDataLocationMode,derivedDataPath:t.derivedDataPath,updatedAt:t.updatedAt}}function t7(e){return{id:String(e.id),agentId:String(e.agentId),worktreeId:"string"==typeof e.worktreeId?e.worktreeId:null,codebaseId:"string"==typeof e.codebaseId?e.codebaseId:null,kind:String(e.kind),payload:t6(e.payload??e.payloadJson),status:String(e.status),idempotencyKey:String(e.idempotencyKey),result:t6(e.result??e.resultJson),error:"string"==typeof e.error?e.error:null,timeoutSeconds:Number(e.timeoutSeconds),createdAt:t8(e.createdAt),startedAt:t8(e.startedAt),finishedAt:t8(e.finishedAt),updatedAt:t8(e.updatedAt)}}function re(e){return JSON.parse(JSON.stringify(e))}function rt(e){let t=e._count,r=e.versions;return{id:String(e.id),name:String(e.name),description:String(e.description??""),enabled:!0===e.enabled,overlapPolicy:String(e.overlapPolicy),overlapScope:String(e.overlapScope??"WORKTREE"),maxConcurrentRuns:Number(e.maxConcurrentRuns),completionNotificationsEnabled:!1!==e.completionNotificationsEnabled,exclusiveWorktree:!0===e.exclusiveWorktree,worktreeConcurrency:String(e.worktreeConcurrency??(!0===e.exclusiveWorktree?"EXCLUSIVE":"NON_EXCLUSIVE")),blocksGitOperations:!0===e.blocksGitOperations,activeVersionId:"string"==typeof e.activeVersionId?e.activeVersionId:null,draftSchemaVersion:Number(e.draftSchemaVersion),quickActionKind:String(e.quickActionKind??"NONE"),archivedAt:t8(e.archivedAt),versionCount:t?.versions??r?.length??0,runCount:t?.runs??0,createdAt:t8(e.createdAt),updatedAt:t8(e.updatedAt)}}function rr(e){return{id:String(e.id),workflowId:String(e.workflowId),version:Number(e.version),name:String(e.name),description:String(e.description??""),schemaVersion:Number(e.schemaVersion),contentHash:String(e.contentHash),definition:t6(e.definitionJson),publishedAt:t8(e.publishedAt)}}function ri(e){let t=e._count;return{id:String(e.id),displayNumber:Number(e.displayNumber),workflowId:String(e.workflowId),versionId:String(e.versionId),parentRunId:"string"==typeof e.parentRunId?e.parentRunId:null,triggerKind:String(e.triggerKind),triggerSubjectKey:String(e.triggerSubjectKey??""),triggerPayload:t6(e.triggerPayloadJson),status:String(e.status),phase:String(e.phase),generation:Number(e.generation),sessionData:t6(e.sessionDataJson),blockedReason:"string"==typeof e.blockedReason?e.blockedReason:null,error:"string"==typeof e.error?e.error:null,attemptCount:t?.attempts??e.attempts?.length??0,eventCount:t?.events??e.events?.length??0,queuedAt:t8(e.queuedAt),startedAt:t8(e.startedAt),pausedAt:t8(e.pausedAt),finishedAt:t8(e.finishedAt),updatedAt:t8(e.updatedAt)}}let ra=e6.object({}),rn=e6.object({id:e6.string(),name:e6.string(),hostname:e6.string(),version:e6.string(),osVersion:e6.string(),architecture:e6.string(),cpuModel:e6.string().nullable(),memoryTotalBytes:e6.number().nullable(),memoryFreeBytes:e6.number().nullable(),diskTotalBytes:e6.number().nullable(),diskFreeBytes:e6.number().nullable(),capabilities:e6.array(e6.string()),baseRepoDirectory:e6.string().nullable(),derivedDataLocationMode:e6.enum(["DEFAULT","ABSOLUTE","RELATIVE"]),derivedDataPath:e6.string().nullable(),buildsDirectory:e6.string().nullable(),defaultBuildsDirectory:e6.string().nullable(),effectiveBuildsDirectory:e6.string().nullable(),connectionStatus:e6.enum(["ONLINE","OFFLINE"]),ipAddress:e6.string().nullable(),lastSeenAt:e6.string().nullable(),disconnectedAt:e6.string().nullable(),createdAt:e6.string(),updatedAt:e6.string()}),rs=e6.object({agentId:e6.string(),baseRepoDirectory:e6.string().nullable(),buildsDirectory:e6.string().nullable(),defaultBuildsDirectory:e6.string().nullable(),effectiveBuildsDirectory:e6.string().nullable(),derivedDataLocationMode:e6.enum(["DEFAULT","ABSOLUTE","RELATIVE"]),derivedDataPath:e6.string().nullable(),updatedAt:e6.string()}),ro=e6.object({id:e6.string(),agentId:e6.string(),worktreeId:e6.string().nullable(),codebaseId:e6.string().nullable(),kind:e6.string(),payload:e6.unknown(),status:e6.string(),idempotencyKey:e6.string(),result:e6.unknown().nullable(),error:e6.string().nullable(),timeoutSeconds:e6.number().int(),createdAt:e6.string(),startedAt:e6.string().nullable(),finishedAt:e6.string().nullable(),updatedAt:e6.string()}),rl=e6.object({id:e6.string(),jobId:e6.string(),sequence:e6.number().int(),stream:e6.string(),message:e6.string(),createdAt:e6.string()}),rc=e6.object({agentId:e6.string().min(1)});var ru=e.i(190714);async function rd(e,t,r=[]){if(!e||"object"!=typeof e)throw Error(`Service for ${t} is unavailable`);let i=e[t];if("function"!=typeof i)throw Error(`Service operation ${t} is unavailable`);return Reflect.apply(i,e,r)}let rp=/^(?:credentialValue|enrollmentToken|privateKey|privateKeyPem|p12|p12Base64|apnsToken|token|nativeTranscript|nativeSession|nativeSessionFile|rawJson|secretHash|tokenHash)$/i;function rh(e){return e instanceof Date?e.toISOString():Array.isArray(e)?e.map(rh):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).filter(([e])=>!rp.test(e)).map(([e,t])=>[e,rh(t)])):e}function rm(e){let t=e.resultKey??"result";return an({name:e.name,title:e.title,description:e.description,inputSchema:e.inputSchema,outputSchema:e6.object({[t]:e6.unknown()}),annotations:e.annotations??i7,handler:async r=>{let i=await rd(e.service,e.method,e.arguments?.(r)??[r]);return{[t]:e.mapResult?e.mapResult(i):rh(i??null)}}})}let rf=e6.object({});var rg=e.i(184015);let ry=e6.object({}),rw=e6.object({settings:e6.object({refreshIntervalSeconds:e6.number().int(),fetchIntervalSeconds:e6.number().int(),defaultJiraBranchRegex:e6.string(),updatedAt:e6.string()})}),rb=e6.object({agentId:e6.string().min(1),path:e6.string().nullable().default(null),requestId:e6.string().min(1)}),rv=e6.object({listing:e6.unknown()}),rk=e6.object({agentId:e6.string().min(1),folder:e6.string().min(1),requestId:e6.string().min(1)}),rE=e6.object({inspection:e6.unknown()}),rS=e6.object({codebaseIds:e6.array(e6.string().min(1)).min(1).max(500),requestId:e6.string().min(1)}),rI=e6.object({jobs:e6.array(e6.unknown()),skipped:e6.array(e6.object({codebaseId:e6.string(),reason:e6.string()}))}),rA=e6.object({codebaseId:e6.string().min(1),requestId:e6.string().min(1)}),rx=e6.object({state:e6.unknown()}),r_=e6.object({codebaseId:e6.string().min(1),stashOid:e6.string().regex(/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/i),requestId:e6.string().min(1)}),rC=e6.object({diff:e6.unknown()}),rR=e6.object({id:e6.string(),kind:e6.enum(["WRITE","DELETE","ASSUME_UNCHANGED"]),path:e6.string(),contentBase64:e6.string().nullable(),contentSha256:e6.string().nullable(),byteCount:e6.number().int().nonnegative().nullable(),definitionHash:e6.string(),createdAt:e6.string(),updatedAt:e6.string()}),rT=e6.object({repositoryId:e6.string().min(1)}),rD=e=>({id:e.id,kind:e.kind,path:e.path,contentBase64:e.contents?Buffer.from(e.contents).toString("base64"):null,contentSha256:e.contentSha256,byteCount:e.byteCount,definitionHash:e.definitionHash,createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString()});e.i(282790);var rN=e.i(474170);function rO(e){return e instanceof Date?e.toISOString():null}function rP(e){if("string"!=typeof e)return e??null;try{return JSON.parse(e)}catch{return null}}let rL=e6.object({id:e6.string(),clientRegistrationId:e6.string(),tokenMasked:e6.string(),topic:e6.string(),environment:e6.string(),supportedPushTypes:e6.array(e6.string()),displayName:e6.string(),deviceModel:e6.string().nullable(),osVersion:e6.string().nullable(),appVersion:e6.string().nullable(),appBuild:e6.string().nullable(),locale:e6.string().nullable(),pushMagicConfigured:e6.boolean(),status:e6.string(),invalidatedAt:e6.string().nullable(),lastFailureReason:e6.string().nullable(),lastFailureAt:e6.string().nullable(),lastRegisteredAt:e6.string(),lastSentAt:e6.string().nullable(),createdAt:e6.string(),updatedAt:e6.string()}),rB=e6.object({id:e6.string(),name:e6.string(),topic:e6.string(),environment:e6.string(),fingerprint:e6.string(),expiresAt:e6.string().nullable(),lastTestedAt:e6.string().nullable(),lastError:e6.string().nullable(),createdAt:e6.string(),updatedAt:e6.string()}),rU=e6.object({tokenConfigured:e6.boolean(),tokenTeamId:e6.string().nullable(),tokenKeyId:e6.string().nullable(),tokenPrivateKeyFingerprint:e6.string().nullable(),tokenConfiguredAt:e6.string().nullable(),tokenLastUsedAt:e6.string().nullable(),tokenLastError:e6.string().nullable(),certificates:e6.array(rB),updatedAt:e6.string()}),rj=e6.object({id:e6.string(),channelId:e6.string(),bundleId:e6.string(),environment:e6.string(),storagePolicy:e6.string(),createdAt:e6.string(),updatedAt:e6.string()}),rM=e6.object({id:e6.string(),name:e6.string(),editor:e6.unknown(),createdAt:e6.string(),updatedAt:e6.string()}),rq=e6.object({id:e6.string(),registrationId:e6.string().nullable(),topic:e6.string(),environment:e6.string(),status:e6.string(),apnsId:e6.string().nullable(),responseCode:e6.number().int().nullable(),reason:e6.string().nullable(),responseTimestamp:e6.string().nullable(),attempts:e6.number().int(),durationMs:e6.number().int().nullable(),createdAt:e6.string(),startedAt:e6.string().nullable(),finishedAt:e6.string().nullable()}),r$=e6.object({id:e6.string(),requestId:e6.string(),status:e6.string(),editor:e6.unknown(),payload:e6.unknown(),headers:e6.unknown(),targetMode:e6.string(),channelId:e6.string().nullable(),recipientCount:e6.number().int(),successCount:e6.number().int(),failureCount:e6.number().int(),error:e6.string().nullable(),createdAt:e6.string(),startedAt:e6.string().nullable(),finishedAt:e6.string().nullable(),updatedAt:e6.string(),deliveries:e6.array(rq)});function rF(e){return{id:String(e.id),requestId:String(e.requestId),status:String(e.status),editor:rP(e.editor??e.editorJson),payload:rP(e.payload??e.payloadJson),headers:rP(e.headers??e.headersJson),targetMode:String(e.targetMode),channelId:"string"==typeof e.channelId?e.channelId:null,recipientCount:Number(e.recipientCount),successCount:Number(e.successCount),failureCount:Number(e.failureCount),error:"string"==typeof e.error?e.error:null,createdAt:rO(e.createdAt),startedAt:rO(e.startedAt),finishedAt:rO(e.finishedAt),updatedAt:rO(e.updatedAt),deliveries:Array.isArray(e.deliveries)?e.deliveries.map(e=>({id:String(e.id),registrationId:"string"==typeof e.registrationId?e.registrationId:null,topic:String(e.topic),environment:String(e.environment),status:String(e.status),apnsId:"string"==typeof e.apnsId?e.apnsId:null,responseCode:"number"==typeof e.responseCode?e.responseCode:null,reason:"string"==typeof e.reason?e.reason:null,responseTimestamp:rO(e.responseTimestamp),attempts:Number(e.attempts),durationMs:"number"==typeof e.durationMs?e.durationMs:null,createdAt:rO(e.createdAt),startedAt:rO(e.startedAt),finishedAt:rO(e.finishedAt)})):[]}}let rG={requestId:e6.string().min(1),editor:e6.record(e6.string(),e6.unknown())},rK={requestId:e6.string().min(1),presetId:e6.string().min(1)},rH=e6.discriminatedUnion("targetMode",[e6.object({...rG,targetMode:e6.literal("DEVICES"),registrationIds:e6.array(e6.string().min(1)).min(1)}),e6.object({...rG,targetMode:e6.literal("ALL")}),e6.object({...rG,targetMode:e6.literal("BROADCAST"),channelId:e6.string().min(1)}),e6.object({...rG,targetMode:e6.literal("DIRECT"),directToken:e6.string().min(1),directTokenEncoding:e6.enum(["HEX","BASE64"]).default("HEX"),directEnvironment:e6.enum(["SANDBOX","PRODUCTION"]).default("SANDBOX")})]),rV=e6.discriminatedUnion("targetMode",[e6.object({...rK,targetMode:e6.literal("DEVICES"),registrationIds:e6.array(e6.string().min(1)).min(1)}),e6.object({...rK,targetMode:e6.literal("ALL")}),e6.object({...rK,targetMode:e6.literal("BROADCAST"),channelId:e6.string().min(1)}),e6.object({...rK,targetMode:e6.literal("DIRECT"),directToken:e6.string().min(1),directTokenEncoding:e6.enum(["HEX","BASE64"]).default("HEX"),directEnvironment:e6.enum(["SANDBOX","PRODUCTION"]).default("SANDBOX")})]);function rW(e){return{requestId:e.requestId,editor:e.editor,targetMode:e.targetMode,registrationIds:"DEVICES"===e.targetMode?e.registrationIds:void 0,channelId:"BROADCAST"===e.targetMode?e.channelId:void 0,directToken:"DIRECT"===e.targetMode?e.directToken:void 0,directTokenEncoding:"DIRECT"===e.targetMode?e.directTokenEncoding:void 0,directEnvironment:"DIRECT"===e.targetMode?e.directEnvironment:void 0}}let rJ=e6.object({id:e6.string(),entryType:e6.enum(["CONSOLE","ANALYTICS","SEPARATOR"]),clientTime:e6.string(),receivedAt:e6.string(),deviceIp:e6.string().nullable(),message:e6.string().nullable(),level:e6.string().nullable(),category:e6.string().nullable(),eventName:e6.string().nullable(),eventKind:e6.string().nullable(),screenName:e6.string().nullable(),buildId:e6.string().nullable(),sessionId:e6.string().nullable(),attributes:e6.record(e6.string(),e6.unknown()),defaultParameters:e6.record(e6.string(),e6.unknown()),additionalParameters:e6.record(e6.string(),e6.unknown()),highlightColor:e6.string().nullable(),separatorKind:e6.string().nullable(),separatorName:e6.string().nullable()}),rz=e6.object({items:e6.array(rJ),nextCursor:e6.string().nullable(),matchingCount:e6.number().int().nonnegative(),totalCount:e6.number().int().nonnegative()}),rY=rz.extend({separator:rJ.nullable()}),rZ=e6.object({first:e6.number().int().min(1).max(500).default(200),after:e6.string().nullable().default(null)}),rQ=e6.object({field:e6.string().min(1),operator:e6.enum(["CONTAINS","DOES_NOT_CONTAIN","IS","IS_NOT","MATCHES_GLOB","MATCHES_REGEX","NO_REGEX_MATCH","IS_EMPTY","IS_NOT_EMPTY"]),value:e6.string().nullable().optional(),caseSensitive:e6.boolean().default(!1),sources:e6.array(e6.enum(["CONSOLE","ANALYTICS"])).optional()}),rX=e6.object({mode:e6.enum(["ALL","ANY"]),conditions:e6.array(rQ).min(1).max(100)}),r0={search:e6.string().min(1).nullable().optional(),searchMode:e6.enum(["TEXT","GLOB","REGEX"]).default("TEXT"),caseSensitive:e6.boolean().default(!1),quickFilters:e6.record(e6.string(),e6.array(e6.string()).max(500)).nullable().optional(),advancedFilter:rX.nullable().optional()},r1=rZ.extend(r0).refine(r6,{message:"At least one telemetry search filter is required"}),r2=rZ.extend(r0),r3=e6.object({scope:e6.literal("MATCHING"),...r0}).refine(r6,{message:"At least one telemetry search filter is required"}),r4=e6.union([e6.object({scope:e6.literal("IDS"),ids:e6.array(e6.string().min(1)).min(1).max(1e3)}),r3,e6.object({scope:e6.literal("ALL"),includeSeparators:e6.boolean().default(!1)}),e6.object({scope:e6.literal("BEFORE_LATEST_SEPARATOR"),includeSeparators:e6.boolean().default(!1)})]);function r6(e){return!!(e.search||Object.values(e.quickFilters??{}).some(e=>e.length)||e.advancedFilter?.conditions.length)}function r8(e,t){return{view:e,first:t.first,after:t.after,search:t.search,searchMode:t.searchMode??"TEXT",caseSensitive:t.caseSensitive??!1,quickFilters:t.quickFilters,advancedFilter:t.advancedFilter}}function r5(e,t,r){return[an({name:`get_${r.plural}`,title:`Get ${r.label}`,description:`Fetch the newest ${r.label.toLocaleLowerCase()} with cursor pagination.`,inputSchema:rZ,outputSchema:rz,annotations:i7,handler:r=>e.timeline(r8(t,r))}),an({name:`get_${r.singular}`,title:`Get ${r.singular.replaceAll("_"," ")}`,description:`Fetch one ${r.label.toLocaleLowerCase()} item by ID.`,inputSchema:e6.object({id:e6.string().min(1)}),outputSchema:e6.object({entry:rJ.nullable()}),annotations:i7,handler:async({id:r})=>({entry:await e.entry(r,t)})}),an({name:`search_${r.plural}`,title:`Search ${r.label}`,description:"Search with text, glob, regex, quick facets, or advanced filter conditions.",inputSchema:r1,outputSchema:rz,annotations:i7,handler:r=>e.timeline(r8(t,r))}),an({name:`get_${r.plural}_since_latest_separator`,title:`Get ${r.label} since latest separator`,description:"Fetch entries strictly newer than the latest global telemetry separator.",inputSchema:r2,outputSchema:rY,annotations:i7,handler:r=>e.timelineSinceLatestSeparator(r8(t,r))}),an({name:`get_${r.singular}_search_metadata`,title:`Get ${r.label} search metadata`,description:"Get searchable fields and current facet values.",inputSchema:e6.object({}),outputSchema:e6.object({fields:e6.array(e6.string()),facets:e6.record(e6.string(),e6.array(e6.string()))}),annotations:i7,handler:async()=>{let[r,i]=await Promise.all([e.fields(t),e.facets(t)]);return{fields:r,facets:i}}}),an({name:`clear_${r.plural}`,title:`Clear ${r.label}`,description:"Clear explicit IDs, matching entries, all entries, or entries before the latest separator.",inputSchema:r4,outputSchema:e6.object({view:e6.enum(["CONSOLE","ANALYTICS","UNIFIED"]),scope:e6.enum(["IDS","MATCHING","ALL","BEFORE_LATEST_SEPARATOR"]),deletedCount:e6.number().int().nonnegative()}),annotations:at,handler:async r=>{let i="MATCHING"===r.scope?r:null,a=await e.clearScoped({view:t,scope:r.scope,ids:"IDS"===r.scope?r.ids:null,includeSeparators:("ALL"===r.scope||"BEFORE_LATEST_SEPARATOR"===r.scope)&&r.includeSeparators,query:i?{search:i.search,searchMode:i.searchMode,caseSensitive:i.caseSensitive,quickFilters:i.quickFilters,advancedFilter:i.advancedFilter}:null});return{view:t,scope:r.scope,deletedCount:a}}})]}var r9=e.i(885418),r7=e.i(586589),ie=e.i(661983),it=e.i(504173),ir=e.i(518733);function ii(e,t,r=null){let i=[...t.volumes].filter(e=>e.monitored).sort((e,t)=>e.freeBytes-t.freeBytes||e.id.localeCompare(t.id))[0],n=i&&i.totalBytes>0?i.freeBytes/i.totalBytes*100:null,s=null===t.agent.disconnectedAt&&null!==t.agent.lastSeenAt&&Date.now()-t.agent.lastSeenAt.getTime()<=(0,a.agentOnlineWindowMs)(t.agent);return{agent:{id:t.agent.id,name:t.agent.name,hostname:t.agent.hostname,connected:s,diskTotalBytes:t.agent.diskTotalBytes,diskFreeBytes:t.agent.diskFreeBytes},codebase:{agentId:t.agent.id},disk:{enabled:t.enabled,status:t.status,pressureMode:t.pressureMode,manualPressureMode:t.manualPressureMode,automaticPressureMode:t.automaticPressureMode,lastReportedAt:t.lastReportedAt,lastError:t.lastError,warnings:[...t.warnings],monitoredVolumeId:i?.id??null,freeBytes:i?.freeBytes??null,totalBytes:i?.totalBytes??null,freeGiB:i?i.freeBytes/0x40000000:null,freePercent:n,usedPercent:null===n?null:100-n,effectiveThresholdBytes:i?.effectiveThresholdBytes??null,normalThresholdGiB:e.normalThresholdGiB,pressureThresholdGiB:e.pressureThresholdGiB,pollIntervalSeconds:e.pollIntervalSeconds,staleAfterSeconds:e.staleAfterSeconds,changeReason:r,volumes:t.volumes.map(e=>({...e}))}}}function ia(e){return{enabled:e.disk.enabled,status:e.disk.status,pressureMode:e.disk.pressureMode,lastError:e.disk.lastError,warnings:e.disk.warnings,monitoredVolumeId:e.disk.monitoredVolumeId}}function is(e){try{let t=JSON.parse(e??"[]");return Array.isArray(t)?t:[]}catch{return[]}}function io(e,t){if(!Number.isFinite(e)||e<=0||e>1e6)throw Error(`${t} must be a positive finite GiB value`);return e}class il{agentControl;constructor(e){this.agentControl=e,this.agentControl.registerCompletionObserver(e=>this.observeCompletion(e))}async settings(){let e=await (0,t1.getPrismaClient)(),t=await e.diskSpaceSettings.upsert({where:{id:"default"},create:{id:"default",normalThresholdGiB:r7.DEFAULT_DISK_SPACE_THRESHOLD_GIB,pressureThresholdGiB:r7.DEFAULT_DISK_SPACE_PRESSURE_THRESHOLD_GIB},update:{}});return{normalThresholdGiB:t.normalThresholdGiB,pressureThresholdGiB:t.pressureThresholdGiB,pollIntervalSeconds:r7.DISK_SPACE_POLL_INTERVAL_SECONDS,staleAfterSeconds:r7.DISK_SPACE_STALE_AFTER_SECONDS}}async updateSettings(e){let t=io(e.normalThresholdGiB,"Normal disk threshold"),r=io(e.pressureThresholdGiB,"Pressure disk threshold");if(r>=t)throw Error("Pressure disk threshold must be lower than the normal threshold");let i=await (0,t1.getPrismaClient)();for(let{agentId:e}of(await i.diskSpaceSettings.upsert({where:{id:"default"},create:{id:"default",normalThresholdGiB:t,pressureThresholdGiB:r},update:{normalThresholdGiB:t,pressureThresholdGiB:r}}),this.publish("settings","SETTINGS_UPDATED"),await i.agentDiskSpaceState.findMany({where:{enabled:!0},select:{agentId:!0}})))this.reconcileAgent(e);return this.settings()}async configuration(e){let t=await (0,t1.getPrismaClient)(),[r,i,a]=await Promise.all([t.agent.findUnique({where:{id:e}}),t.agentDiskSpaceState.findUnique({where:{agentId:e}}),t.worktree.findMany({where:{missingAt:null,codebase:{agentId:e}},select:{id:!0,folder:!0}})]);if(!r)throw Error("Agent not found");return{enabled:i?.enabled??!0,pollIntervalSeconds:r7.DISK_SPACE_POLL_INTERVAL_SECONDS,baseRepoDirectory:r.baseRepoDirectory,derivedDataLocationMode:r.derivedDataLocationMode,derivedDataPath:r.derivedDataPath,worktrees:a}}async report(e,t){let r=(0,r7.parseAgentDiskSpaceReport)(t),i=await (0,t1.getPrismaClient)(),[a,n]=await Promise.all([i.agent.findUnique({where:{id:e}}),i.worktree.findMany({where:{missingAt:null,codebase:{agentId:e}},include:{codebase:{select:{agentId:!0}}}})]);if(!a)throw Error("Agent not found");let s=new Date(r.observedAt),o=r.entries.map(e=>{let t=e.workspacePath?n.filter(t=>{var r,i;let a;return r=t.folder,i=e.workspacePath,i===(a="/"===r?r:r.replace(/\/+$/,""))||i.startsWith(`${a}/`)}).sort((e,t)=>t.folder.length-e.folder.length)[0]:null;return{...e,worktreeId:t?.id??null,worktreePath:t?(0,it.worktreeDisplayPath)(t.folder,a.baseRepoDirectory):null}});await i.agentDiskSpaceState.upsert({where:{agentId:e},create:{agentId:e,volumesJson:JSON.stringify(r.volumes),entriesJson:JSON.stringify(o),warningsJson:JSON.stringify(r.warnings),lastReportedAt:s,lastError:null},update:{volumesJson:JSON.stringify(r.volumes),entriesJson:JSON.stringify(o),warningsJson:JSON.stringify(r.warnings),lastReportedAt:s,lastError:null}}),this.publish(e,"REPORT_RECEIVED"),this.reconcileAgent(e)}async overview(){let e=await (0,t1.getPrismaClient)();await e.derivedDataCleanupLease.deleteMany({where:{jobId:null,expiresAt:{lte:new Date}}});let[t,r,i]=await Promise.all([this.settings(),e.agent.findMany({orderBy:{name:"asc"},include:{diskSpaceState:!0}}),e.derivedDataCleanupLease.findMany({select:{agentId:!0}})]),a=new Set(i.map(e=>e.agentId));return{settings:t,agents:r.map(e=>{let r=e.diskSpaceState,i=r?.enabled??!0,n=r?.manualPressureMode??!1,s=r?.automaticPressureMode??!1,o=r?.lastReportedAt??null,l=!o||Date.now()-o.getTime()>1e3*t.staleAfterSeconds,c=(n||s?t.pressureThresholdGiB:t.normalThresholdGiB)*0x40000000,u=is(r?.volumesJson),d=(0,r7.monitoredDiskSpaceVolumes)(u),p=d.some(e=>e.freeBytes<=0x40000000*t.pressureThresholdGiB),h=d.some(e=>e.freeBytes<c),m="IDLE";i?l?m="STALE":r?.lastError||0===u.length&&is(r?.warningsJson).length>0?m="ERROR":p?m="CRITICAL":a.has(e.id)?m="DELETING":n||s?m="PRESSURE":h&&(m="CLEANUP_REQUIRED"):m="DISABLED";let f=u.map(r=>{let o=(0,r7.isMonitoredDiskSpaceVolume)(r);return{...r,effectiveThresholdBytes:c,monitored:o,status:i?l?"STALE":o?r.freeBytes<=0x40000000*t.pressureThresholdGiB?"CRITICAL":a.has(e.id)&&r.freeBytes<c?"DELETING":n||s?"PRESSURE":r.freeBytes<c?"CLEANUP_REQUIRED":"IDLE":"IDLE":"DISABLED"}}),g=is(r?.warningsJson);return i&&!l&&u.length>0&&0===d.length&&g.push("No Derived Data volume was reported, so free space is not being monitored for this agent"),{agent:e,enabled:i,status:m,pressureMode:n?"MANUAL":s?"AUTOMATIC":"NORMAL",manualPressureMode:n,automaticPressureMode:s,lastReportedAt:o?.toISOString()??null,lastError:r?.lastError??null,warnings:g,volumes:f}})}}async agentView(e){let t=(await this.overview()).agents.find(t=>t.agent.id===e);if(!t)throw Error("Agent not found");return t}async snapshot(e,t=null){let r=await this.overview(),i=r.agents.find(t=>t.agent.id===e);if(!i)throw Error("Agent not found");return ii(r.settings,i,t)}async requestRefresh(e){let t=await this.agentView(e);if(!t.enabled)throw Error("Disk-space monitoring is disabled for this agent");let r=new Date().toISOString();return this.agentControl.requestDiskSpacePoll(e),{agentId:e,requestedAt:r,previousReportedAt:t.lastReportedAt}}async setMonitoring(e,t){let r=await (0,t1.getPrismaClient)();return await r.agent.findUniqueOrThrow({where:{id:e}}),await r.agentDiskSpaceState.upsert({where:{agentId:e},create:{agentId:e,enabled:t},update:{enabled:t,...!t?{manualPressureMode:!1,automaticPressureMode:!1}:{}}}),t||await r.derivedDataCleanupLease.deleteMany({where:{agentId:e,jobId:null}}),this.publish(e,"MONITORING_CHANGED"),this.agentControl.requestAgentConfigurationRefresh(e),this.agentView(e)}async setManualPressureMode(e,t){let r=await (0,t1.getPrismaClient)();return await r.agent.findUniqueOrThrow({where:{id:e}}),await r.agentDiskSpaceState.upsert({where:{agentId:e},create:{agentId:e,manualPressureMode:t},update:{manualPressureMode:t}}),this.publish(e,"MANUAL_PRESSURE_CHANGED"),this.reconcileAgent(e),this.agentView(e)}async assertWorktreeCanStart(e){let t=await (0,t1.getPrismaClient)();await t.derivedDataCleanupLease.deleteMany({where:{worktreeId:e,jobId:null,expiresAt:{lte:new Date}}});let[r,i]=await Promise.all([t.derivedDataCleanupLease.findUnique({where:{worktreeId:e}}),t.worktree.findUnique({where:{id:e},select:{codebase:{select:{agentId:!0}}}})]);if(r)throw Error("Derived Data cleanup is in progress for this worktree; try again shortly");i&&await this.assertAgentCanStart(i.codebase.agentId)}async assertAgentCanStart(e){let t=await (0,t1.getPrismaClient)(),[r,i]=await Promise.all([this.settings(),t.agentDiskSpaceState.findUnique({where:{agentId:e}})]);if(!(!i?.enabled||!i.lastReportedAt||i.lastError||Date.now()-i.lastReportedAt.getTime()>1e3*r.staleAfterSeconds)&&(0,r7.monitoredDiskSpaceVolumes)(is(i.volumesJson)).some(e=>e.freeBytes<=0x40000000*r.pressureThresholdGiB))throw Error(`New builds, plans, and sessions are paused because this agent has ${r.pressureThresholdGiB} GiB or less free disk space`)}subscribe(){return ie.agentEventBus.iterate(ie.DISK_SPACE_CHANGED_TOPIC)}async reconcileAgent(e){let t=await (0,t1.getPrismaClient)();await t.derivedDataCleanupLease.deleteMany({where:{jobId:null,expiresAt:{lte:new Date}}});let[r,i,n,s,o]=await Promise.all([this.settings(),t.agentDiskSpaceState.findUnique({where:{agentId:e}}),t.derivedDataLock.findMany({where:{agentId:e},select:{path:!0}}),t.derivedDataCleanupLease.findFirst({where:{agentId:e}}),t.agent.findUnique({where:{id:e}})]);if(!i?.enabled||!i.lastReportedAt||i.lastError||s||!o||null!==o.disconnectedAt||null===o.lastSeenAt||Date.now()-o.lastSeenAt.getTime()>(0,a.agentOnlineWindowMs)(o)||!is(o.capabilitiesJson).includes(r9.BUILD_DATA_DELETE_JOB_KIND)||Date.now()-i.lastReportedAt.getTime()>1e3*r.staleAfterSeconds)return;let l=is(i.entriesJson),c=is(i.volumesJson),u=(0,r7.monitoredDiskSpaceVolumes)(c),d=l.map(e=>e.worktreeId).filter(e=>!!e),p=await (0,ir.executingResourcesByWorktree)(d),h=new Set(n.map(e=>e.path));l=l.filter(e=>"PROJECT"===e.kind&&!!e.worktreeId&&!h.has(e.path)&&(p.get(e.worktreeId)?.length??0)===0);let m=0x40000000*r.normalThresholdGiB,f=0x40000000*r.pressureThresholdGiB,g=u.filter(e=>e.freeBytes<m),y=e=>e.capacityId??e.id,w=new Map(c.map(e=>[e.id,y(e)])),v=e=>l.some(t=>w.get(t.volumeId)===y(e)),k=i.automaticPressureMode;if(!i.manualPressureMode){let r=g.length>0&&g.some(e=>!v(e)),a=k&&(0===g.length||g.every(e=>v(e)));r?k=!0:a&&(k=!1),k!==i.automaticPressureMode&&(await t.agentDiskSpaceState.update({where:{agentId:e},data:{automaticPressureMode:k}}),this.publish(e,"AUTOMATIC_PRESSURE_CHANGED"))}let E=i.manualPressureMode||k?f:m,S=new Set(u.filter(e=>e.freeBytes<E).map(y)),I=l.filter(e=>S.has(w.get(e.volumeId)??"")).sort((e,t)=>new Date(e.modifiedAt).getTime()-new Date(t.modifiedAt).getTime()||e.path.localeCompare(t.path))[0];if(!I?.worktreeId)return;try{await t.derivedDataCleanupLease.create({data:{worktreeId:I.worktreeId,agentId:e,path:I.path,source:"AUTOMATIC",expiresAt:new Date(Date.now()+6e5)}})}catch{return}let A=await (0,ir.executingResourcesByWorktree)([I.worktreeId]);if((A.get(I.worktreeId)?.length??0)>0){await t.derivedDataCleanupLease.deleteMany({where:{worktreeId:I.worktreeId,jobId:null}}),this.publish(e,"CLEANUP_SKIPPED");return}try{var x;let r=await this.agentControl.createJob({agentId:e,kind:r9.BUILD_DATA_DELETE_JOB_KIND,payload:{source:"AUTOMATIC",targets:[{path:I.path,rootPath:I.rootPath,name:I.name,kind:I.kind,worktreeId:I.worktreeId,worktreePath:I.worktreePath}]},idempotencyKey:`disk-space:auto:${(x=I.path,(0,b.createHash)("sha256").update(e).update("\0").update(x).digest("base64url"))}:${(0,b.randomUUID)()}`,timeoutSeconds:600,visibility:"SYSTEM"});await t.derivedDataCleanupLease.update({where:{worktreeId:I.worktreeId},data:{jobId:r.id}}),this.publish(e,"CLEANUP_STARTED")}catch(r){await t.derivedDataCleanupLease.deleteMany({where:{worktreeId:I.worktreeId}}),await t.agentDiskSpaceState.update({where:{agentId:e},data:{lastError:r instanceof Error?r.message:String(r)}}),this.publish(e,"CLEANUP_START_FAILED")}}async observeCompletion(e){if(e.kind!==r9.BUILD_DATA_DELETE_JOB_KIND)return;let t="USER",r=[];try{let i=(0,r9.buildDataDeletePayload)(JSON.parse(e.payloadJson));t=i.source,r=i.targets}catch{}let i=await (0,t1.getPrismaClient)(),a=await i.derivedDataCleanupLease.deleteMany({where:{jobId:e.id}});if("AUTOMATIC"===t&&"SUCCEEDED"!==e.status&&await i.agentDiskSpaceState.updateMany({where:{agentId:e.agentId},data:{lastError:e.error||"Automatic Derived Data cleanup failed"}}),a.count||"AUTOMATIC"===t){let i=[];if("AUTOMATIC"===t&&e.resultJson)try{i=(0,r9.parseBuildDataDeleteResult)(JSON.parse(e.resultJson)).deleted}catch{}this.publish(e.agentId,"CLEANUP_COMPLETED","AUTOMATIC"===t?{jobId:e.id,status:e.status,source:t,error:e.error,targets:r,deleted:i}:null),this.agentControl.requestDiskSpacePoll(e.agentId)}}publish(e,t,r=null){ie.agentEventBus.publish(ie.DISK_SPACE_CHANGED_TOPIC,{diskSpaceChanged:e,diskSpaceChange:{id:(0,b.randomUUID)(),reason:t,cleanup:r}}),ie.agentEventBus.publish(ie.SIDEBAR_STATUS_CHANGED_TOPIC,{sidebarStatusChanged:!0}),ie.agentEventBus.publish(ie.POLLING_CHANGED_TOPIC,{pollingOperationChanged:`agent-disk-space:${e}`})}}let ic=e6.object({normalThresholdGiB:e6.number(),pressureThresholdGiB:e6.number(),pollIntervalSeconds:e6.number().int(),staleAfterSeconds:e6.number().int()}),iu=e6.object({id:e6.string(),name:e6.string(),hostname:e6.string(),connected:e6.boolean(),diskTotalBytes:e6.number().nullable(),diskFreeBytes:e6.number().nullable()}),id=e6.enum(["DISABLED","STALE","IDLE","CLEANUP_REQUIRED","DELETING","PRESSURE","CRITICAL","ERROR"]),ip=e6.object({id:e6.string(),capacityId:e6.string(),totalBytes:e6.number(),freeBytes:e6.number(),roles:e6.array(e6.enum(["MAIN","BASE_REPO","DERIVED_DATA"])),paths:e6.array(e6.string()),status:id,effectiveThresholdBytes:e6.number(),monitored:e6.boolean()}),ih=e6.object({enabled:e6.boolean(),status:id,pressureMode:e6.enum(["NORMAL","MANUAL","AUTOMATIC"]),manualPressureMode:e6.boolean(),automaticPressureMode:e6.boolean(),lastReportedAt:e6.string().nullable(),lastError:e6.string().nullable(),warnings:e6.array(e6.string()),monitoredVolumeId:e6.string().nullable(),freeBytes:e6.number().nullable(),totalBytes:e6.number().nullable(),freeGiB:e6.number().nullable(),freePercent:e6.number().nullable(),usedPercent:e6.number().nullable(),effectiveThresholdBytes:e6.number().nullable(),normalThresholdGiB:e6.number(),pressureThresholdGiB:e6.number(),pollIntervalSeconds:e6.number().int(),staleAfterSeconds:e6.number().int(),changeReason:e6.string().nullable(),volumes:e6.array(ip)}),im=e6.object({agent:iu,codebase:e6.object({agentId:e6.string()}),disk:ih}),ig=e6.object({agentId:e6.string().min(1)}),iy=e6.object({name:e6.string().min(1),description:e6.string().default(""),script:e6.string().min(1),targetKind:e6.enum(["ANY_AGENT_HOME","SPECIFIC_AGENT_HOME","ANY_WORKTREE","REPOSITORY_WORKTREE"]),targetAgentId:e6.string().nullable().optional(),targetRepositoryId:e6.string().nullable().optional(),restartPolicy:e6.enum(["NEVER","ON_FAILURE","ALWAYS"]).default("NEVER"),restartLimit:e6.number().int().min(0).max(100).default(3),quickActionEnabled:e6.boolean().default(!1),quickActionIconKey:e6.string().default("terminal"),quickActionButtonVariant:e6.string().default("default"),notificationsEnabled:e6.boolean().default(!0)}),iw="WORKFLOW_AUTOMATION",ib={actor:"workflow",ipAddress:null},iv=e6.object({owner:e6.string().min(1),name:e6.string().min(1),number:e6.number().int().positive()}),ik=e6.object({projectId:e6.string().min(1),iid:e6.number().int().positive()}),iE=e6.object({issueKey:e6.string().min(1)}),iS=e6.object({format:e6.string().min(1),value:e6.string()}),iI=e6.enum(["JQL","BOARD"]);var iA=e.i(807237);let ix=e6.object({runId:e6.string().min(1)}),i_=e6.object({kind:e6.string().min(1),worktreeId:e6.string().min(1),jiraIssueKey:e6.string().nullable().optional(),provider:e6.string().min(1),model:e6.string().min(1),effort:e6.string().nullable().optional(),webSearchEnabled:e6.boolean().nullable().optional(),prompt:e6.string().min(1),attachmentIds:e6.array(e6.string().min(1)).nullable().optional(),draftId:e6.string().nullable().optional(),sourcePlanId:e6.string().nullable().optional(),parentRunId:e6.string().nullable().optional(),followUpMode:e6.string().nullable().optional(),contextMode:e6.string().nullable().optional()});var iC=e.i(497800),iR=e.i(835544);function iT(e,t){let r=new Set([...e.nodes.map(({id:e})=>e),...e.triggers.map(({id:e})=>e)]);for(let e=1;;e+=1){let i=`${t}-${e}`;if(!r.has(i))return i}}function iD(e,t){return e.nodes.find(e=>e.id===t)??e.triggers.find(e=>e.id===t)}function iN(e){return(0,iR.isChoiceTriggerKind)(e.kind)?(0,iC.workflowTriggerChoices)(e.config).map(({key:e})=>e):(0,iR.workflowStaticSourceHandles)(e.kind)}function iO(e,t){if(t.config)return t.config;if(!t.configPatch)return e;let r={...e};for(let[e,i]of Object.entries(t.configPatch))null===i?delete r[e]:r[e]=i;return r}function iP(e,t){let r=iD(e,t.source);if(!r)throw Error(`${t.source} is not in this workflow`);if(!e.nodes.some(({id:e})=>e===t.target))throw Error(`${t.target} is not a step — triggers cannot have incoming connections`);let i=iN(r),a=t.sourceHandle??i[0];if(!a)throw Error(`${t.source} offers no connectors yet — a choice trigger needs its options set first`);if(!i.includes(a))throw Error(`${t.source} has no ${a} connector; it offers ${i.join(", ")}`);let n=t.targetHandle??"input",s=e.edges.find(e=>e.source===t.source&&e.target===t.target&&e.sourceHandle===a);if(s)return{definition:e,edgeId:s.id};let o=function(e){let t=new Set(e.edges.map(({id:e})=>e));for(let e=1;;e+=1){let r=`edge-${e}`;if(!t.has(r))return r}}(e);return{definition:{...e,edges:[...e.edges,{id:o,source:t.source,target:t.target,sourceHandle:a,targetHandle:n}]},edgeId:o}}let iL={workflow:[{name:"id",description:"Workflow definition id"},{name:"name",description:"Workflow name"},{name:"runId",description:"Current run id"},{name:"startedAt",description:"Run start timestamp"},{name:"trigger",description:"Trigger that started the run"}],repo:[{name:"id",description:"Repository id"},{name:"githubId",description:"GitHub repository id"},{name:"owner",description:"Repository owner / organization"},{name:"name",description:"Repository name"},{name:"url",description:"Repository URL"},{name:"canonicalOrigin",description:"Normalized repository origin"},{name:"displayOrigin",description:"Human-readable repository origin"},{name:"defaultBranch",description:"Repository default branch"}],codebase:[{name:"id",description:"Codebase id"},{name:"agentId",description:"Owning agent id"},{name:"folder",description:"Codebase filesystem path"},{name:"branch",description:"Current branch"},{name:"headSha",description:"HEAD commit SHA"},{name:"dirty",description:"Whether the working tree has changes"},{name:"branches",description:"Local and remote Git branches"},{name:"branchesTruncated",description:"Whether branch results were truncated"},{name:"stashes",description:"Git stashes"},{name:"stashesTruncated",description:"Whether stash results were truncated"},{name:"remoteBranches",description:"Known remote branches"}],agent:[{name:"id",description:"Owning agent id"},{name:"name",description:"Agent display name"},{name:"hostname",description:"Agent hostname"},{name:"connected",description:"Whether the agent is connected"},{name:"diskTotalBytes",description:"Root disk capacity in bytes"},{name:"diskFreeBytes",description:"Available disk space in bytes"},{name:"memoryFreeBytes",description:"Available memory in bytes"}],disk:[{name:"enabled",description:"Whether disk monitoring is enabled"},{name:"status",description:"Current disk monitor status"},{name:"pressureMode",description:"Normal, manual, or automatic pressure mode"},{name:"manualPressureMode",description:"Whether manual pressure mode is enabled"},{name:"automaticPressureMode",description:"Whether automatic pressure mode is active"},{name:"lastReportedAt",description:"Timestamp of the latest accepted disk report"},{name:"lastError",description:"Latest monitor or cleanup error"},{name:"warnings",description:"Current disk report warnings"},{name:"monitoredVolumeId",description:"Least-free monitored Derived Data volume id"},{name:"freeBytes",description:"Monitored Derived Data free bytes"},{name:"totalBytes",description:"Monitored Derived Data total bytes"},{name:"freeGiB",description:"Monitored Derived Data free space in GiB"},{name:"freePercent",description:"Monitored Derived Data free percentage"},{name:"usedPercent",description:"Monitored Derived Data used percentage"},{name:"effectiveThresholdBytes",description:"Current cleanup threshold in bytes"},{name:"normalThresholdGiB",description:"Global normal threshold in GiB"},{name:"pressureThresholdGiB",description:"Global pressure threshold in GiB"},{name:"pollIntervalSeconds",description:"Agent disk report cadence"},{name:"staleAfterSeconds",description:"Age at which a report is stale"},{name:"changeReason",description:"Internal reason for the monitor event"},{name:"volumes",description:"All reported volumes and their monitor status"}],cleanup:[{name:"jobId",description:"Automatic cleanup agent job id"},{name:"status",description:"Automatic cleanup terminal status"},{name:"source",description:"Cleanup source"},{name:"error",description:"Cleanup error, if any"},{name:"targets",description:"Derived Data entries selected for cleanup"},{name:"deleted",description:"Derived Data entries reported deleted"}],command:[{name:"id",description:"Command run id"},{name:"commandId",description:"Saved command definition id"},{name:"name",description:"Command display name"},{name:"status",description:"Command run status"},{name:"exitCode",description:"Command process exit code"},{name:"signal",description:"Command termination signal"},{name:"error",description:"Command failure reason"},{name:"finishedAt",description:"Command completion timestamp"}],skill:[{name:"id",description:"Skill id"},{name:"groupId",description:"Skill group id"}],skillSync:[{name:"id",description:"Skill sync run id"},{name:"kind",description:"Skill sync kind"},{name:"status",description:"Skill sync status"},{name:"error",description:"Skill sync failure reason"},{name:"conflictCount",description:"Unresolved conflict count"},{name:"conflicts",description:"Unresolved skill conflicts"},{name:"updatedAt",description:"Skill sync update timestamp"},{name:"finishedAt",description:"Skill sync completion timestamp"}],buildData:[{name:"id",description:"Build-data collection id"},{name:"status",description:"Collection status"},{name:"finishedAt",description:"Collection completion timestamp"},{name:"totalBytes",description:"Total discovered bytes"},{name:"entryCount",description:"Discovered entry count"},{name:"successfulAgentCount",description:"Agents that completed collection successfully"}],signingProfile:[{name:"id",description:"Signing profile id"},{name:"uuid",description:"Provisioning profile UUID"},{name:"name",description:"Provisioning profile name"},{name:"expiresAt",description:"Provisioning profile expiry"},{name:"expired",description:"Whether the profile is expired"}],device:[{name:"id",description:"iOS device id"},{name:"udid",description:"Device UDID"},{name:"name",description:"Device display name"},{name:"product",description:"Device product identifier"},{name:"osVersion",description:"Device OS version"},{name:"status",description:"Device registration status"},{name:"error",description:"Device registration failure reason"},{name:"updatedAt",description:"Device update timestamp"}],pushBatch:[{name:"id",description:"Push-notification batch id"},{name:"status",description:"Push batch status"},{name:"targetMode",description:"Push batch target mode"},{name:"deliveryCount",description:"Push delivery count"},{name:"updatedAt",description:"Push batch update timestamp"}],ticket:[{name:"key",description:"Jira issue key (e.g. AIDE-42)"},{name:"projectKey",description:"Jira project key"},{name:"title",description:"Issue summary / title"},{name:"type",description:"Issue type (Bug, Story, …)"},{name:"status",description:"Workflow status name"},{name:"statusId",description:"Workflow status id"},{name:"statusCategory",description:"Status category (To Do, Done, …)"},{name:"assignee",description:"Assigned user"},{name:"assigneeAccountId",description:"Assigned Jira account id"},{name:"labels",description:"Issue labels"},{name:"sprintNames",description:"Sprints containing the issue"},{name:"url",description:"Jira issue URL"}],changelog:[{name:"id",description:"Jira webhook changelog id"},{name:"items",description:"Fields changed in the Jira update"}],pr:[{name:"id",description:"Pull request id"},{name:"number",description:"Pull request number"},{name:"state",description:"Open / closed / merged state"},{name:"merged",description:"Whether the pull request was merged"},{name:"title",description:"Pull request title"},{name:"url",description:"Pull request URL"},{name:"labels",description:"Pull request labels"},{name:"isDraft",description:"Whether the pull request is a draft"},{name:"headBranch",description:"Pull request head branch"},{name:"headRefName",description:"Pull request head ref"},{name:"headSha",description:"Pull request head commit SHA"},{name:"baseBranch",description:"Pull request base branch"},{name:"reviewDecision",description:"Latest review decision"},{name:"pipelineStatus",description:"Combined pull request check status"},{name:"unresolvedReviewThreadCount",description:"Number of unresolved pull request review threads"},{name:"pipelines",description:"CI pipelines linked to the pull request"},{name:"reviewThreads",description:"Pull request review threads"},{name:"mergeable",description:"Pull request mergeability"},{name:"repositoryGithubId",description:"GitHub repository id"},{name:"repositoryNameWithOwner",description:"GitHub owner and repository name"},{name:"jiraKey",description:"Jira key linked to the pull request"},{name:"unresolvedThreads",description:"Unresolved review threads"}],worktree:[{name:"id",description:"Worktree id"},{name:"branch",description:"Worktree branch"},{name:"baseBranch",description:"Base branch the work targets"},{name:"path",description:"Filesystem path"},{name:"headSha",description:"Worktree HEAD commit SHA"},{name:"pushStatus",description:"Push readiness status"},{name:"upstream",description:"Tracked upstream branch"},{name:"syncState",description:"Relationship to the tracked branch"},{name:"ahead",description:"Commits ahead of upstream"},{name:"behind",description:"Commits behind upstream"},{name:"baseAhead",description:"Commits ahead of the base branch"},{name:"baseBehind",description:"Commits behind the base branch"},{name:"commits",description:"Commits on the branch"},{name:"changes",description:"Pending file changes"},{name:"branchChanges",description:"Files changed from the base branch"},{name:"commitsTruncated",description:"Whether commit results were truncated"},{name:"changesTruncated",description:"Whether pending changes were truncated"},{name:"branchChangesTruncated",description:"Whether branch change results were truncated"},{name:"dirty",description:"Whether the working tree has changes"},{name:"branches",description:"Local and remote Git branches"},{name:"branchesTruncated",description:"Whether branch results were truncated"},{name:"stashes",description:"Git stashes"},{name:"stashesTruncated",description:"Whether stash results were truncated"},{name:"rebaseInProgress",description:"Whether a rebase is in progress"},{name:"hasConflicts",description:"Whether Git reports conflicts"},{name:"conflicted",description:"Whether an inspection found conflicts"},{name:"conflicts",description:"Conflicting files"},{name:"missingAt",description:"When the worktree was found missing"},{name:"dirtySince",description:"When the worktree became dirty"},{name:"autoSync",description:"Persistent Auto Sync configuration and current state"},{name:"autoMerge",description:"Persistent Auto Merge configuration and current state"}],pipeline:[{name:"id",description:"CI pipeline id"},{name:"runId",description:"CI run id"},{name:"workflowId",description:"CI workflow id"},{name:"name",description:"CI workflow name"},{name:"displayTitle",description:"CI run display title"},{name:"status",description:"Run status"},{name:"conclusion",description:"Run conclusion"},{name:"headBranch",description:"Branch built by the CI run"},{name:"headSha",description:"Commit built by the CI run"},{name:"pullRequests",description:"Pull requests linked to the CI run"},{name:"url",description:"CI run URL"},{name:"failedJobs",description:"Failed jobs"},{name:"jobs",description:"Jobs in the CI run"},{name:"checkSuiteId",description:"GitHub check suite id"},{name:"runNumber",description:"GitHub Actions run number"},{name:"runAttempt",description:"GitHub Actions run attempt"},{name:"jiraKey",description:"Jira key inferred from the run"}],build:[{name:"id",description:"Build id"},{name:"status",description:"Build status"},{name:"action",description:"Build action"},{name:"error",description:"Build error, if any"},{name:"artifactDirectory",description:"Build artifact directory"},{name:"testSummary",description:"Test result summary"},{name:"tests",description:"Individual test results"},{name:"coverageSummary",description:"Coverage summary"},{name:"coverageFiles",description:"Per-file coverage results"},{name:"changedCoverageFiles",description:"Coverage for files changed on the branch"},{name:"artifacts",description:"Exported build artifacts"},{name:"exportId",description:"Build export id"}],run:[{name:"id",description:"Agent run id"},{name:"kind",description:"Run kind (PLAN / SESSION)"},{name:"status",description:"Run status"},{name:"phase",description:"Run phase"},{name:"origin",description:"Run origin"},{name:"provider",description:"AI provider"},{name:"model",description:"AI model"},{name:"branch",description:"Branch used by the run"},{name:"finalOutput",description:"Final output text"},{name:"error",description:"Run error, if any"},{name:"usage",description:"Token usage and cost"},{name:"questions",description:"Questions asked by the run"},{name:"events",description:"Run events"},{name:"links",description:"Resources linked to the run"}],steps:[{name:"status",description:"Step completion status"},{name:"output",description:"Step output payload"},{name:"answer",description:"Human answer for the step"},{name:"snapshotId",description:"Captured snapshot id"},{name:"items",description:"Items produced for iteration"},{name:"commandRunId",description:"Command run id"},{name:"displayNumber",description:"Resource display number"},{name:"matches",description:"Ordered regex matches emitted by a command step"},{name:"latestMatch",description:"Latest regex match emitted by a command step"}],comment:[{name:"id",description:"Comment id"},{name:"body",description:"Comment body"},{name:"author",description:"Comment author"}],push:[{name:"ref",description:"Pushed Git ref"},{name:"before",description:"Commit before the push"},{name:"after",description:"Commit after the push"}],job:[{name:"id",description:"Job id"},{name:"name",description:"Job name"},{name:"status",description:"Job status"},{name:"url",description:"Job URL"},{name:"runAttempt",description:"Workflow run attempt"}]},iB=new Map(Object.entries(iL).flatMap(([e,t])=>t.map(t=>[`${e}.${t.name}`,t.description])));function iU(e){return e.split(".")[0]??e}let ij=e6.object({workflowId:e6.string().min(1).describe("Workflow id.")}),iM=e6.object({x:e6.number(),y:e6.number()}).describe("Canvas position. Presentation only — omit it and a sensible spot is chosen."),iq=e6.record(e6.string(),e6.unknown()).describe("Config object for this kind. Call describe_workflow_kind for its schema. A value may be a constant, a session binding `{source:'SESSION',path:'ticket.key'}`, or a string with `{{ticket.key}}` interpolation."),i$=e6.array(e6.string()).max(100).describe("Extra session paths this step guarantees, on top of what its kind always provides. Required when a step writes to a config-chosen path — e.g. a CONTROL_SET_VARIABLE with `path: 'checks.ready'` must declare ['checks.ready'], or a later step binding it fails validation with REQUIREMENT_UNSATISFIED."),iF=e6.array(e6.string()).max(100).describe("Extra session paths this step demands, on top of its kind's own. Publishing fails unless every trigger that reaches the step guarantees them."),iG=e6.object({severity:e6.enum(["ERROR","WARNING"]),code:e6.string(),message:e6.string(),nodeId:e6.string().nullable(),triggerId:e6.string().nullable(),path:e6.string().nullable()}),iK=e6.object({workflowId:e6.string(),definition:e6.unknown().describe("The saved draft definition."),valid:e6.boolean().describe("Whether the draft would publish. Warnings do not block."),diagnostics:e6.array(iG),nodeId:e6.string().nullable().describe("Id of a step this call created."),triggerId:e6.string().nullable().describe("Id of a trigger this call created."),edgeId:e6.string().nullable().describe("Id of a connection this call created.")}),iH=e6.object({id:e6.string(),name:e6.string(),description:e6.string(),enabled:e6.boolean(),overlapPolicy:e6.string(),overlapScope:e6.string(),maxConcurrentRuns:e6.number(),completionNotificationsEnabled:e6.boolean(),exclusiveWorktree:e6.boolean(),worktreeConcurrency:e6.enum(["EXCLUSIVE","NON_EXCLUSIVE","EXCLUDED"]),blocksGitOperations:e6.boolean(),activeVersionId:e6.string().nullable(),draftSchemaVersion:e6.number(),quickActionKind:e6.enum(["STANDARD","MERGE_CONFLICT","GITHUB_ACTIONS","NONE"]),archivedAt:e6.string().nullable(),versionCount:e6.number(),runCount:e6.number(),createdAt:e6.string().nullable(),updatedAt:e6.string().nullable()}),iV=e6.object({id:e6.string(),displayNumber:e6.number(),workflowId:e6.string(),versionId:e6.string(),parentRunId:e6.string().nullable(),triggerKind:e6.string(),triggerSubjectKey:e6.string(),triggerPayload:e6.unknown(),status:e6.string(),phase:e6.string(),generation:e6.number(),sessionData:e6.unknown(),blockedReason:e6.string().nullable(),error:e6.string().nullable(),attemptCount:e6.number(),eventCount:e6.number(),queuedAt:e6.string().nullable(),startedAt:e6.string().nullable(),pausedAt:e6.string().nullable(),finishedAt:e6.string().nullable(),updatedAt:e6.string().nullable()}),iW=e6.object({id:e6.string(),runId:e6.string(),attemptId:e6.string().nullable(),sequence:e6.number(),type:e6.string(),message:e6.string(),detail:e6.unknown(),createdAt:e6.string().nullable()}),iJ=e6.object({batchId:e6.string(),runId:e6.string().nullable(),status:e6.string(),createdAt:e6.string().nullable(),questions:e6.array(e6.object({id:e6.string(),header:e6.string().nullable(),prompt:e6.string(),multiSelect:e6.boolean(),allowCustom:e6.boolean(),options:e6.array(e6.object({label:e6.string(),description:e6.string().nullable()}))}))}),iz={readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0};function iY(e,t){return!t||e.toLowerCase().includes(t.toLowerCase())}async function iZ(e,t){let r=await e().get(t);if(!r)throw Error(`Workflow ${t} was not found`);return(0,iC.parseWorkflowDefinition)(JSON.parse(r.draftDefinitionJson))}async function iQ(e,t,r,i={}){let a=e();await a.saveDraft({id:t,definition:r});let{valid:n,diagnostics:s}=await a.validateDraft(t);return{workflowId:t,definition:re(r),valid:n,diagnostics:s.map(e=>({severity:e.severity,code:e.code,message:e.message,nodeId:e.nodeId??null,triggerId:e.triggerId??null,path:e.path??null})),nodeId:i.nodeId??null,triggerId:i.triggerId??null,edgeId:i.edgeId??null}}function iX(e){let t=iC.WORKFLOW_TRIGGER_CATALOG.find(t=>t.kind===e);if(!t)throw Error(`Unknown trigger kind ${e}`);return t}var i0=e.i(119909);let i1=e6.object({id:e6.string().min(1)}),i2=e6.object({worktreeId:e6.string().min(1),requestId:e6.string().min(1)}),i3=e6.object({mode:e6.enum(["NEW","EXISTING","TICKET"]),branchName:e6.string().nullable().optional(),ticketKey:e6.string().nullable().optional(),baseBranch:e6.string().min(1)}),i4=e6.object({worktreeIds:e6.array(e6.string().min(1)).max(500),action:e6.enum(i0.WORKTREE_PREPARATION_ACTIONS),requestId:e6.string().min(1)}),i6=e6.object({id:e6.string(),kind:e6.enum(["WRITE","DELETE","ASSUME_UNCHANGED"]),path:e6.string(),contentSha256:e6.string().nullable(),byteCount:e6.number().int().nonnegative().nullable(),definitionHash:e6.string()}),i8=e6.object({repositories:e6.array(e6.object({repository:e6.object({id:e6.string(),name:e6.string(),canonicalOrigin:e6.string(),displayOrigin:e6.string()}),preparations:e6.array(i6),worktrees:e6.array(e6.object({worktree:e6.object({id:e6.string(),codebaseId:e6.string(),folder:e6.string(),relativePath:e6.string(),branch:e6.string().nullable(),baseBranch:e6.string().nullable(),primary:e6.boolean(),availability:e6.string(),missingAt:e6.string().nullable()}),agent:e6.object({id:e6.string(),name:e6.string(),hostname:e6.string(),version:e6.string()}),supported:e6.boolean(),unsupportedReason:e6.string().nullable(),overallState:e6.string(),statuses:e6.array(e6.object({preparationId:e6.string(),kind:e6.enum(["WRITE","DELETE","ASSUME_UNCHANGED"]),path:e6.string(),definitionHash:e6.string(),state:e6.string(),message:e6.string().nullable(),checkedAt:e6.string().nullable()})),activeJob:e6.object({id:e6.string(),status:e6.string()}).nullable()}))}))}),i5=e6.object({worktreeId:e6.string(),state:e6.string(),conflictWorkflowId:e6.string().nullable(),conflictWorkflowChoice:e6.string().nullable(),lastError:e6.string().nullable(),pauseReason:e6.string().nullable(),lastSyncedAt:e6.string().nullable(),updatedAt:e6.string()}),i9=e6.object({worktreeId:e6.string(),state:e6.string(),repositoryNameWithOwner:e6.string(),pullRequestNumber:e6.number().int(),mergeMethod:e6.enum(["MERGE","REBASE","SQUASH"]),commitHeadline:e6.string(),commitBody:e6.string(),authorEmail:e6.string().nullable(),deleteWorktree:e6.boolean(),moveTicketToDone:e6.boolean(),ticketKey:e6.string().nullable(),lastError:e6.string().nullable(),updatedAt:e6.string()}),i7={readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},ae={readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},at={readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},ar={...i7,openWorldHint:!0},ai={...ae,openWorldHint:!0},aa={...at,openWorldHint:!0};function an(e){return{name:e.name,title:e.title,description:e.description,inputSchema:e.inputSchema,outputSchema:e.outputSchema,annotations:e.annotations??i7,invoke:async t=>{let r=e.inputSchema.parse(t);return e.outputSchema.parse(await e.handler(r))}}}function as(e){return{id:e.id,name:e.name,source:"BUILTIN",transport:null,url:null,error:null,tools:e.tools.map(e=>({name:e.name,title:e.title,description:e.description,inputSchema:I.toJSONSchema(e.inputSchema),outputSchema:I.toJSONSchema(e.outputSchema),annotations:e.annotations})),children:e.children.map(as)}}function ao(e){if(!e||"object"!=typeof e||Array.isArray(e))throw Error("Built-in tool output must be a JSON object");return{content:[{type:"text",text:JSON.stringify(e,null,2)}],structuredContent:e}}class al{groups;indexed;byName;groupIds;constructor(e){this.groups=e,this.indexed=function e(t){return t.flatMap(t=>[...t.tools.map(e=>({groupId:t.id,definition:e})),...e(t.children)])}(e),this.byName=new Map,this.groupIds=new Set;const t=e=>{if(this.groupIds.has(e.id))throw Error(`Duplicate built-in tool group id: ${e.id}`);this.groupIds.add(e.id),e.children.forEach(t)};for(const r of(e.forEach(t),this.indexed)){if(this.byName.has(r.definition.name))throw Error(`Duplicate built-in MCP tool name: ${r.definition.name}`);this.byName.set(r.definition.name,r)}}definitions(){return this.indexed.map(({definition:e})=>e)}catalog(){return this.groups.map(as)}hasGroup(e){return this.groupIds.has(e)}groupIdForName(e){return this.byName.get(e)?.groupId??null}async call(e,t,r){let i=this.byName.get(t);if(!i||i.groupId!==e)throw Error(`Unknown built-in tool: ${t}`);return ao(await i.definition.invoke(r))}async callByName(e,t){let r=this.byName.get(e);if(!r)throw Error(`Unknown built-in tool: ${e}`);return ao(await r.definition.invoke(t))}}function ac(e){return{...e,startedAt:e.startedAt.toISOString(),finishedAt:e.finishedAt?.toISOString()??null}}class au{async clear(){return(await (0,t1.getPrismaClient)()).toolCallAudit.deleteMany({where:{resultStatus:{not:"RUNNING"}}})}async execute(e,t){var r;let i,a,n=await (0,t1.getPrismaClient)(),s=(0,b.randomUUID)(),o=new Date;await n.toolCallAudit.create({data:{id:s,correlationId:e.correlationId,caller:e.caller,source:e.source,groupId:e.groupId,toolName:e.toolName,argumentsSha256:(r=e.arguments,(0,b.createHash)("sha256").update(JSON.stringify((a=e=>null===e||"string"==typeof e||"boolean"==typeof e?e:"number"==typeof e?Number.isFinite(e)?e:String(e):"bigint"==typeof e?e.toString():Array.isArray(e)?e.map(a):e instanceof Date?e.toISOString():e&&"object"==typeof e?Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,a(t)])):String(e))(r))).digest("hex")),resultStatus:"RUNNING",startedAt:o}});try{i=await t()}catch(t){let e=new Date;throw await n.toolCallAudit.update({where:{id:s},data:{resultStatus:"FAILED",durationMs:Math.max(0,e.getTime()-o.getTime()),finishedAt:e}}).catch(()=>void 0),ie.agentEventBus.publish(ie.TOOL_CALL_AUDIT_CHANGED_TOPIC,{toolCallAuditChanged:{id:s}}),t}let l=new Date,c=!1;try{await n.toolCallAudit.update({where:{id:s},data:{resultStatus:"SUCCEEDED",durationMs:Math.max(0,l.getTime()-o.getTime()),finishedAt:l}}),c=!0}catch(e){console.error("Could not persist successful tool-call audit completion:",e instanceof Error?e.message:e)}return c&&ie.agentEventBus.publish(ie.TOOL_CALL_AUDIT_CHANGED_TOPIC,{toolCallAuditChanged:{id:s}}),i}async list(e={}){let t=await (0,t1.getPrismaClient)();return(await t.toolCallAudit.findMany({where:{...e.toolName?{toolName:e.toolName}:{},...e.resultStatus?{resultStatus:e.resultStatus}:{}},orderBy:{startedAt:"desc"},take:Math.min(Math.max(e.first??100,1),500)})).map(ac)}async get(e){let t=await (0,t1.getPrismaClient)(),r=await t.toolCallAudit.findUnique({where:{id:e}});return r?ac(r):null}}let ad="external:",ap=new Set(["accept","connection","content-length","content-type","host","last-event-id","mcp-protocol-version","mcp-session-id","transfer-encoding"]),ah=new Set(v.BUILD_CONFIGURATION_ICON_KEYS),am=new Set(["get_codebase_repository_preparations","save_codebase_repository_preparations"]);function af(e){if("STREAMABLE_HTTP"===e||"SSE"===e)return e;throw Error(`Unsupported MCP transport: ${e}`)}function ag(e,t){return{id:e.id,name:e.name,url:e.url,transport:af(e.transport),toolNamePrefix:e.toolNamePrefix,headers:[...e.headers].sort((e,t)=>e.name.localeCompare(t.name)).map(e=>({id:e.id,name:e.name,valueConfigured:t})),createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString()}}function ay(e){return{id:e.id,name:e.name,description:e.description,iconKey:e.iconKey,enabledForPlans:e.enabledForPlans,enabledForSessions:e.enabledForSessions,toolNames:e.tools.map(({toolName:e})=>e).sort(),createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString()}}class aw{credentials;audit;builtInTools;constructor(e,t,r={},i=new t3.CredentialService,a=new au){this.credentials=i,this.audit=a,this.builtInTools=function(e){var t,r,i,a,n,s,o,l,u,d,p,h,m,f,g,y,w,b,v,k,E,S,I,A,x,_,C,R,T,D,N,O;let P,L,B,U,j=[(t=e.codebaseTools,r=e.codebases,P=[an({name:"get_codebases",title:"Get codebases",description:"List every registered codebase checkout.",inputSchema:c.GetCodebasesInputSchema,outputSchema:c.GetCodebasesOutputSchema,annotations:i7,handler:async()=>({codebases:await t.list()})}),an({name:"get_codebase",title:"Get codebase",description:"Get one registered codebase by ID or exact folder path.",inputSchema:c.GetCodebaseInputSchema,outputSchema:c.GetCodebaseOutputSchema,annotations:i7,handler:async e=>({codebase:"id"in e?await t.getById(e.id):e.agentId?await t.getByPath(e.path,e.agentId):await t.getByPath(e.path)})})],r&&(P.splice(1,0,an({name:"search_codebases",title:"Search codebases",description:"Search registered codebases by text, agent, repository, branch, availability, or sync state.",inputSchema:c.SearchCodebasesInputSchema,outputSchema:c.SearchCodebasesOutputSchema,annotations:i7,handler:e=>t.search(e)}),rm({name:"register_codebase",title:"Register codebase",description:"Register a previously inspected agent repository folder.",inputSchema:e6.object({inspectionJobId:e6.string().min(1),name:e6.string().nullable().optional(),description:e6.string().nullable().optional()}),service:r,method:"confirm",resultKey:"codebase",annotations:{...ae,idempotentHint:!1}}),rm({name:"update_codebase_repository",title:"Update codebase repository",description:"Update canonical repository metadata and linked skill groups.",inputSchema:e6.object({id:e6.string().min(1),name:e6.string().min(1),description:e6.string(),jiraBranchRegex:e6.string().nullable().optional(),keepBaseBranchUpToDate:e6.boolean(),skillGroupIds:e6.array(e6.string()).nullable().optional()}),service:r,method:"updateRepository",arguments:e=>[e.id,e.name,e.description,e.jiraBranchRegex,e.keepBaseBranchUpToDate,e.skillGroupIds],resultKey:"repository",annotations:ae}),rm({name:"update_codebase_settings",title:"Update codebase settings",description:"Update global refresh, fetch, and Jira branch parsing settings.",inputSchema:e6.object({refreshIntervalSeconds:e6.number().int().positive(),fetchIntervalSeconds:e6.number().int().positive(),defaultJiraBranchRegex:e6.string()}),service:r,method:"updateSettings",resultKey:"settings",annotations:ae}),rm({name:"remove_codebase",title:"Remove codebase",description:"Remove a registered codebase from the control plane without deleting its repository folder.",inputSchema:e6.object({id:e6.string().min(1)}),service:r,method:"removeCodebase",arguments:({id:e})=>[e],resultKey:"removed",annotations:at}),rm({name:"run_codebase_git_operation",title:"Run codebase Git operation",description:"Run a supported Git operation against a registered codebase.",inputSchema:e6.object({codebaseId:e6.string().min(1),operation:e6.string().min(1),branch:e6.string().nullable().optional(),stashOid:e6.string().nullable().optional(),stashChanges:e6.boolean().nullable().optional(),requestId:e6.string().min(1)}),service:r,method:"runGitOperation",resultKey:"job",annotations:ae})),P.push(an({name:"get_codebase_repositories",title:"Get codebase repositories",description:"List canonical repositories and their checkout counts.",inputSchema:ry,outputSchema:c.GetCodebaseRepositoriesOutputSchema,annotations:i7,handler:async()=>({repositories:await t.repositories()})}),an({name:"get_codebase_repository",title:"Get codebase repository",description:"Get a canonical repository and all of its registered checkouts.",inputSchema:c.GetCodebaseRepositoryInputSchema,outputSchema:c.GetCodebaseRepositoryOutputSchema,annotations:i7,handler:async({id:e})=>({repository:await t.repository(e)})}),an({name:"get_codebase_repository_preparations",title:"Get repository preparations",description:"Get every write, delete, and assume-unchanged rule configured for a repository, including uploaded write contents.",inputSchema:rT,outputSchema:e6.object({preparations:e6.array(rR)}),annotations:i7,handler:async({repositoryId:e})=>({preparations:(await r.repositoryPreparations(e)).map(rD)})}),an({name:"save_codebase_repository_preparations",title:"Save repository preparations",description:"Atomically replace a repository's preparation rules. Existing write contents are retained when their rule ID is supplied without contentBase64; omitted rules are deleted.",inputSchema:rT.extend({preparations:e6.array(e6.object({id:e6.string().min(1).nullable().optional(),kind:e6.enum(["WRITE","DELETE","ASSUME_UNCHANGED"]),path:e6.string().min(1),contentBase64:e6.string().nullable().optional()})).max(500)}),outputSchema:e6.object({preparations:e6.array(rR)}),annotations:at,handler:async({repositoryId:e,preparations:t})=>(await r.saveRepositoryPreparations(e,t),{preparations:(await r.repositoryPreparations(e)).map(rD)})}),an({name:"get_codebase_settings",title:"Get codebase settings",description:"Get global codebase refresh, fetch, and branch settings.",inputSchema:ry,outputSchema:rw,annotations:i7,handler:async()=>{let e=await r.settings();return{settings:{refreshIntervalSeconds:e.refreshIntervalSeconds,fetchIntervalSeconds:e.fetchIntervalSeconds,defaultJiraBranchRegex:e.defaultJiraBranchRegex,updatedAt:e.updatedAt.toISOString()}}}}),an({name:"browse_agent_directory",title:"Browse agent directory",description:"List candidate repository folders on an enrolled agent.",inputSchema:rb,outputSchema:rv,annotations:i7,handler:async({agentId:e,path:t,requestId:i})=>({listing:await r.browse(e,t,i)})}),an({name:"inspect_agent_codebase",title:"Inspect agent codebase",description:"Inspect a repository folder without registering or changing it.",inputSchema:rk,outputSchema:rE,annotations:i7,handler:async({agentId:e,folder:t,requestId:i})=>({inspection:re(await r.inspect(e,t,i))})}),an({name:"refresh_codebases",title:"Refresh codebases",description:"Queue local metadata refreshes for registered codebases.",inputSchema:rS,outputSchema:rI,annotations:ae,handler:async({codebaseIds:e,requestId:t})=>{let i=await r.runOperation(rg.CODEBASE_REFRESH_JOB_KIND,e,t);return{jobs:i.jobs.map(e=>t7(e)),skipped:i.skipped}}}),an({name:"fetch_codebases",title:"Fetch codebases",description:"Queue remote Git fetches and configured base-branch updates.",inputSchema:rS,outputSchema:rI,annotations:{...ae,openWorldHint:!0},handler:async({codebaseIds:e,requestId:t})=>{let i=await r.runOperation(rg.CODEBASE_FETCH_JOB_KIND,e,t);return{jobs:i.jobs.map(e=>t7(e)),skipped:i.skipped}}}),an({name:"inspect_codebase_git_state",title:"Inspect codebase Git state",description:"Inspect branches, checkout locations, and stashes.",inputSchema:rA,outputSchema:rx,annotations:i7,handler:async({codebaseId:e,requestId:t})=>({state:await r.inspectGitState(e,t)})}),an({name:"inspect_codebase_stash",title:"Inspect codebase stash",description:"Read a bounded textual patch for a Git stash.",inputSchema:r_,outputSchema:rC,annotations:i7,handler:async({codebaseId:e,stashOid:t,requestId:i})=>({diff:await r.inspectStash(e,t,i)})}))),{id:"builtin:codebases",name:"Codebases",tools:P,children:[]})];return e.builds&&j.push((i=e.builds,{id:"builtin:builds",name:"Builds",children:[],tools:[an({name:"get_builds",title:"Get builds",description:"List immutable iOS build records.",inputSchema:ru.GetBuildsInputSchema,outputSchema:ru.GetBuildsOutputSchema,annotations:i7,handler:async e=>{let t=await i.builds(e);return{builds:t.items,nextCursor:t.nextCursor}}}),an({name:"get_build",title:"Get build",description:"Get a build with sanitized logs.",inputSchema:ru.GetBuildInputSchema,outputSchema:ru.GetBuildOutputSchema,annotations:i7,handler:async({buildId:e,afterLogId:t,logLimit:r})=>{let a=await i.getBuild(e);if(!a)throw Error("Build not found");return{build:a,logs:await i.logChunks(e,t,r)}}}),an({name:"get_build_configurations",title:"Get build configurations",description:"List build configurations for a worktree.",inputSchema:ru.GetBuildConfigurationsInputSchema,outputSchema:ru.GetBuildConfigurationsOutputSchema,annotations:i7,handler:async({worktreeId:e})=>({project:await i.projectForWorktree(e)})}),an({name:"get_build_destinations",title:"Get build destinations",description:"Inspect compatible build destinations.",inputSchema:ru.GetBuildDestinationsInputSchema,outputSchema:ru.GetBuildDestinationsOutputSchema,annotations:i7,handler:async e=>({destinations:"buildId"in e?await i.destinationsForBuild(e.buildId,e.requestId):await i.destinations(e)})}),an({name:"start_build",title:"Start build",description:"Queue an iOS build.",inputSchema:ru.StartBuildToolInputSchema,outputSchema:ru.StartBuildToolOutputSchema,annotations:ae,handler:async e=>({build:await i.startBuild(e)})}),an({name:"import_coverage_report",title:"Import coverage report",description:"Record a coverage file from a worktree as a coverage report.",inputSchema:ru.ImportCoverageReportToolInputSchema,outputSchema:ru.ImportCoverageReportToolOutputSchema,annotations:ae,handler:async e=>({build:await i.importCoverageReport(e)})}),an({name:"cancel_build",title:"Cancel build",description:"Cancel an active build.",inputSchema:ru.CancelBuildToolInputSchema,outputSchema:ru.CancelBuildToolOutputSchema,annotations:at,handler:async({buildId:e})=>({build:await i.cancelBuild(e)})}),an({name:"run_build",title:"Run build",description:"Install and launch without rebuilding.",inputSchema:ru.RunBuildToolInputSchema,outputSchema:ru.RunBuildToolOutputSchema,annotations:ae,handler:async e=>({deployments:await i.runBuild(e)})}),an({name:"export_build_archive",title:"Export build archive",description:"Export an archive to a local IPA folder.",inputSchema:ru.ExportBuildToolInputSchema,outputSchema:ru.ExportBuildToolOutputSchema,annotations:ae,handler:async e=>({export:await i.exportArchive(e)})}),rm({name:"get_build_project",title:"Get build project",description:"Get the iOS build project configured for a codebase.",inputSchema:e6.object({codebaseId:e6.string().min(1)}),service:i,method:"project",arguments:({codebaseId:e})=>[e],resultKey:"project"}),rm({name:"create_build_project",title:"Create build project",description:"Create an iOS build project for a codebase.",inputSchema:e6.object({codebaseId:e6.string().min(1)}),service:i,method:"createProject",arguments:({codebaseId:e})=>[e],resultKey:"project",annotations:{...ae,idempotentHint:!1}}),rm({name:"save_build_configuration",title:"Save build configuration",description:"Create or update an iOS build configuration.",inputSchema:e6.object({input:e6.record(e6.string(),e6.unknown())}),service:i,method:"saveConfiguration",arguments:({input:e})=>[e],resultKey:"configuration",annotations:ae}),rm({name:"delete_build_configuration",title:"Delete build configuration",description:"Delete an iOS build configuration.",inputSchema:e6.object({id:e6.string().min(1)}),service:i,method:"deleteConfiguration",arguments:({id:e})=>[e],resultKey:"deleted",annotations:at}),rm({name:"discover_build_sources",title:"Discover build sources",description:"Discover Xcode projects and workspaces in a worktree.",inputSchema:e6.object({worktreeId:e6.string().min(1),requestId:e6.string().min(1)}),service:i,method:"discoverSources",arguments:e=>[e.worktreeId,e.requestId],resultKey:"sources",annotations:ae}),rm({name:"inspect_build_source",title:"Inspect build source",description:"Inspect schemes, configurations, and targets for an Xcode source.",inputSchema:e6.object({input:e6.record(e6.string(),e6.unknown())}),service:i,method:"inspectSource",arguments:({input:e})=>[e],resultKey:"inspection",annotations:ae}),rm({name:"get_build_scripts",title:"Get build scripts",description:"List reusable build scripts.",inputSchema:e6.object({}),service:i,method:"scripts",arguments:()=>[],resultKey:"scripts"}),rm({name:"save_build_script",title:"Save build script",description:"Create or update a reusable build script.",inputSchema:e6.object({input:e6.record(e6.string(),e6.unknown())}),service:i,method:"saveScript",arguments:({input:e})=>[e],resultKey:"script",annotations:ae}),rm({name:"delete_build_script",title:"Delete build script",description:"Delete a reusable build script.",inputSchema:e6.object({id:e6.string().min(1)}),service:i,method:"deleteScript",arguments:({id:e})=>[e],resultKey:"deleted",annotations:at}),rm({name:"rebuild_build",title:"Rebuild build",description:"Queue a new build from an existing build snapshot.",inputSchema:e6.object({buildId:e6.string().min(1),requestId:e6.string().min(1)}),service:i,method:"rebuildBuild",arguments:e=>[e.buildId,e.requestId,null],resultKey:"build",annotations:ae}),rm({name:"delete_builds",title:"Delete builds",description:"Permanently delete build records and their retained data.",inputSchema:e6.object({ids:e6.array(e6.string().min(1)).min(1)}),service:i,method:"deleteBuilds",arguments:({ids:e})=>[e],resultKey:"count",annotations:at}),rm({name:"get_build_reports",title:"Get build reports",description:"Get parsed test and coverage reports for a build.",inputSchema:e6.object({buildId:e6.string().min(1)}),service:i,method:"reportsForBuild",arguments:({buildId:e})=>[e],resultKey:"reports"}),rm({name:"generate_build_report",title:"Generate build report",description:"Generate a parsed test-results or code-coverage report.",inputSchema:e6.object({buildId:e6.string().min(1),kind:e6.enum(["TEST_RESULTS","CODE_COVERAGE"]),requestId:e6.string().min(1)}),service:i,method:"generateReport",arguments:e=>[e.buildId,e.kind,e.requestId],resultKey:"report",annotations:ae}),rm({name:"start_worktree_coverage",title:"Start worktree coverage",description:"Start the configured coverage workflow for a worktree.",inputSchema:e6.object({input:e6.record(e6.string(),e6.unknown())}),service:i,method:"startWorktreeCoverage",arguments:({input:e})=>[e],resultKey:"build",annotations:ae}),rm({name:"get_worktree_coverage",title:"Get worktree coverage",description:"Get coverage history for a worktree.",inputSchema:e6.object({worktreeId:e6.string().min(1)}),service:i,method:"coverageHistory",arguments:({worktreeId:e})=>[e],resultKey:"history"})]})),e.telemetry&&e.pushNotifications&&j.push((a=e.telemetry,n=e.pushNotifications,(L=r5(a,"UNIFIED",{plural:"unified_events",singular:"unified_event",label:"Unified Events"})).push(an({name:"get_telemetry_separators",title:"Get telemetry separators",description:"List global manual and build separators with optional filters.",inputSchema:e6.object({first:e6.number().int().min(1).max(500).default(100),after:e6.string().nullable().default(null),kind:e6.string().min(1).nullable().optional(),name:e6.string().min(1).nullable().optional(),buildId:e6.string().min(1).nullable().optional()}),outputSchema:e6.object({items:e6.array(rJ),nextCursor:e6.string().nullable()}),annotations:i7,handler:e=>a.separators(e)}),an({name:"add_telemetry_separator",title:"Add telemetry separator",description:"Add a global manual separator to all telemetry views.",inputSchema:e6.object({name:e6.string().max(100).nullable().default(null)}),outputSchema:e6.object({separator:rJ}),annotations:{...ae,idempotentHint:!1},handler:async({name:e})=>({separator:await a.addSeparator(e)})}),an({name:"get_telemetry_settings",title:"Get telemetry settings",description:"Get telemetry collection state and effective ingestion URLs.",inputSchema:e6.object({}),outputSchema:e6.object({settings:e6.object({localBaseUrlOverride:e6.string().nullable(),remoteBaseUrlOverride:e6.string().nullable(),consoleCollectionEnabled:e6.boolean(),analyticsCollectionEnabled:e6.boolean(),detectedLocalBaseUrl:e6.string(),detectedRemoteBaseUrl:e6.string(),effectiveLocalBaseUrl:e6.string(),effectiveRemoteBaseUrl:e6.string(),updatedAt:e6.string()})}),annotations:i7,handler:async()=>({settings:await a.settings()})}),rm({name:"update_telemetry_settings",title:"Update telemetry settings",description:"Update telemetry collection and ingestion URL settings.",inputSchema:e6.object({localBaseUrlOverride:e6.string().nullable().optional(),remoteBaseUrlOverride:e6.string().nullable().optional(),consoleCollectionEnabled:e6.boolean().nullable().optional(),analyticsCollectionEnabled:e6.boolean().nullable().optional()}),service:a,method:"saveSettings",resultKey:"settings",annotations:ae}),rm({name:"get_telemetry_view_settings",title:"Get telemetry view settings",description:"Get display settings for a telemetry view.",inputSchema:e6.object({view:e6.enum(["UNIFIED","CONSOLE","ANALYTICS"])}),service:a,method:"viewSettings",arguments:({view:e})=>[e],resultKey:"settings"}),rm({name:"update_telemetry_highlight",title:"Update telemetry highlight",description:"Set or clear the highlight color on a telemetry entry.",inputSchema:e6.object({id:e6.string().min(1),color:e6.string().nullable().optional()}),service:a,method:"highlight",arguments:({id:e,color:t})=>[e,t??null],resultKey:"entry",annotations:ae}),rm({name:"get_telemetry_presets",title:"Get telemetry presets",description:"List saved column presets for a telemetry view.",inputSchema:e6.object({view:e6.enum(["UNIFIED","CONSOLE","ANALYTICS"])}),service:a,method:"columnPresets",arguments:({view:e})=>[e],resultKey:"presets"}),rm({name:"save_telemetry_preset",title:"Save telemetry preset",description:"Create or update a telemetry column preset.",inputSchema:e6.object({input:e6.record(e6.string(),e6.unknown())}),service:a,method:"saveColumnPreset",arguments:({input:e})=>[e],resultKey:"preset",annotations:ae}),rm({name:"get_saved_telemetry_filters",title:"Get saved telemetry filters",description:"List saved filters for a telemetry view.",inputSchema:e6.object({view:e6.enum(["UNIFIED","CONSOLE","ANALYTICS"])}),service:a,method:"savedFilters",arguments:({view:e})=>[e],resultKey:"filters"}),rm({name:"save_telemetry_filter",title:"Save telemetry filter",description:"Create or update a saved telemetry filter.",inputSchema:e6.object({input:e6.record(e6.string(),e6.unknown())}),service:a,method:"saveFilter",arguments:({input:e})=>[e],resultKey:"filter",annotations:ae}),rm({name:"export_telemetry",title:"Export telemetry",description:"Export a bounded telemetry query as structured JSON.",inputSchema:e6.object({view:e6.enum(["UNIFIED","CONSOLE","ANALYTICS"]).default("UNIFIED"),search:e6.string().nullable().optional(),first:e6.number().int().min(1).max(5e3).default(1e3)}),service:a,method:"timeline",resultKey:"export"})),{id:"builtin:debugging",name:"Debugging",tools:L,children:[{id:"builtin:debugging:console-logs",name:"Console Logs",tools:r5(a,"CONSOLE",{plural:"console_logs",singular:"console_log",label:"Console Logs"}),children:[]},{id:"builtin:debugging:analytics-events",name:"Analytics Events",tools:r5(a,"ANALYTICS",{plural:"analytics_events",singular:"analytics_event",label:"Analytics Events"}),children:[]},(B={...ae,openWorldHint:!0},{id:"builtin:debugging:push-notifications",name:"Push Notifications",children:[],tools:[an({name:"get_push_notification_registrations",title:"Get push notification registrations",description:"List registered APNs devices with masked tokens.",inputSchema:e6.object({}),outputSchema:e6.object({registrations:e6.array(rL)}),annotations:i7,handler:async()=>({registrations:(await n.registrations()).map(e=>{let t,r;return t=Array.isArray(e.supportedPushTypes)?e.supportedPushTypes:rP(e.pushTypesJson),r="string"==typeof e.token?e.token:"",{id:String(e.id),clientRegistrationId:String(e.clientRegistrationId),tokenMasked:"string"==typeof e.tokenMasked?e.tokenMasked:r?`${r.slice(0,8)}…${r.slice(-8)}`:"—",topic:String(e.topic),environment:String(e.environment),supportedPushTypes:Array.isArray(t)?t:[],displayName:String(e.displayName),deviceModel:"string"==typeof e.deviceModel?e.deviceModel:null,osVersion:"string"==typeof e.osVersion?e.osVersion:null,appVersion:"string"==typeof e.appVersion?e.appVersion:null,appBuild:"string"==typeof e.appBuild?e.appBuild:null,locale:"string"==typeof e.locale?e.locale:null,pushMagicConfigured:!!e.pushMagic,status:String(e.status),invalidatedAt:rO(e.invalidatedAt),lastFailureReason:"string"==typeof e.lastFailureReason?e.lastFailureReason:null,lastFailureAt:rO(e.lastFailureAt),lastRegisteredAt:rO(e.lastRegisteredAt),lastSentAt:rO(e.lastSentAt),createdAt:rO(e.createdAt),updatedAt:rO(e.updatedAt)}})})}),an({name:"get_push_notification_settings",title:"Get push notification settings",description:"Inspect APNs credential status without returning secrets.",inputSchema:e6.object({}),outputSchema:e6.object({settings:rU}),annotations:i7,handler:async()=>{var e;return{settings:{tokenConfigured:!!(e=await n.settings()).tokenConfigured,tokenTeamId:"string"==typeof e.tokenTeamId?e.tokenTeamId:null,tokenKeyId:"string"==typeof e.tokenKeyId?e.tokenKeyId:null,tokenPrivateKeyFingerprint:"string"==typeof e.tokenPrivateKeyFingerprint?e.tokenPrivateKeyFingerprint:null,tokenConfiguredAt:rO(e.tokenConfiguredAt),tokenLastUsedAt:rO(e.tokenLastUsedAt),tokenLastError:"string"==typeof e.tokenLastError?e.tokenLastError:null,certificates:Array.isArray(e.certificates)?e.certificates.map(e=>({id:String(e.id),name:String(e.name),topic:String(e.topic),environment:String(e.environment),fingerprint:String(e.fingerprint),expiresAt:rO(e.expiresAt),lastTestedAt:rO(e.lastTestedAt),lastError:"string"==typeof e.lastError?e.lastError:null,createdAt:rO(e.createdAt),updatedAt:rO(e.updatedAt)})):[],updatedAt:rO(e.updatedAt)}}}}),an({name:"get_push_notification_channels",title:"Get push notification channels",description:"List configured APNs broadcast channels.",inputSchema:e6.object({}),outputSchema:e6.object({channels:e6.array(rj)}),annotations:i7,handler:async()=>({channels:(await n.channels()).map(e=>({id:String(e.id),channelId:String(e.channelId),bundleId:String(e.bundleId),environment:String(e.environment),storagePolicy:String(e.storagePolicy),createdAt:rO(e.createdAt),updatedAt:rO(e.updatedAt)}))})}),an({name:"get_push_notification_presets",title:"Get push notification presets",description:"List saved, validated push editor presets.",inputSchema:e6.object({}),outputSchema:e6.object({presets:e6.array(rM)}),annotations:i7,handler:async()=>({presets:(await n.presets()).map(e=>({id:String(e.id),name:String(e.name),editor:rP(e.editor??e.editorJson),createdAt:rO(e.createdAt),updatedAt:rO(e.updatedAt)}))})}),an({name:"get_push_notification_history",title:"Get push notification history",description:"List recent push batches and per-recipient delivery results.",inputSchema:e6.object({limit:e6.number().int().min(1).max(200).default(100)}),outputSchema:e6.object({batches:e6.array(r$)}),annotations:i7,handler:async({limit:e})=>({batches:(await n.history(e)).map(e=>rF(e))})}),an({name:"get_push_notification_history_item",title:"Get push notification history item",description:"Get one push batch and all delivery results by ID.",inputSchema:e6.object({id:e6.string().min(1)}),outputSchema:e6.object({batch:r$.nullable()}),annotations:i7,handler:async({id:e})=>{let t=await n.historyItem(e);return{batch:t?rF(t):null}}}),an({name:"preview_push_notification",title:"Preview push notification",description:"Validate an editor and return its final payload and APNs headers.",inputSchema:e6.object({editor:e6.record(e6.string(),e6.unknown())}),outputSchema:e6.object({editor:e6.unknown(),payload:e6.unknown(),headers:e6.record(e6.string(),e6.string()),byteLength:e6.number().int().nonnegative()}),annotations:i7,handler:({editor:e})=>(0,rN.validatePushEditor)(e)}),an({name:"send_push_notification",title:"Send push notification",description:"Validate and queue a raw APNs editor payload for delivery.",inputSchema:rH,outputSchema:e6.object({batch:r$}),annotations:B,handler:async e=>({batch:rF(await n.send(rW(e)))})}),an({name:"send_push_notification_preset",title:"Send push notification preset",description:"Load a saved preset by ID and queue it for APNs delivery.",inputSchema:rV,outputSchema:e6.object({batch:r$}),annotations:B,handler:async e=>{let t=await n.preset(e.presetId);if(!t)throw Error("Push notification preset not found");let r={...e,editor:rP(t.editorJson)};return{batch:rF(await n.send(rW(r)))}}}),an({name:"resend_push_notification",title:"Resend push notification",description:"Queue a historical non-draft, non-direct batch again.",inputSchema:e6.object({id:e6.string().min(1),requestId:e6.string().min(1)}),outputSchema:e6.object({batch:r$}),annotations:B,handler:async({id:e,requestId:t})=>({batch:rF(await n.resend(e,t))})}),an({name:"rename_push_registration",title:"Rename push registration",description:"Rename an APNs device registration.",inputSchema:e6.object({id:e6.string().min(1),displayName:e6.string().min(1)}),outputSchema:e6.object({registration:e6.unknown()}),annotations:ae,handler:async({id:e,displayName:t})=>({registration:await n.renameRegistration(e,t)})}),an({name:"set_push_registration_enabled",title:"Set push registration enabled",description:"Enable or disable an APNs device registration.",inputSchema:e6.object({id:e6.string().min(1),enabled:e6.boolean()}),outputSchema:e6.object({registration:e6.unknown()}),annotations:ae,handler:async({id:e,enabled:t})=>({registration:await n.setRegistrationActive(e,t)})}),an({name:"delete_push_registration",title:"Delete push registration",description:"Permanently delete an APNs device registration.",inputSchema:e6.object({id:e6.string().min(1)}),outputSchema:e6.object({deleted:e6.unknown()}),annotations:at,handler:async({id:e})=>({deleted:await n.deleteRegistration(e)})}),an({name:"save_push_preset",title:"Save push preset",description:"Create or update a reusable push-notification preset.",inputSchema:e6.object({id:e6.string().nullable().optional(),name:e6.string().min(1),editor:e6.record(e6.string(),e6.unknown())}),outputSchema:e6.object({preset:e6.unknown()}),annotations:ae,handler:async({id:e,name:t,editor:r})=>({preset:await n.savePreset(t,r,e)})}),an({name:"delete_push_preset",title:"Delete push preset",description:"Delete a saved push-notification preset.",inputSchema:e6.object({id:e6.string().min(1)}),outputSchema:e6.object({deleted:e6.unknown()}),annotations:at,handler:async({id:e})=>({deleted:await n.deletePreset(e)})}),an({name:"delete_push_history",title:"Delete push history",description:"Delete one push-notification history batch.",inputSchema:e6.object({id:e6.string().min(1)}),outputSchema:e6.object({deleted:e6.unknown()}),annotations:at,handler:async({id:e})=>({deleted:await n.deleteHistory(e)})}),an({name:"clear_push_history",title:"Clear push history",description:"Permanently clear all push-notification history.",inputSchema:e6.object({}),outputSchema:e6.object({count:e6.unknown()}),annotations:at,handler:async()=>({count:await n.clearHistory()})}),an({name:"create_push_channel",title:"Create push channel",description:"Create a push-notification broadcast channel.",inputSchema:e6.object({input:e6.record(e6.string(),e6.unknown())}),outputSchema:e6.object({channel:e6.unknown()}),annotations:ae,handler:async({input:e})=>({channel:await n.createChannel(e)})}),an({name:"delete_push_channel",title:"Delete push channel",description:"Delete a push-notification broadcast channel.",inputSchema:e6.object({id:e6.string().min(1)}),outputSchema:e6.object({deleted:e6.unknown()}),annotations:at,handler:async({id:e})=>({deleted:await n.deleteChannel(e)})}),an({name:"retest_push_certificate",title:"Retest push certificate",description:"Retest an existing APNs certificate credential without returning its secret material.",inputSchema:e6.object({id:e6.string().min(1)}),outputSchema:e6.object({credential:e6.unknown()}),annotations:ae,handler:async({id:e})=>({credential:await n.retestCertificateCredential(e)})})]})]})),e.agents&&j.push((s=e.agents,{id:"builtin:agents",name:"Agents",children:[],tools:[an({name:"get_agents",title:"Get agents",description:"List enrolled agents, capabilities, resources, and status.",inputSchema:ra,outputSchema:e6.object({agents:e6.array(rn)}),annotations:i7,handler:async()=>({agents:(await s.listAgents()).map(e=>t5(e))})}),an({name:"get_agent",title:"Get agent",description:"Get one enrolled agent by ID.",inputSchema:rc,outputSchema:e6.object({agent:rn.nullable()}),annotations:i7,handler:async({agentId:e})=>{let t=await s.getAgent(e);return{agent:t?t5(t):null}}}),an({name:"get_agent_settings",title:"Get agent settings",description:"Get repository, build, and Derived Data paths for an agent.",inputSchema:rc,outputSchema:e6.object({settings:rs}),annotations:i7,handler:async({agentId:e})=>{let t=await s.getAgent(e);if(!t)throw Error("Agent not found");return{settings:t9(t)}}}),an({name:"get_agent_jobs",title:"Get agent jobs",description:"List recent user-visible jobs for an agent.",inputSchema:e6.object({agentId:e6.string().min(1),limit:e6.number().int().min(1).max(200).default(50)}),outputSchema:e6.object({jobs:e6.array(ro)}),annotations:i7,handler:async({agentId:e,limit:t})=>({jobs:(await s.listJobs(e,t)).map(e=>t7(e))})}),an({name:"get_agent_job",title:"Get agent job",description:"Get one agent job and its result by ID.",inputSchema:e6.object({jobId:e6.string().min(1)}),outputSchema:e6.object({job:ro.nullable()}),annotations:i7,handler:async({jobId:e})=>{let t=await s.getJob(e);return{job:t?t7(t):null}}}),an({name:"get_agent_job_logs",title:"Get agent job logs",description:"Fetch ordered job logs after an optional sequence number.",inputSchema:e6.object({jobId:e6.string().min(1),afterSequence:e6.number().int().min(-1).default(-1)}),outputSchema:e6.object({logs:e6.array(rl)}),annotations:i7,handler:async({jobId:e,afterSequence:t})=>({logs:(await s.listLogs(e,t)).map(e=>({id:String(e.id),jobId:String(e.jobId),sequence:Number(e.sequence),stream:String(e.stream),message:String(e.message),createdAt:t8(e.createdAt)}))})}),an({name:"update_agent_base_repo_directory",title:"Update agent base repository directory",description:"Set or reset the absolute base repository directory.",inputSchema:e6.object({agentId:e6.string().min(1),baseRepoDirectory:e6.string().min(1).nullable()}),outputSchema:e6.object({settings:rs}),annotations:ae,handler:async({agentId:e,baseRepoDirectory:t})=>({settings:t9(await s.updateBaseRepoDirectory(e,t))})}),an({name:"update_agent_builds_directory",title:"Update agent builds directory",description:"Set or reset the absolute build-output directory.",inputSchema:e6.object({agentId:e6.string().min(1),buildsDirectory:e6.string().min(1).nullable()}),outputSchema:e6.object({settings:rs}),annotations:ae,handler:async({agentId:e,buildsDirectory:t})=>({settings:t9(await s.updateBuildsDirectory(e,t))})}),an({name:"update_agent_derived_data_settings",title:"Update agent Derived Data settings",description:"Set default, absolute, or worktree-relative Derived Data paths.",inputSchema:e6.object({agentId:e6.string().min(1),mode:e6.enum(["DEFAULT","ABSOLUTE","RELATIVE"]),path:e6.string().min(1).nullable().default(null)}),outputSchema:e6.object({settings:rs}),annotations:ae,handler:async({agentId:e,mode:t,path:r})=>({settings:t9(await s.updateDerivedDataSettings(e,t,r))})}),an({name:"request_agent_codebase_reconcile",title:"Request agent codebase reconcile",description:"Ask an online agent to reconcile its registered codebases.",inputSchema:rc,outputSchema:e6.object({requested:e6.boolean()}),annotations:ae,handler:async({agentId:e})=>({requested:await s.requestCodebaseReconcile([e])===1})}),an({name:"cancel_agent_job",title:"Cancel agent job",description:"Cancel a queued or running agent job.",inputSchema:e6.object({jobId:e6.string().min(1)}),outputSchema:e6.object({job:ro}),annotations:at,handler:async({jobId:e})=>({job:t7(await s.cancelJob(e))})}),an({name:"get_agent_cadence_settings",title:"Get agent cadence settings",description:"Get effective scan, reconciliation, fetch, and heartbeat intervals for an agent.",inputSchema:rc,outputSchema:e6.object({settings:e6.unknown()}),handler:async({agentId:e})=>({settings:await s.cadenceSettings(e)})}),an({name:"update_agent_cadence_settings",title:"Update agent cadence settings",description:"Update scan, reconciliation, fetch, and heartbeat intervals for an agent.",inputSchema:rc.extend({settings:e6.object({codebaseScanIntervalSeconds:e6.number().int().positive(),jobReconciliationIntervalSeconds:e6.number().int().positive(),gitFetchIntervalSeconds:e6.number().int().positive(),heartbeatIntervalSeconds:e6.number().int().positive()})}),outputSchema:e6.object({settings:e6.unknown()}),annotations:ae,handler:async({agentId:e,settings:t})=>({settings:await s.updateCadenceSettings(e,t)})}),an({name:"delete_agent",title:"Delete agent",description:"Permanently delete an enrolled agent and its control-plane records.",inputSchema:rc,outputSchema:e6.object({deleted:e6.boolean()}),annotations:at,handler:async({agentId:e})=>({deleted:await s.deleteAgent(e)})})]})),e.diskSpace&&j.push((o=e.diskSpace,{id:"builtin:disk-space",name:"Disk Space",children:[],tools:[an({name:"get_disk_space_overview",title:"Get disk-space overview",description:"Get global thresholds and canonical Derived Data disk snapshots for every agent.",inputSchema:e6.object({}),outputSchema:e6.object({settings:ic,agents:e6.array(im)}),annotations:i7,handler:async()=>{let e=await o.overview();return{settings:e.settings,agents:e.agents.map(t=>ii(e.settings,t))}}}),an({name:"get_disk_space_settings",title:"Get disk-space settings",description:"Get global disk thresholds and report timing settings.",inputSchema:e6.object({}),outputSchema:e6.object({settings:ic}),annotations:i7,handler:async()=>({settings:await o.settings()})}),an({name:"get_agent_disk_space",title:"Get agent disk space",description:"Get one agent's canonical Derived Data disk-space monitor snapshot.",inputSchema:ig,outputSchema:e6.object({snapshot:im}),annotations:i7,handler:async({agentId:e})=>({snapshot:await o.snapshot(e)})}),an({name:"update_disk_space_settings",title:"Update disk-space settings",description:"Update the global normal and pressure free-space thresholds in GiB.",inputSchema:e6.object({normalThresholdGiB:e6.number().positive(),pressureThresholdGiB:e6.number().positive()}),outputSchema:e6.object({settings:ic}),annotations:ae,handler:async e=>({settings:await o.updateSettings(e)})}),an({name:"set_agent_disk_space_monitoring",title:"Set agent disk-space monitoring",description:"Enable or disable Derived Data disk-space monitoring for an agent.",inputSchema:ig.extend({enabled:e6.boolean()}),outputSchema:e6.object({snapshot:im}),annotations:ae,handler:async({agentId:e,enabled:t})=>(await o.setMonitoring(e,t),{snapshot:await o.snapshot(e)})}),an({name:"set_agent_disk_space_pressure_mode",title:"Set agent disk pressure mode",description:"Enable or clear manual disk pressure mode for an agent.",inputSchema:ig.extend({enabled:e6.boolean()}),outputSchema:e6.object({snapshot:im}),annotations:ae,handler:async({agentId:e,enabled:t})=>(await o.setManualPressureMode(e,t),{snapshot:await o.snapshot(e)})}),an({name:"request_agent_disk_space_refresh",title:"Request agent disk-space refresh",description:"Ask an agent to collect and report disk-space telemetry immediately.",inputSchema:ig,outputSchema:e6.object({agentId:e6.string(),requestedAt:e6.string(),previousReportedAt:e6.string().nullable()}),annotations:ae,handler:async({agentId:e})=>o.requestRefresh(e)})]})),e.worktrees&&j.push({id:"builtin:worktrees",name:"Worktrees",children:[],tools:[rm({name:"get_worktrees",title:"Get worktrees",description:"Get the current worktree overview grouped by agent and codebase.",inputSchema:rf,service:l=e.worktrees,method:"overview",arguments:()=>[],resultKey:"overview"}),an({name:"get_worktree_preparation_overview",title:"Get worktree preparation overview",description:"Get persisted per-file preparation status for every repository worktree, including unsupported and offline worktrees.",inputSchema:rf,outputSchema:e6.object({overview:i8}),handler:async()=>({overview:{repositories:(await l.preparationOverview()).repositories.map(({repository:e,worktrees:t})=>({repository:{id:e.id,name:e.name,canonicalOrigin:e.canonicalOrigin,displayOrigin:e.displayOrigin},preparations:e.preparations.map(e=>({id:e.id,kind:e.kind,path:e.path,contentSha256:e.contentSha256,byteCount:e.byteCount,definitionHash:e.definitionHash})),worktrees:t.map(e=>({worktree:{id:e.worktree.id,codebaseId:e.worktree.codebaseId,folder:e.worktree.folder,relativePath:e.worktree.relativePath,branch:e.worktree.branch,baseBranch:e.worktree.baseBranch,primary:e.worktree.primary,availability:e.worktree.availability,missingAt:e.worktree.missingAt?.toISOString()??null},agent:{id:e.agent.id,name:e.agent.name,hostname:e.agent.hostname,version:e.agent.version},supported:e.supported,unsupportedReason:e.unsupportedReason,overallState:e.overallState,statuses:e.statuses.map(e=>({preparationId:e.preparation.id,kind:e.preparation.kind,path:e.preparation.path,definitionHash:e.preparation.definitionHash,state:e.state,message:e.message,checkedAt:e.checkedAt?.toISOString()??null})),activeJob:e.activeJob?{id:e.activeJob.id,status:e.activeJob.status}:null}))}))}})}),an({name:"run_worktree_preparations",title:"Run worktree preparations",description:"Inspect, apply, or undo repository preparations for up to 500 worktrees. Returns dispatched jobs and explicit skip reasons.",inputSchema:i4,outputSchema:e6.object({jobs:e6.array(e6.unknown()),skipped:e6.array(e6.object({worktreeId:e6.string(),reason:e6.string()}))}),handler:e=>l.runPreparations(e.worktreeIds,e.action,e.requestId),annotations:at}),an({name:"get_worktree",title:"Get worktree",description:"Get one current worktree by ID.",inputSchema:i1,outputSchema:e6.object({worktree:e6.unknown().nullable()}),handler:async({id:e})=>({worktree:(await l.overview()).agents.flatMap(e=>e.codebases).flatMap(e=>e.worktrees).find(t=>t.id===e)??null})}),rm({name:"get_hidden_worktrees",title:"Get hidden worktrees",description:"List worktrees no longer present on their agents.",inputSchema:rf,service:l,method:"hidden",arguments:()=>[],resultKey:"worktrees"}),rm({name:"inspect_worktree",title:"Inspect worktree",description:"Request a fresh inspection of a worktree.",inputSchema:i2,service:l,method:"inspect",arguments:e=>[e.worktreeId,e.requestId],resultKey:"job",annotations:ae}),rm({name:"inspect_worktree_diff",title:"Inspect worktree diff",description:"Inspect a worktree diff for a scope, file, or commit.",inputSchema:i2.extend({scope:e6.string().min(1),path:e6.string().nullable().optional(),previousPath:e6.string().nullable().optional(),commitSha:e6.string().nullable().optional()}),service:l,method:"inspectDiff",arguments:e=>[e.worktreeId,{scope:e.scope,path:e.path,previousPath:e.previousPath,commitSha:e.commitSha},e.requestId],resultKey:"inspection",annotations:ae}),rm({name:"refresh_worktrees",title:"Refresh worktrees",description:"Ask connected agents to refresh their worktree reports.",inputSchema:rf,service:l,method:"requestRefresh",arguments:()=>[],resultKey:"requested",annotations:ae}),rm({name:"refresh_worktree_pull_request",title:"Refresh worktree pull request",description:"Refresh the GitHub pull request attached to a worktree.",inputSchema:i1,service:l,method:"refreshPullRequest",arguments:({id:e})=>[e],resultKey:"worktree",annotations:ae}),rm({name:"create_worktree",title:"Create worktree",description:"Create a worktree from a new, existing, or Jira ticket branch.",inputSchema:e6.object({codebaseId:e6.string().min(1),selection:i3,requestId:e6.string().min(1)}),service:l,method:"createWorktree",resultKey:"worktree",annotations:{...ae,idempotentHint:!1}}),rm({name:"change_worktree_branch",title:"Change worktree branch",description:"Switch a worktree to another branch selection.",inputSchema:e6.object({worktreeId:e6.string().min(1),selection:i3,requestId:e6.string().min(1),stashOnFailure:e6.boolean().nullable().optional()}),service:l,method:"changeWorktreeBranch",resultKey:"job",annotations:ae}),rm({name:"commit_worktree",title:"Commit worktree changes",description:"Stage all or an exact set of changed paths and create a Git commit in a worktree.",inputSchema:i2.extend({message:e6.string().trim().min(1).max(5e4),signed:e6.boolean().nullable().optional(),stageAll:e6.boolean().default(!0),paths:e6.array(e6.string().min(1)).max(500).default([])}),service:l,method:"commitWorktree",resultKey:"job",annotations:ae}),rm({name:"move_worktree",title:"Move worktree",description:"Move work from one worktree into another codebase or worktree.",inputSchema:e6.object({sourceWorktreeId:e6.string().min(1),targetCodebaseId:e6.string().min(1),targetWorktreeId:e6.string().nullable().optional(),deleteSource:e6.boolean().default(!1),requestId:e6.string().min(1)}),service:l,method:"moveWorktree",resultKey:"move",annotations:ae}),rm({name:"retry_worktree_move_with_stash",title:"Retry worktree move with stash",description:"Retry a blocked worktree move after stashing changes.",inputSchema:i1,service:l,method:"retryWorktreeMoveWithStash",arguments:({id:e})=>[e],resultKey:"move",annotations:ae}),rm({name:"cancel_worktree_move",title:"Cancel worktree move",description:"Cancel an active worktree move.",inputSchema:i1,service:l,method:"cancelWorktreeMove",arguments:({id:e})=>[e],resultKey:"move",annotations:ae}),rm({name:"delete_worktree",title:"Delete worktree",description:"Delete a worktree and optionally its remote branch.",inputSchema:e6.object({worktreeId:e6.string().min(1),deleteRemoteBranch:e6.boolean().default(!1),requestId:e6.string().min(1)}),service:l,method:"deleteWorktree",resultKey:"job",annotations:at}),rm({name:"run_worktree_operation",title:"Run worktree operation",description:"Run a supported high-level operation in a worktree.",inputSchema:i2.extend({operation:e6.enum(i0.WORKTREE_OPERATIONS),forcePreparations:e6.boolean().default(!1)}),service:l,method:"runOperation",arguments:e=>[e.worktreeId,e.operation,e.requestId,e.forcePreparations],resultKey:"job",annotations:ae}),rm({name:"run_worktree_git_operation",title:"Run worktree Git operation",description:"Run a supported Git operation in a worktree.",inputSchema:i2.extend({operation:e6.enum(i0.WORKTREE_GIT_OPERATIONS),branch:e6.string().nullable().optional(),stashOid:e6.string().nullable().optional(),stashChanges:e6.boolean().nullable().optional()}),service:l,method:"runGitOperation",resultKey:"job",annotations:ae}),an({name:"update_worktree_metadata",title:"Update worktree metadata",description:"Update a worktree base branch and/or highlight color.",inputSchema:e6.object({id:e6.string().min(1),baseBranch:e6.string().nullable().optional(),highlightColor:e6.string().nullable().optional()}),outputSchema:e6.object({worktree:e6.unknown()}),annotations:ae,handler:async({id:e,baseBranch:t,highlightColor:r})=>{let i=null;if(void 0!==t&&(i=await l.updateBaseBranch(e,t)),void 0!==r&&(i=await l.updateHighlight(e,r)),void 0===t&&void 0===r)throw Error("At least one metadata field is required");return{worktree:i}}}),rm({name:"set_worktree_tags",title:"Set worktree tags",description:"Replace the tags assigned to a worktree.",inputSchema:e6.object({id:e6.string().min(1),tagIds:e6.array(e6.string().min(1))}),service:l,method:"setTags",arguments:e=>[e.id,e.tagIds],resultKey:"worktree",annotations:ae})]}),e.runs&&j.push((u=e.runs,{id:"builtin:agent-runs",name:"Agent Runs",children:[],tools:[rm({name:"get_agent_runs",title:"Get agent runs",description:"List agent runs with kind, archive, provider, origin, search, and pagination filters.",inputSchema:e6.object({kind:e6.enum(["SESSION","PLAN"]).default("SESSION"),search:e6.string().nullable().optional(),archive:e6.string().default("ACTIVE"),provider:e6.string().nullable().optional(),origin:e6.string().nullable().optional(),first:e6.number().int().min(1).max(200).default(100),after:e6.string().nullable().optional()}),service:u,method:"list",resultKey:"page"}),rm({name:"get_agent_run",title:"Get agent run",description:"Get an agent run without exposing its native session transcript.",inputSchema:ix,service:u,method:"get",arguments:({runId:e})=>[e],resultKey:"run"}),rm({name:"get_run_events",title:"Get run events",description:"Get normalized run events; native provider payloads are redacted.",inputSchema:ix.extend({search:e6.string().nullable().optional(),afterSequence:e6.number().int().default(-1),first:e6.number().int().min(1).max(500).default(200),includeSuperseded:e6.boolean().default(!1)}),service:u,method:"events",resultKey:"events"}),rm({name:"get_run_questions",title:"Get run questions",description:"Get question batches for a run.",inputSchema:ix.extend({first:e6.number().int().min(1).max(200).default(100),after:e6.string().nullable().optional()}),service:u,method:"questions",resultKey:"page"}),rm({name:"get_run_usage",title:"Get run usage",description:"Get token and cost usage summarized for a run.",inputSchema:ix,service:u,method:"usage",arguments:({runId:e})=>[e],resultKey:"usage"}),rm({name:"get_run_linked_items",title:"Get linked run items",description:"Get runs linked by follow-up, plan, or parent relationships.",inputSchema:ix,service:u,method:"linkedItems",arguments:({runId:e})=>[e],resultKey:"runs"}),rm({name:"get_run_provider_catalog",title:"Get run provider catalog",description:"Get provider, model, and reasoning-effort choices for a run or worktree.",inputSchema:e6.object({runId:e6.string().nullable().optional(),worktreeId:e6.string().nullable().optional()}),service:u,method:"providerCatalog",resultKey:"providers"}),rm({name:"create_agent_run",title:"Create agent run",description:"Create and queue a new agent run.",inputSchema:i_,service:u,method:"create",resultKey:"run",annotations:{...ae,idempotentHint:!1}}),rm({name:"play_plan",title:"Play plan",description:"Create a run from an existing plan run.",inputSchema:e6.object({planId:e6.string().min(1)}),service:u,method:"playPlan",arguments:({planId:e})=>[e],resultKey:"run",annotations:{...ae,idempotentHint:!1}}),rm({name:"create_run_follow_up",title:"Create run follow-up",description:"Create a follow-up run linked to a source run.",inputSchema:e6.object({sourceId:e6.string().min(1),input:i_}),service:u,method:"followUp",arguments:({sourceId:e,input:t})=>[e,t],resultKey:"run",annotations:{...ae,idempotentHint:!1}}),rm({name:"steer_agent_run",title:"Steer agent run",description:"Send additional guidance to an active run.",inputSchema:ix.extend({prompt:e6.string().min(1),attachmentIds:e6.array(e6.string().min(1)).default([])}),service:u,method:"steer",arguments:e=>[e.runId,e.prompt,e.attachmentIds],resultKey:"run",annotations:ae}),rm({name:"answer_run_question",title:"Answer run question",description:"Answer a pending agent question batch.",inputSchema:e6.object({batchId:e6.string().min(1),answers:e6.unknown()}),service:u,method:"answerQuestion",arguments:({batchId:e,answers:t})=>[e,t],resultKey:"run",annotations:ae}),rm({name:"revise_run_answer",title:"Revise run answer",description:"Revise an answer and optionally stash or roll back worktree changes.",inputSchema:e6.object({batchId:e6.string().min(1),answers:e6.unknown(),stash:e6.boolean().default(!1),rollback:e6.boolean().default(!0)}),service:u,method:"reviseAnswer",arguments:e=>[e.batchId,e.answers,e.stash,e.rollback],resultKey:"run",annotations:ae}),rm({name:"pause_agent_run",title:"Pause agent run",description:"Pause an active agent run.",inputSchema:ix,service:u,method:"lifecycle",arguments:({runId:e})=>[e,"PAUSE"],resultKey:"run",annotations:ae}),rm({name:"continue_agent_run",title:"Continue agent run",description:"Continue a paused agent run.",inputSchema:ix,service:u,method:"lifecycle",arguments:({runId:e})=>[e,"CONTINUE"],resultKey:"run",annotations:ae}),rm({name:"cancel_agent_run",title:"Cancel agent run",description:"Cancel an active agent run.",inputSchema:ix,service:u,method:"lifecycle",arguments:({runId:e})=>[e,"CANCEL"],resultKey:"run",annotations:ae}),rm({name:"archive_agent_runs",title:"Archive agent runs",description:"Archive or restore agent runs.",inputSchema:e6.object({ids:e6.array(e6.string().min(1)).min(1),archived:e6.boolean().default(!0)}),service:u,method:"archive",arguments:({ids:e,archived:t})=>[e,t],resultKey:"count",annotations:ae}),rm({name:"delete_agent_runs",title:"Delete agent runs",description:"Permanently delete agent runs and their stored normalized history.",inputSchema:e6.object({ids:e6.array(e6.string().min(1)).min(1)}),service:u,method:"deleteRuns",arguments:({ids:e})=>[e],resultKey:"count",annotations:at})]})),e.commands&&j.push((d=e.commands,{id:"builtin:commands",name:"Commands",children:[],tools:[rm({name:"get_commands",title:"Get commands",description:"List saved command definitions.",inputSchema:e6.object({includeArchived:e6.boolean().default(!1)}),service:d,method:"listDefinitions",arguments:({includeArchived:e})=>[e],resultKey:"commands"}),rm({name:"get_command",title:"Get command",description:"Get one command definition.",inputSchema:e6.object({id:e6.string().min(1)}),service:d,method:"getDefinition",arguments:({id:e})=>[e],resultKey:"command"}),an({name:"get_eligible_commands",title:"Get eligible commands",description:"List commands eligible for an agent or worktree target.",inputSchema:e6.discriminatedUnion("targetType",[e6.object({targetType:e6.literal("AGENT"),agentId:e6.string().min(1)}),e6.object({targetType:e6.literal("WORKTREE"),worktreeId:e6.string().min(1)})]),outputSchema:e6.object({commands:e6.unknown()}),handler:async e=>({commands:rh(await rd(d,"AGENT"===e.targetType?"eligibleForAgent":"eligibleForWorktree",["AGENT"===e.targetType?e.agentId:e.worktreeId]))})}),rm({name:"get_command_runs",title:"Get command runs",description:"List command runs with target, archive, search, and cursor filters.",inputSchema:e6.object({includeArchived:e6.boolean().default(!1),search:e6.string().nullable().optional(),agentId:e6.string().nullable().optional(),worktreeId:e6.string().nullable().optional(),first:e6.number().int().min(1).max(200).default(50),after:e6.string().nullable().optional()}),service:d,method:"listRuns",resultKey:"page"}),rm({name:"get_command_run",title:"Get command run",description:"Get one command run and its attempts.",inputSchema:e6.object({id:e6.string().min(1)}),service:d,method:"getRun",arguments:({id:e})=>[e],resultKey:"run"}),rm({name:"get_command_run_output",title:"Get command run output",description:"Read paginated terminal output chunks for a command run.",inputSchema:e6.object({runId:e6.string().min(1),afterAttempt:e6.number().int().min(0).default(0),afterSequence:e6.number().int().default(-1),first:e6.number().int().min(1).max(5e3).default(1e3)}),service:d,method:"listOutput",arguments:e=>[e.runId,e.afterAttempt,e.afterSequence,e.first],resultKey:"chunks"}),rm({name:"start_command",title:"Start command",description:"Start a saved command on an eligible agent or worktree.",inputSchema:e6.object({commandId:e6.string().min(1),agentId:e6.string().nullable().optional(),worktreeId:e6.string().nullable().optional(),origin:e6.string().default("MANUAL"),idempotencyKey:e6.string().nullable().optional()}),service:d,method:"startRun",resultKey:"run",annotations:ae}),rm({name:"start_custom_command",title:"Start custom command",description:"Start an ad hoc shell command on an agent or worktree.",inputSchema:e6.object({script:e6.string().min(1),agentId:e6.string().nullable().optional(),worktreeId:e6.string().nullable().optional(),origin:e6.string().default("MANUAL"),idempotencyKey:e6.string().nullable().optional()}),service:d,method:"startCustomRun",resultKey:"run",annotations:ae}),rm({name:"terminate_command_run",title:"Terminate command run",description:"Request termination of an active command run.",inputSchema:e6.object({id:e6.string().min(1)}),service:d,method:"terminateRun",arguments:({id:e})=>[e],resultKey:"run",annotations:ae}),rm({name:"rerun_command",title:"Rerun command",description:"Create a new run from a previous command snapshot.",inputSchema:e6.object({id:e6.string().min(1)}),service:d,method:"rerun",arguments:({id:e})=>[e],resultKey:"run",annotations:{...ae,idempotentHint:!1}}),rm({name:"create_command",title:"Create command",description:"Create a saved command definition.",inputSchema:iy,service:d,method:"createDefinition",resultKey:"command",annotations:{...ae,idempotentHint:!1}}),rm({name:"update_command",title:"Update command",description:"Replace a saved command definition.",inputSchema:e6.object({id:e6.string().min(1),input:iy}),service:d,method:"updateDefinition",arguments:({id:e,input:t})=>[e,t],resultKey:"command",annotations:ae}),rm({name:"archive_command",title:"Archive command",description:"Archive or restore a command definition.",inputSchema:e6.object({id:e6.string().min(1),archived:e6.boolean().default(!0)}),service:d,method:"archiveDefinition",arguments:({id:e,archived:t})=>[e,t],resultKey:"command",annotations:ae}),rm({name:"archive_command_runs",title:"Archive command runs",description:"Archive or restore command runs.",inputSchema:e6.object({ids:e6.array(e6.string().min(1)).min(1),archived:e6.boolean().default(!0)}),service:d,method:"archiveRuns",arguments:({ids:e,archived:t})=>[e,t],resultKey:"updated",annotations:ae}),rm({name:"delete_command_runs",title:"Delete command runs",description:"Permanently delete command runs and stored output.",inputSchema:e6.object({ids:e6.array(e6.string().min(1)).min(1)}),service:d,method:"deleteRuns",arguments:({ids:e})=>[e],resultKey:"count",annotations:at})]})),e.jira&&e.jiraWebhooks&&j.push((p=e.jira,{id:"builtin:jira",name:"Jira",children:[(h=e.jiraWebhooks,{id:"builtin:jira:administration",name:"Jira Administration",children:[],tools:[rm({name:"get_jira_webhook_settings",title:"Get Jira webhook settings",description:"Get the Jira webhook configuration and the outcome of the most recent delivery.",inputSchema:e6.object({}),service:h,method:"getWebhookSettings",arguments:()=>[],resultKey:"settings",annotations:i7}),rm({name:"get_jira_webhook_deliveries",title:"Get Jira webhook deliveries",description:"List Jira webhook deliveries with their event, issue, and outcome.",inputSchema:e6.object({limit:e6.number().int().min(1).max(100).default(50),offset:e6.number().int().min(0).default(0)}),service:h,method:"deliveries",arguments:({limit:e,offset:t})=>[e,t],resultKey:"page",annotations:i7}),rm({name:"clear_jira_webhook_deliveries",title:"Clear Jira webhook deliveries",description:"Delete the Jira webhook delivery history.",inputSchema:e6.object({}),service:h,method:"clearDeliveries",arguments:()=>[],resultKey:"cleared",annotations:at}),an({name:"rotate_jira_webhook_secret",title:"Rotate Jira webhook secret",description:"Replace the Jira webhook signing secret and return it once. For a manually configured webhook, paste the returned secret into Jira before expecting deliveries to succeed.",inputSchema:e6.object({}),outputSchema:e6.object({rotated:e6.boolean(),secret:e6.string().min(1)}),annotations:{...ae,idempotentHint:!1},handler:async()=>({rotated:!0,secret:(await h.rotateSecret()).secret})}),rm({name:"disable_jira_webhook",title:"Disable Jira webhook",description:"Delete the Jira webhook signing secret and stop accepting deliveries.",inputSchema:e6.object({}),service:h,method:"disableWebhook",arguments:()=>[],resultKey:"settings",annotations:at}),rm({name:"get_jira_available_projects",title:"Get Jira available projects",description:"List Jira projects that can be added, including ones not configured yet.",inputSchema:e6.object({}),service:p,method:"availableProjects",arguments:()=>[],resultKey:"projects",annotations:ar}),rm({name:"get_jira_project_statuses",title:"Get Jira project statuses",description:"List the statuses available in a configured Jira project.",inputSchema:e6.object({projectId:e6.string().min(1)}),service:p,method:"projectStatuses",arguments:({projectId:e})=>[e],resultKey:"statuses",annotations:ar}),rm({name:"add_jira_project",title:"Add Jira project",description:"Add a Jira project by its Jira ID.",inputSchema:e6.object({jiraId:e6.string().min(1)}),service:p,method:"addProject",arguments:({jiraId:e})=>[e],resultKey:"projects",annotations:ai}),rm({name:"remove_jira_project",title:"Remove Jira project",description:"Remove a configured Jira project along with its sources and cached tickets.",inputSchema:e6.object({projectId:e6.string().min(1)}),service:p,method:"removeProject",arguments:({projectId:e})=>[e],resultKey:"projects",annotations:at}),rm({name:"update_jira_project_display_settings",title:"Update Jira project display settings",description:"Set the assignment filter, completed statuses, and done status for a Jira project.",inputSchema:e6.object({projectId:e6.string().min(1),ticketAssignmentFilter:e6.enum(["ALL","UNASSIGNED_OR_SELF","SELF_IN_PROGRESS"]),hideCompletedTickets:e6.boolean(),completedStatusIds:e6.array(e6.string()),doneStatusId:e6.string().nullable().optional()}),service:p,method:"updateProjectDisplaySettings",resultKey:"projects",annotations:ae}),rm({name:"update_jira_project_branch_naming",title:"Update Jira project branch naming",description:"Set the branch-naming script used to derive branch names for a Jira project.",inputSchema:e6.object({projectId:e6.string().min(1),branchNamingScript:e6.string()}),service:p,method:"updateProjectBranchNaming",arguments:({projectId:e,branchNamingScript:t})=>[e,t],resultKey:"projects",annotations:ae}),rm({name:"create_jira_source",title:"Create Jira source",description:"Create a ticket-board source for a Jira project from a JQL query or a board URL.",inputSchema:e6.object({projectId:e6.string().min(1),name:e6.string().min(1),kind:iI,value:e6.string().min(1)}),service:p,method:"createSource",resultKey:"projects",annotations:ai}),rm({name:"update_jira_source",title:"Update Jira source",description:"Update a Jira ticket-board source and clear its cache.",inputSchema:e6.object({id:e6.string().min(1),name:e6.string().min(1),kind:iI,value:e6.string().min(1)}),service:p,method:"updateSource",resultKey:"projects",annotations:ai}),rm({name:"delete_jira_source",title:"Delete Jira source",description:"Delete a Jira ticket-board source and the cached tickets only it referenced.",inputSchema:e6.object({id:e6.string().min(1)}),service:p,method:"deleteSource",arguments:({id:e})=>[e],resultKey:"projects",annotations:at}),rm({name:"update_jira_cache_ttl",title:"Update Jira cache TTL",description:"Set how long Jira API responses stay cached, in minutes (1 to 1440).",inputSchema:e6.object({ttlMinutes:e6.number().int().min(1).max(1440)}),service:p,method:"updateCacheTtl",arguments:({ttlMinutes:e})=>[e],resultKey:"settings",annotations:ae}),rm({name:"refresh_jira_cached_ticket",title:"Refresh Jira cached ticket",description:"Discard the cached copy of a Jira ticket and fetch it again from Jira.",inputSchema:iE,service:p,method:"refreshCachedTicket",arguments:({issueKey:e})=>[e],resultKey:"ticket",annotations:ai}),rm({name:"delete_jira_cached_ticket",title:"Delete Jira cached ticket",description:"Remove a Jira ticket from the local cache without touching Jira.",inputSchema:iE,service:p,method:"deleteCachedTicket",arguments:({issueKey:e})=>[e],resultKey:"deleted",annotations:at})]})],tools:[rm({name:"get_jira_status",title:"Get Jira status",description:"Test the configured Jira connection without exposing credentials.",inputSchema:e6.object({}),service:p,method:"testConnection",arguments:()=>[],resultKey:"status",annotations:ar}),rm({name:"get_jira_projects",title:"Get Jira projects",description:"List configured Jira projects and display settings.",inputSchema:e6.object({}),service:p,method:"listProjects",arguments:()=>[],resultKey:"projects",annotations:ar}),an({name:"get_jira_sources",title:"Get Jira sources",description:"List ticket-board sources configured across Jira projects.",inputSchema:e6.object({}),outputSchema:e6.object({sources:e6.unknown()}),annotations:ar,handler:async()=>({sources:rh((await p.listProjects()).flatMap(e=>e.sources))})}),rm({name:"get_jira_board",title:"Get Jira board",description:"Get tickets for a configured Jira source.",inputSchema:e6.object({sourceId:e6.string().min(1),refresh:e6.boolean().default(!1)}),service:p,method:"ticketBoard",arguments:({sourceId:e,refresh:t})=>[e,t],resultKey:"board",annotations:ar}),rm({name:"get_jira_ticket",title:"Get Jira ticket",description:"Get a Jira ticket and its normalized editable metadata.",inputSchema:iE.extend({refresh:e6.boolean().default(!1)}),service:p,method:"ticket",arguments:({issueKey:e,refresh:t})=>[e,t],resultKey:"ticket",annotations:ar}),rm({name:"get_jira_assignable_users",title:"Get Jira assignable users",description:"Search users who can be assigned to a Jira ticket.",inputSchema:iE.extend({query:e6.string().default("")}),service:p,method:"assignableUsers",arguments:({issueKey:e,query:t})=>[e,t],resultKey:"users",annotations:ar}),rm({name:"get_jira_transitions",title:"Get Jira transitions",description:"Get available transitions for a Jira ticket.",inputSchema:iE,service:p,method:"ticketTransitions",arguments:({issueKey:e})=>[e],resultKey:"transitions",annotations:ar}),rm({name:"get_jira_edit_fields",title:"Get Jira edit fields",description:"Get editable fields and allowed values for a Jira ticket.",inputSchema:iE,service:p,method:"ticketEditFields",arguments:({issueKey:e})=>[e],resultKey:"fields",annotations:ar}),rm({name:"get_jira_ticket_changes",title:"Get Jira ticket changes",description:"Get paginated Jira ticket changelog entries.",inputSchema:iE.extend({limit:e6.number().int().min(1).max(200).default(50),offset:e6.number().int().min(0).default(0)}),service:p,method:"ticketChanges",arguments:e=>[e.issueKey,e.limit,e.offset],resultKey:"page",annotations:ar}),rm({name:"get_jira_worklogs",title:"Get Jira worklogs",description:"Get paginated worklogs for a Jira ticket.",inputSchema:iE.extend({limit:e6.number().int().min(1).max(200).default(50),offset:e6.number().int().min(0).default(0)}),service:p,method:"ticketWorklogs",arguments:e=>[e.issueKey,e.limit,e.offset],resultKey:"page",annotations:ar}),rm({name:"add_jira_comment",title:"Add Jira comment",description:"Add a plain-text or Markdown comment to a Jira ticket.",inputSchema:iE.extend({content:iS}),service:p,method:"addComment",arguments:({issueKey:e,content:t})=>[e,t],resultKey:"ticket",annotations:{...ai,idempotentHint:!1}}),rm({name:"assign_jira_ticket",title:"Assign Jira ticket",description:"Assign or unassign a Jira ticket.",inputSchema:iE.extend({accountId:e6.string().nullable().optional()}),service:p,method:"assignTicket",arguments:({issueKey:e,accountId:t})=>[e,t??null],resultKey:"ticket",annotations:ai}),rm({name:"transition_jira_ticket",title:"Transition Jira ticket",description:"Apply an available status transition to a Jira ticket.",inputSchema:iE.extend({transitionId:e6.string().min(1)}),service:p,method:"transitionTicket",arguments:({issueKey:e,transitionId:t})=>[e,t],resultKey:"ticket",annotations:ai}),rm({name:"update_jira_ticket",title:"Update Jira ticket",description:"Update supported editable fields on a Jira ticket.",inputSchema:iE.extend({summary:e6.string().nullable().optional(),description:iS.nullable().optional(),priorityId:e6.string().nullable().optional(),labels:e6.array(e6.string()).nullable().optional(),componentIds:e6.array(e6.string()).nullable().optional(),fixVersionIds:e6.array(e6.string()).nullable().optional(),affectedVersionIds:e6.array(e6.string()).nullable().optional(),dueDate:e6.string().nullable().optional()}),service:p,method:"updateTicket",resultKey:"ticket",annotations:ai}),rm({name:"transition_jira_ticket_to_done",title:"Transition Jira ticket to done",description:"Move a Jira ticket to the done status configured for its project.",inputSchema:iE,service:p,method:"transitionTicketToConfiguredDone",arguments:({issueKey:e})=>[e],resultKey:"ticket",annotations:ai}),rm({name:"resolve_jira_branch",title:"Resolve Jira branch",description:"Resolve the configured branch name for a Jira ticket.",inputSchema:iE,service:p,method:"branchTicket",arguments:({issueKey:e})=>[e],resultKey:"branch",annotations:ar}),rm({name:"create_jira_ticket",title:"Create Jira ticket",description:"Create a Jira ticket with typed core fields and optional additional fields.",inputSchema:e6.object({projectKey:e6.string().min(1),issueTypeId:e6.string().min(1),summary:e6.string().min(1),description:iS.nullable().optional(),fields:e6.record(e6.string(),e6.unknown()).nullable().optional()}),service:p,method:"createTicket",resultKey:"ticket",annotations:{...ai,idempotentHint:!1}}),rm({name:"add_jira_worklog",title:"Add Jira worklog",description:"Add a time-spent worklog to a Jira ticket.",inputSchema:iE.extend({timeSpentSeconds:e6.number().int().positive(),startedAt:e6.string().nullable().optional(),comment:iS.nullable().optional()}),service:p,method:"addWorklog",resultKey:"ticket",annotations:{...ai,idempotentHint:!1}}),rm({name:"link_jira_tickets",title:"Link Jira tickets",description:"Create a typed relationship between two Jira tickets.",inputSchema:e6.object({inwardIssueKey:e6.string().min(1),outwardIssueKey:e6.string().min(1),linkType:e6.string().min(1)}),service:p,method:"linkTickets",resultKey:"ticket",annotations:{...ai,idempotentHint:!1}})]})),e.github&&j.push((m=e.github,{id:"builtin:github",name:"GitHub",children:[],tools:[rm({name:"get_github_status",title:"Get GitHub status",description:"Test the configured GitHub connection without exposing credentials.",inputSchema:e6.object({}),service:m,method:"testConnection",arguments:()=>[],resultKey:"status",annotations:ar}),rm({name:"get_github_repositories",title:"Get GitHub repositories",description:"List configured GitHub repositories.",inputSchema:e6.object({}),service:m,method:"listRepositories",arguments:()=>[],resultKey:"repositories",annotations:ar}),rm({name:"get_pull_requests",title:"Get pull requests",description:"List GitHub pull requests by scope, repository, and state.",inputSchema:e6.object({scope:e6.enum(["MINE","REVIEW_REQUESTED","REPOSITORY"]),repositoryId:e6.string().nullable().optional(),state:e6.enum(["ALL","OPEN","CLOSED","MERGED"]).default("OPEN"),first:e6.number().int().min(1).max(100).default(25),after:e6.string().nullable().optional(),includePipelineJobs:e6.boolean().default(!1)}),service:m,method:"pullRequests",arguments:e=>[e.scope,e.repositoryId,{includePipelineJobs:e.includePipelineJobs,state:e.state,first:e.first,after:e.after,requestSource:iw}],resultKey:"page",annotations:ar}),rm({name:"get_pull_request",title:"Get pull request",description:"Get a GitHub pull request by repository and number.",inputSchema:iv,service:m,method:"pullRequest",arguments:e=>[e.owner,e.name,e.number,iw],resultKey:"pullRequest",annotations:ar}),rm({name:"get_pull_request_merge_options",title:"Get pull request merge options",description:"Get merge eligibility, methods, and commit-email choices for a pull request.",inputSchema:iv,service:m,method:"pullRequestMergeOptions",arguments:e=>[e.owner,e.name,e.number,iw],resultKey:"options",annotations:ar}),rm({name:"get_review_threads",title:"Get review threads",description:"List tracked GitHub review threads.",inputSchema:e6.object({}),service:m,method:"reviewThreads",arguments:()=>[],resultKey:"threads",annotations:ar}),rm({name:"get_actions_runs",title:"Get Actions runs",description:"List GitHub Actions workflow runs with repository and branch filters.",inputSchema:e6.object({codebaseRepositoryId:e6.string().nullable().optional(),branch:e6.string().nullable().optional(),workflowId:e6.string().nullable().optional(),first:e6.number().int().min(1).max(100).default(25),after:e6.string().nullable().optional()}),service:m,method:"actionsWorkflowRuns",arguments:e=>[e.codebaseRepositoryId,e.first,e.after,e.branch,e.workflowId,iw],resultKey:"page",annotations:ar}),rm({name:"get_actions_jobs",title:"Get Actions jobs",description:"Get jobs for a GitHub Actions workflow run.",inputSchema:e6.object({codebaseRepositoryId:e6.string().min(1),workflowRunId:e6.string().min(1)}),service:m,method:"actionsWorkflowJobs",arguments:e=>[e.codebaseRepositoryId,e.workflowRunId,iw],resultKey:"jobs",annotations:ar}),rm({name:"get_actions_run_attempt",title:"Get Actions run attempt",description:"Get one attempt of a GitHub Actions workflow run.",inputSchema:e6.object({repositoryId:e6.string().min(1),workflowRunId:e6.string().min(1),attempt:e6.number().int().positive(),includeJobs:e6.boolean().default(!0)}),service:m,method:"actionsWorkflowRunAttempt",arguments:e=>[e.repositoryId,e.workflowRunId,e.attempt,e.includeJobs,iw],resultKey:"attempt",annotations:ar}),rm({name:"get_repository_workflows",title:"Get repository workflows",description:"List GitHub Actions workflows for a configured repository.",inputSchema:e6.object({codebaseRepositoryId:e6.string().min(1)}),service:m,method:"repositoryWorkflows",arguments:({codebaseRepositoryId:e})=>[e,iw],resultKey:"workflows",annotations:ar}),rm({name:"get_auto_retry_rules",title:"Get auto-retry rules",description:"List GitHub pipeline auto-retry rules.",inputSchema:e6.object({codebaseRepositoryId:e6.string().nullable().optional(),workflowRunId:e6.string().nullable().optional()}),service:m,method:"autoRetryRules",resultKey:"rules",annotations:ar}),rm({name:"get_github_rate_limits",title:"Get GitHub rate limits",description:"Get recently observed GitHub API rate-limit snapshots.",inputSchema:e6.object({}),service:m,method:"rateLimitSnapshots",arguments:()=>[],resultKey:"snapshots",annotations:ar}),rm({name:"create_pull_request",title:"Create pull request",description:"Create a GitHub pull request using configured GitHub App credentials.",inputSchema:e6.object({owner:e6.string().min(1),name:e6.string().min(1),baseRefName:e6.string().min(1),headRefName:e6.string().min(1),title:e6.string().min(1),body:e6.string().nullable().optional(),draft:e6.boolean().nullable().optional()}),service:m,method:"createPullRequest",resultKey:"pullRequest",annotations:{...ai,idempotentHint:!1}}),rm({name:"update_pull_request",title:"Update pull request",description:"Update a pull request title, body, or draft state on GitHub.",inputSchema:iv.extend({title:e6.string().nullable().optional(),body:e6.string().nullable().optional(),draft:e6.boolean().nullable().optional()}),service:m,method:"updatePullRequest",resultKey:"pullRequest",annotations:ai}),rm({name:"submit_pull_request_review",title:"Submit pull request review",description:"Approve, comment on, or request changes to a pull request.",inputSchema:iv.extend({event:e6.enum(["APPROVE","REQUEST_CHANGES","COMMENT"]),body:e6.string().nullable().optional()}),service:m,method:"submitPullRequestReview",resultKey:"pullRequest",annotations:{...ai,idempotentHint:!1}}),rm({name:"request_pull_request_reviewers",title:"Request pull request reviewers",description:"Request GitHub users or organization teams to review a pull request.",inputSchema:iv.extend({reviewers:e6.array(e6.string()).default([]),teamReviewers:e6.array(e6.string()).default([])}),service:m,method:"requestPullRequestReviewers",resultKey:"pullRequest",annotations:ai}),rm({name:"dispatch_github_workflow",title:"Dispatch GitHub workflow",description:"Dispatch a workflow_dispatch-enabled GitHub Actions workflow.",inputSchema:e6.object({repositoryId:e6.string().min(1),workflowId:e6.string().min(1),ref:e6.string().min(1),inputs:e6.record(e6.string(),e6.string()).nullable().optional()}),service:m,method:"dispatchWorkflow",resultKey:"dispatched",annotations:{...ai,idempotentHint:!1}}),rm({name:"merge_pull_request",title:"Merge pull request",description:"Merge a GitHub pull request with an enabled merge method.",inputSchema:iv.extend({method:e6.enum(["MERGE","SQUASH","REBASE"]),commitHeadline:e6.string().min(1),commitBody:e6.string().default(""),authorEmail:e6.string().nullable().optional()}),service:m,method:"mergePullRequest",arguments:e=>[e,iw],resultKey:"pullRequest",annotations:ai}),rm({name:"set_pull_request_labels",title:"Set pull request labels",description:"Replace labels on a GitHub pull request.",inputSchema:iv.extend({labels:e6.array(e6.string())}),service:m,method:"setPullRequestLabels",resultKey:"pullRequest",annotations:ai}),rm({name:"reply_review_thread",title:"Reply to review thread",description:"Post a reply to a GitHub pull-request review thread.",inputSchema:e6.object({threadId:e6.string().min(1),body:e6.string().min(1)}),service:m,method:"replyToReviewThread",arguments:({threadId:e,body:t})=>[e,t],resultKey:"thread",annotations:{...ai,idempotentHint:!1}}),rm({name:"set_review_thread_resolved",title:"Set review thread resolved",description:"Resolve or unresolve a GitHub review thread.",inputSchema:e6.object({threadId:e6.string().min(1),resolved:e6.boolean()}),service:m,method:"setReviewThreadResolved",arguments:({threadId:e,resolved:t})=>[e,t],resultKey:"thread",annotations:ai}),rm({name:"retry_pipeline",title:"Retry pipeline",description:"Retry a failed GitHub check suite.",inputSchema:e6.object({repositoryId:e6.string().min(1),checkSuiteId:e6.string().min(1)}),service:m,method:"retryPipeline",arguments:e=>[e.repositoryId,e.checkSuiteId,iw,ib],resultKey:"pipeline",annotations:ai}),rm({name:"retry_workflow_job",title:"Retry workflow job",description:"Retry one failed job in a GitHub Actions workflow run.",inputSchema:e6.object({repositoryId:e6.string().min(1),checkSuiteId:e6.string().min(1),jobId:e6.string().min(1)}),service:m,method:"retryWorkflowJob",arguments:e=>[e.repositoryId,e.checkSuiteId,e.jobId,iw,ib],resultKey:"job",annotations:ai}),rm({name:"cancel_actions_run",title:"Cancel Actions run",description:"Cancel a GitHub Actions workflow run.",inputSchema:e6.object({codebaseRepositoryId:e6.string().min(1),workflowRunId:e6.string().min(1),force:e6.boolean().default(!1)}),service:m,method:"cancelActionsWorkflowRun",arguments:e=>[e.codebaseRepositoryId,e.workflowRunId,e.force,iw,ib],resultKey:"run",annotations:ai}),rm({name:"save_auto_retry_rule",title:"Save auto-retry rule",description:"Create or update a GitHub pipeline auto-retry rule.",inputSchema:e6.object({id:e6.string().nullable().optional(),scope:e6.string().min(1),codebaseRepositoryId:e6.string().min(1),repositoryGithubId:e6.string().nullable().optional(),worktreeId:e6.string().nullable().optional(),branch:e6.string().nullable().optional(),pullRequestNumber:e6.number().int().positive().nullable().optional(),allWorkflows:e6.boolean(),mode:e6.string().min(1),retryLimit:e6.number().int().min(0).nullable().optional(),failureStrategy:e6.string().min(1),targets:e6.array(e6.object({workflowId:e6.string().nullable().optional(),workflowRunId:e6.string().nullable().optional(),jobName:e6.string().nullable().optional()}))}),service:m,method:"saveAutoRetryRule",resultKey:"rule",annotations:ai})]})),e.gitlab&&j.push((f=e.gitlab,{id:"builtin:gitlab",name:"GitLab",children:[],tools:[rm({name:"gitlab_get_status",title:"Get GitLab status",description:"Test the configured GitLab connection.",inputSchema:e6.object({}),service:f,method:"testConnection",arguments:()=>[],resultKey:"status",annotations:ar}),rm({name:"gitlab_get_projects",title:"Get GitLab projects",description:"List the GitLab projects managed by AIDE.",inputSchema:e6.object({}),service:f,method:"projects",arguments:()=>[],resultKey:"projects",annotations:ar}),rm({name:"gitlab_get_merge_requests",title:"Get GitLab merge requests",description:"List accessible GitLab merge requests.",inputSchema:e6.object({scope:e6.enum(["MINE","REVIEW_REQUESTED","PROJECT","ALL"]),projectId:e6.string().nullable().optional(),state:e6.enum(["OPENED","CLOSED","MERGED","ALL"]).default("OPENED"),page:e6.number().int().positive().default(1),perPage:e6.number().int().min(1).max(100).default(25)}),service:f,method:"mergeRequests",resultKey:"page",annotations:ar}),rm({name:"gitlab_get_merge_request",title:"Get GitLab merge request",description:"Get a merge request with discussions and pipelines.",inputSchema:ik,service:f,method:"mergeRequest",arguments:({projectId:e,iid:t})=>[e,t],resultKey:"mergeRequest",annotations:ar}),rm({name:"gitlab_create_merge_request",title:"Create GitLab merge request",description:"Create a GitLab merge request.",inputSchema:e6.object({projectId:e6.string().min(1),sourceBranch:e6.string().min(1),targetBranch:e6.string().min(1),title:e6.string().min(1),description:e6.string().nullable().optional(),removeSourceBranch:e6.boolean().nullable().optional(),squash:e6.boolean().nullable().optional(),reviewerIds:e6.array(e6.string()).nullable().optional(),labels:e6.array(e6.string()).nullable().optional()}),service:f,method:"createMergeRequest",resultKey:"mergeRequest",annotations:{...ai,idempotentHint:!1}}),rm({name:"gitlab_update_merge_request",title:"Update GitLab merge request",description:"Update title, description, state, labels, or reviewers.",inputSchema:ik.extend({title:e6.string().nullable().optional(),description:e6.string().nullable().optional(),stateEvent:e6.enum(["CLOSE","REOPEN"]).nullable().optional(),reviewerIds:e6.array(e6.string()).nullable().optional(),labels:e6.array(e6.string()).nullable().optional()}),service:f,method:"updateMergeRequest",resultKey:"mergeRequest",annotations:ai}),rm({name:"gitlab_set_merge_request_labels",title:"Set GitLab merge request labels",description:"Replace the labels on a GitLab merge request.",inputSchema:ik.extend({labels:e6.array(e6.string())}),service:f,method:"updateMergeRequest",resultKey:"mergeRequest",annotations:ai}),rm({name:"gitlab_request_merge_request_reviewers",title:"Request GitLab merge request reviewers",description:"Replace the reviewers on a GitLab merge request.",inputSchema:ik.extend({reviewerIds:e6.array(e6.string())}),service:f,method:"updateMergeRequest",resultKey:"mergeRequest",annotations:ai}),rm({name:"gitlab_submit_review",title:"Submit GitLab review",description:"Approve, comment on, or request changes on a merge request.",inputSchema:ik.extend({outcome:e6.enum(["APPROVE","COMMENT","REQUEST_CHANGES"]),body:e6.string().nullable().optional()}),service:f,method:"submitReview",resultKey:"submitted",annotations:{...ai,idempotentHint:!1}}),rm({name:"gitlab_reply_discussion",title:"Reply to GitLab discussion",description:"Reply to a merge-request discussion.",inputSchema:ik.extend({discussionId:e6.string().min(1),body:e6.string().min(1)}),service:f,method:"replyToDiscussion",resultKey:"discussion",annotations:{...ai,idempotentHint:!1}}),rm({name:"gitlab_set_discussion_resolved",title:"Resolve GitLab discussion",description:"Resolve or reopen a merge-request discussion.",inputSchema:ik.extend({discussionId:e6.string().min(1),resolved:e6.boolean()}),service:f,method:"setDiscussionResolved",resultKey:"discussion",annotations:ai}),rm({name:"gitlab_merge_merge_request",title:"Merge GitLab merge request",description:"Merge now or enable auto-merge for a GitLab merge request.",inputSchema:ik.extend({squash:e6.boolean().nullable().optional(),removeSourceBranch:e6.boolean().nullable().optional(),autoMerge:e6.boolean().nullable().optional(),sha:e6.string().nullable().optional()}),service:f,method:"mergeMergeRequest",resultKey:"mergeRequest",annotations:ai}),rm({name:"gitlab_get_pipelines",title:"Get GitLab pipelines",description:"List pipelines for a GitLab project.",inputSchema:e6.object({projectId:e6.string().min(1),page:e6.number().int().positive().default(1),perPage:e6.number().int().min(1).max(100).default(25)}),service:f,method:"pipelines",arguments:({projectId:e,page:t,perPage:r})=>[e,t,r],resultKey:"page",annotations:ar}),rm({name:"gitlab_get_pipeline",title:"Get GitLab pipeline",description:"Get a GitLab pipeline by project and pipeline ID.",inputSchema:e6.object({projectId:e6.string().min(1),pipelineId:e6.string().min(1)}),service:f,method:"pipeline",arguments:({projectId:e,pipelineId:t})=>[e,t],resultKey:"pipeline",annotations:ar}),rm({name:"gitlab_get_pipeline_jobs",title:"Get GitLab pipeline jobs",description:"List jobs for a GitLab pipeline.",inputSchema:e6.object({projectId:e6.string().min(1),pipelineId:e6.string().min(1)}),service:f,method:"pipelineJobs",arguments:({projectId:e,pipelineId:t})=>[e,t],resultKey:"jobs",annotations:ar}),rm({name:"gitlab_create_pipeline",title:"Create GitLab pipeline",description:"Create a pipeline for a ref and optional variables.",inputSchema:e6.object({projectId:e6.string().min(1),ref:e6.string().min(1),variables:e6.array(e6.object({key:e6.string().min(1),value:e6.string()})).default([])}),service:f,method:"createPipeline",arguments:({projectId:e,ref:t,variables:r})=>[e,t,r],resultKey:"pipeline",annotations:{...ai,idempotentHint:!1}}),rm({name:"gitlab_retry_pipeline",title:"Retry GitLab pipeline",description:"Retry failed or canceled jobs in a GitLab pipeline.",inputSchema:e6.object({projectId:e6.string().min(1),pipelineId:e6.string().min(1)}),service:f,method:"retryPipeline",arguments:({projectId:e,pipelineId:t})=>[e,t],resultKey:"pipeline",annotations:ai}),rm({name:"gitlab_cancel_pipeline",title:"Cancel GitLab pipeline",description:"Cancel a running GitLab pipeline.",inputSchema:e6.object({projectId:e6.string().min(1),pipelineId:e6.string().min(1)}),service:f,method:"cancelPipeline",arguments:({projectId:e,pipelineId:t})=>[e,t],resultKey:"pipeline",annotations:ai}),rm({name:"gitlab_retry_job",title:"Retry GitLab job",description:"Retry a failed or canceled GitLab job.",inputSchema:e6.object({projectId:e6.string().min(1),jobId:e6.string().min(1)}),service:f,method:"retryJob",arguments:({projectId:e,jobId:t})=>[e,t],resultKey:"job",annotations:ai}),rm({name:"gitlab_get_auto_retry_rules",title:"Get GitLab auto-retry rules",description:"List GitLab pipeline auto-retry rules.",inputSchema:e6.object({projectId:e6.string().nullable().optional()}),service:f,method:"autoRetryRules",arguments:({projectId:e})=>[e],resultKey:"rules",annotations:ar}),rm({name:"gitlab_save_auto_retry_rule",title:"Save GitLab auto-retry rule",description:"Create or update a GitLab pipeline auto-retry rule.",inputSchema:e6.object({id:e6.string().nullable().optional(),projectId:e6.string().min(1),pipelineId:e6.string().nullable().optional(),enabled:e6.boolean().nullable().optional(),maxAttempts:e6.number().int().min(1).max(100)}),service:f,method:"saveAutoRetryRule",resultKey:"rule",annotations:ai}),rm({name:"gitlab_delete_auto_retry_rule",title:"Delete GitLab auto-retry rule",description:"Permanently delete a GitLab pipeline auto-retry rule.",inputSchema:e6.object({id:e6.string().min(1)}),service:f,method:"deleteAutoRetryRule",arguments:({id:e})=>[e],resultKey:"deleted",annotations:ai}),rm({name:"gitlab_get_rate_limits",title:"Get GitLab rate limits",description:"Get recently observed GitLab API rate-limit snapshots.",inputSchema:e6.object({}),service:f,method:"rateLimitSnapshots",arguments:()=>[],resultKey:"snapshots",annotations:ar})]})),e.skills&&j.push((g=e.skills,{id:"builtin:skills",name:"Skills",children:[],tools:[rm({name:"get_skills_overview",title:"Get skills overview",description:"List skills, groups, installations, and sync status.",inputSchema:e6.object({search:e6.string().default("")}),service:g,method:"overview",arguments:({search:e})=>[e],resultKey:"overview"}),rm({name:"get_skill",title:"Get skill",description:"Get one skill and its deployments.",inputSchema:e6.object({id:e6.string().min(1)}),service:g,method:"getSkill",arguments:({id:e})=>[e],resultKey:"skill"}),an({name:"get_skill_groups",title:"Get skill groups",description:"Get skill groups, optionally for one repository.",inputSchema:e6.object({repositoryId:e6.string().nullable().optional()}),outputSchema:e6.object({groups:e6.unknown()}),handler:async({repositoryId:e})=>({groups:rh(e?await g.groupsForRepository(e):(await g.overview()).groups)})}),rm({name:"get_skill_sync_run",title:"Get skill sync run",description:"Inspect a skill synchronization run and its conflicts.",inputSchema:e6.object({id:e6.string().min(1)}),service:g,method:"getRun",arguments:({id:e})=>[e],resultKey:"run"}),rm({name:"save_skill",title:"Save skill",description:"Create or update a managed skill.",inputSchema:e6.object({input:e6.record(e6.string(),e6.unknown())}),service:g,method:"saveSkill",arguments:({input:e})=>[e],resultKey:"skill",annotations:ae}),rm({name:"delete_skill",title:"Delete skill",description:"Delete a managed skill and its associations.",inputSchema:e6.object({id:e6.string().min(1)}),service:g,method:"deleteSkill",arguments:({id:e})=>[e],resultKey:"deleted",annotations:at}),rm({name:"save_skill_group",title:"Save skill group",description:"Create or update a managed skill group.",inputSchema:e6.object({input:e6.record(e6.string(),e6.unknown())}),service:g,method:"saveGroup",arguments:({input:e})=>[e],resultKey:"group",annotations:ae}),rm({name:"delete_skill_group",title:"Delete skill group",description:"Delete a managed skill group.",inputSchema:e6.object({id:e6.string().min(1)}),service:g,method:"deleteGroup",arguments:({id:e})=>[e],resultKey:"deleted",annotations:at}),rm({name:"update_skill_settings",title:"Update skill settings",description:"Update managed skill locations and reconciliation settings.",inputSchema:e6.object({input:e6.record(e6.string(),e6.unknown())}),service:g,method:"saveSettings",arguments:({input:e})=>[e],resultKey:"settings",annotations:ae}),rm({name:"prepare_skill_sync",title:"Prepare skill sync",description:"Prepare a push or pull skill synchronization run.",inputSchema:e6.object({kind:e6.enum(["ALL","GROUP"]),groupId:e6.string().nullable().optional()}),service:g,method:"prepareSync",arguments:({kind:e,groupId:t})=>[e,t??null],resultKey:"run",annotations:ae}),rm({name:"resolve_skill_sync_conflict",title:"Resolve skill sync conflict",description:"Choose a resolution for one skill synchronization conflict.",inputSchema:e6.object({input:e6.record(e6.string(),e6.unknown())}),service:g,method:"resolveItem",arguments:({input:e})=>[e],resultKey:"run",annotations:ae}),rm({name:"skip_skill_sync",title:"Skip skill sync",description:"Skip remaining pending work in a skill synchronization run.",inputSchema:e6.object({runId:e6.string().min(1)}),service:g,method:"skipPending",arguments:({runId:e})=>[e],resultKey:"run",annotations:ae}),rm({name:"apply_skill_sync",title:"Apply skill sync",description:"Apply all resolved items in a prepared skill synchronization run.",inputSchema:e6.object({runId:e6.string().min(1)}),service:g,method:"applyRun",arguments:({runId:e})=>[e],resultKey:"run",annotations:ae})]})),e.buildData&&j.push((y=e.buildData,{id:"builtin:build-data",name:"Build Data",children:[],tools:[rm({name:"get_build_data_collection",title:"Get build data collection",description:"Get a derived-data collection and its entries.",inputSchema:e6.object({id:e6.string().min(1)}),service:y,method:"getCollection",arguments:({id:e})=>[e],resultKey:"collection"}),rm({name:"get_build_data_deletion_history",title:"Get build data deletion history",description:"Get paginated build-data cleanup history.",inputSchema:e6.object({first:e6.number().int().min(1).max(500).default(100),after:e6.string().nullable().optional()}),service:y,method:"history",arguments:({first:e,after:t})=>[e,t],resultKey:"page"}),rm({name:"refresh_build_data",title:"Refresh build data",description:"Collect current derived-data entries from enrolled agents.",inputSchema:e6.object({requestId:e6.string().nullable().optional()}),service:y,method:"refresh",arguments:({requestId:e})=>[e],resultKey:"collection",annotations:ae}),rm({name:"calculate_build_data_sizes",title:"Calculate build data sizes",description:"Calculate accurate sizes for selected build-data entries.",inputSchema:e6.object({collectionId:e6.string().min(1),entryIds:e6.array(e6.string().min(1)).min(1),requestId:e6.string().min(1)}),service:y,method:"calculateSizes",arguments:e=>[e.collectionId,e.entryIds,e.requestId],resultKey:"collection",annotations:ae}),rm({name:"delete_build_data_entries",title:"Delete build data entries",description:"Delete selected derived-data entries from their agents.",inputSchema:e6.object({collectionId:e6.string().min(1),entryIds:e6.array(e6.string().min(1)).min(1),requestId:e6.string().min(1),overrideProtection:e6.boolean().default(!1)}),service:y,method:"deleteEntries",arguments:e=>[e.collectionId,e.entryIds,e.requestId,e.overrideProtection],resultKey:"collection",annotations:at}),rm({name:"clear_build_data_history",title:"Clear build data history",description:"Permanently clear build-data deletion history.",inputSchema:e6.object({}),service:y,method:"clearHistory",arguments:()=>[],resultKey:"count",annotations:at}),rm({name:"set_build_data_lock",title:"Set build data lock",description:"Lock or unlock a build-data entry to control cleanup eligibility.",inputSchema:e6.object({collectionId:e6.string().min(1),entryId:e6.string().min(1),locked:e6.boolean()}),service:y,method:"setEntryLocked",arguments:e=>[e.collectionId,e.entryId,e.locked],resultKey:"entry",annotations:ae})]})),e.signingAssets&&j.push((w=e.signingAssets,{id:"builtin:signing-assets",name:"Signing Assets",children:[],tools:[rm({name:"get_signing_agents",title:"Get signing agents",description:"List agents and signing-asset availability.",inputSchema:e6.object({}),service:w,method:"agents",arguments:()=>[],resultKey:"agents"}),rm({name:"get_signing_profiles",title:"Get signing profiles",description:"List provisioning-profile metadata without profile contents.",inputSchema:e6.object({}),service:w,method:"profiles",arguments:()=>[],resultKey:"profiles"}),rm({name:"get_signing_profile",title:"Get signing profile",description:"Get one provisioning profile and matched devices.",inputSchema:e6.object({id:e6.string().min(1)}),service:w,method:"profile",arguments:({id:e})=>[e],resultKey:"profile"}),rm({name:"get_signing_certificates",title:"Get signing certificates",description:"List signing-certificate metadata without private keys or P12 files.",inputSchema:e6.object({}),service:w,method:"certificates",arguments:()=>[],resultKey:"certificates"}),rm({name:"get_signing_operations",title:"Get signing operations",description:"List recent signing-asset operation history.",inputSchema:e6.object({limit:e6.number().int().min(1).max(500).default(50)}),service:w,method:"operations",arguments:({limit:e})=>[e],resultKey:"operations"}),rm({name:"get_apple_portal_inventory",title:"Get Apple portal inventory",description:"Get provisioning profiles, certificates, devices, and identifiers visible in the Apple Developer portal.",inputSchema:e6.object({}),service:w,method:"portalInventory",arguments:()=>[],resultKey:"inventory",annotations:ar}),rm({name:"refresh_signing_assets",title:"Refresh signing assets",description:"Refresh signing-asset inventory from selected or all agents.",inputSchema:e6.object({agentIds:e6.array(e6.string().min(1)).optional()}),service:w,method:"refresh",arguments:({agentIds:e})=>[e],resultKey:"operation",annotations:ae}),rm({name:"download_signing_profile",title:"Download signing profile",description:"Download an Apple provisioning profile to an agent; profile contents are not returned.",inputSchema:e6.object({uuid:e6.string().min(1),agentId:e6.string().min(1)}),service:w,method:"downloadProfile",arguments:e=>[e.uuid,e.agentId],resultKey:"operation",mapResult:e=>({uuid:"string"==typeof e.uuid?e.uuid:null,filename:"string"==typeof e.filename?e.filename:null}),annotations:ae}),rm({name:"sync_signing_profile",title:"Sync signing profile",description:"Synchronize a provisioning profile between agents.",inputSchema:e6.object({uuid:e6.string().min(1),sourceAgentId:e6.string().min(1),targetAgentIds:e6.array(e6.string().min(1)).min(1)}),service:w,method:"syncProfile",arguments:e=>[e.uuid,e.sourceAgentId,e.targetAgentIds],resultKey:"operation",annotations:ae}),rm({name:"delete_signing_profile",title:"Delete signing profile",description:"Delete a provisioning profile from selected agents.",inputSchema:e6.object({uuid:e6.string().min(1),agentIds:e6.array(e6.string().min(1)).min(1)}),service:w,method:"deleteProfile",arguments:e=>[e.uuid,e.agentIds],resultKey:"operation",annotations:at}),rm({name:"delete_expired_signing_profiles",title:"Delete expired signing profiles",description:"Delete expired provisioning profiles from selected or all agents.",inputSchema:e6.object({agentIds:e6.array(e6.string().min(1)).optional()}),service:w,method:"deleteExpiredProfiles",arguments:({agentIds:e})=>[e],resultKey:"operation",annotations:at})]})),e.iosDevices&&j.push((b=e.iosDevices,{id:"builtin:ios-devices",name:"iOS Devices",children:[],tools:[rm({name:"get_ios_devices",title:"Get iOS devices",description:"List enrolled and pending iOS devices.",inputSchema:e6.object({status:e6.enum(["PENDING","REGISTERING","REGISTERED","REGISTRATION_FAILED","REJECTED"]).nullable().optional()}),service:b,method:"devices",arguments:({status:e})=>[e],resultKey:"devices"}),rm({name:"get_ios_device",title:"Get iOS device",description:"Get one enrolled or pending iOS device.",inputSchema:e6.object({id:e6.string().min(1)}),service:b,method:"device",arguments:({id:e})=>[e],resultKey:"device"}),rm({name:"get_ios_device_firmware",title:"Get iOS device firmware",description:"Get firmware metadata discovered for an iOS device.",inputSchema:e6.object({id:e6.string().min(1)}),service:b,method:"deviceFirmware",arguments:({id:e})=>[e],resultKey:"firmware"}),rm({name:"get_ios_device_settings",title:"Get iOS device settings",description:"Get redacted enrollment and App Store Connect settings.",inputSchema:e6.object({}),service:b,method:"getSettings",arguments:()=>[],resultKey:"settings"}),rm({name:"rename_ios_device",title:"Rename iOS device",description:"Change the display name of an iOS device.",inputSchema:e6.object({id:e6.string().min(1),displayName:e6.string().min(1)}),service:b,method:"renameDevice",arguments:e=>[e.id,e.displayName],resultKey:"device",annotations:ai}),rm({name:"register_ios_device",title:"Register iOS device",description:"Register a pending iOS device with the Apple Developer portal.",inputSchema:e6.object({id:e6.string().min(1)}),service:b,method:"registerDevice",arguments:({id:e})=>[e],resultKey:"device",annotations:ai}),rm({name:"reject_ios_device",title:"Reject iOS device",description:"Reject a pending iOS device enrollment.",inputSchema:e6.object({id:e6.string().min(1)}),service:b,method:"rejectDevice",arguments:({id:e})=>[e],resultKey:"device",annotations:ai}),rm({name:"delete_ios_device",title:"Delete iOS device",description:"Permanently delete an iOS device record.",inputSchema:e6.object({id:e6.string().min(1)}),service:b,method:"deleteDevice",arguments:({id:e})=>[e],resultKey:"deleted",annotations:aa})]})),e.notifications&&j.push((v=e.notifications,{id:"builtin:notifications",name:"Notifications",children:[],tools:[rm({name:"get_notification_history",title:"Get notification history",description:"Get paginated application notification history.",inputSchema:e6.object({first:e6.number().int().min(1).max(500).default(100),after:e6.string().nullable().optional()}),service:v,method:"history",resultKey:"page"}),rm({name:"get_notification_preferences",title:"Get notification preferences",description:"Get notification-category preferences.",inputSchema:e6.object({}),service:v,method:"preferences",arguments:()=>[],resultKey:"preferences"}),rm({name:"get_notification_sidebar",title:"Get notification sidebar",description:"Get unread and recent notification sidebar state.",inputSchema:e6.object({limit:e6.number().int().min(1).max(200).default(25)}),service:v,method:"sidebar",arguments:({limit:e})=>[e],resultKey:"sidebar"}),rm({name:"get_web_push_status",title:"Get web-push status",description:"Get redacted web-push readiness and subscription status.",inputSchema:e6.object({}),service:v,method:"webPushState",arguments:()=>[],resultKey:"status",annotations:ar}),rm({name:"update_notification_preference",title:"Update notification preference",description:"Update one notification-category preference.",inputSchema:e6.object({input:e6.object({typeKey:e6.string().min(1),sidebarEnabled:e6.boolean(),browserEnabled:e6.boolean(),webPushEnabled:e6.boolean()})}),service:v,method:"savePreference",arguments:({input:e})=>[e],resultKey:"preference",annotations:ae}),rm({name:"dismiss_notification",title:"Dismiss notification",description:"Dismiss one application notification.",inputSchema:e6.object({id:e6.string().min(1)}),service:v,method:"dismiss",arguments:({id:e})=>[e],resultKey:"dismissed",annotations:ae}),rm({name:"dismiss_all_notifications",title:"Dismiss all notifications",description:"Dismiss every current application notification.",inputSchema:e6.object({}),service:v,method:"dismissAll",arguments:()=>[],resultKey:"count",annotations:ae}),rm({name:"delete_notifications",title:"Delete notifications",description:"Permanently delete notifications selected by IDs or filters.",inputSchema:e6.object({selection:e6.object({all:e6.boolean().nullable().optional(),ids:e6.array(e6.string().min(1)).nullable().optional(),excludedIds:e6.array(e6.string().min(1)).nullable().optional(),ranges:e6.array(e6.object({start:iA.iso.datetime(),end:iA.iso.datetime()})).nullable().optional(),excludedRanges:e6.array(e6.object({start:iA.iso.datetime(),end:iA.iso.datetime()})).nullable().optional()})}),service:v,method:"deleteSelection",arguments:({selection:e})=>[e],resultKey:"count",annotations:at}),rm({name:"test_web_push_subscription",title:"Test web-push subscription",description:"Send a test notification to a saved web-push subscription.",inputSchema:e6.object({id:e6.string().min(1)}),service:v,method:"testWebPushSubscription",arguments:({id:e})=>[e],resultKey:"sent",annotations:ai})]})),e.ccusage&&e.modelCosts&&j.push((k=e.ccusage,E=e.modelCosts,{id:"builtin:usage-costs",name:"Usage and Costs",children:[],tools:[rm({name:"collect_ccusage",title:"Collect ccusage",description:"Collect current local AI-provider usage from enrolled agents.",inputSchema:e6.object({requestId:e6.string().nullable().optional()}),service:k,method:"collect",arguments:({requestId:e})=>[e],resultKey:"collection",annotations:ae}),rm({name:"get_ccusage_collection",title:"Get ccusage collection",description:"Get a usage collection and aggregated model usage.",inputSchema:e6.object({id:e6.string().min(1)}),service:k,method:"getCollection",arguments:({id:e})=>[e],resultKey:"collection"}),rm({name:"get_model_cost_catalog",title:"Get model cost catalog",description:"Get the active model-pricing catalog and refresh metadata.",inputSchema:e6.object({}),service:E,method:"getCatalog",arguments:()=>[],resultKey:"catalog",annotations:ar}),rm({name:"get_model_cost_entries",title:"Get model cost entries",description:"List model-pricing entries with search and pagination.",inputSchema:e6.object({search:e6.string().nullable().optional(),first:e6.number().int().min(1).max(500).default(100),offset:e6.number().int().min(0).default(0),sortKey:e6.enum(["MODEL","PROVIDER","INPUT","OUTPUT","UPDATED_AT"]).default("MODEL"),direction:e6.enum(["ASC","DESC"]).default("ASC")}),service:E,method:"listEntries",resultKey:"page"}),rm({name:"refresh_model_costs",title:"Refresh model costs",description:"Refresh the model-pricing catalog from its configured URL.",inputSchema:e6.object({}),service:E,method:"refresh",arguments:()=>[],resultKey:"catalog",annotations:ai}),rm({name:"estimate_model_cost",title:"Estimate model cost",description:"Estimate cost for token usage using the current model-pricing catalog.",inputSchema:e6.object({model:e6.string().min(1),inputTokens:e6.number().int().min(0).default(0),outputTokens:e6.number().int().min(0).default(0),cacheCreationInputTokens:e6.number().int().min(0).default(0),cacheReadInputTokens:e6.number().int().min(0).default(0)}),service:{estimate:async e=>{await E.ensureFresh();let t=await E.lookup([String(e.model)]);return E.estimate(t.get(String(e.model)),{inputTokens:Number(e.inputTokens),outputTokens:Number(e.outputTokens),cacheWriteTokens:Number(e.cacheCreationInputTokens),cacheReadTokens:Number(e.cacheReadInputTokens)})}},method:"estimate",resultKey:"estimate"})]})),e.systemStatus&&e.polling&&e.credentials&&j.push((S=e.systemStatus,I=e.polling,A=e.credentials,{id:"builtin:system",name:"System",children:[],tools:[rm({name:"get_system_status",title:"Get system status",description:"Get the control plane's aggregated operational health.",inputSchema:e6.object({}),service:S,method:"status",arguments:()=>[],resultKey:"status"}),rm({name:"get_polling_operations",title:"Get polling operations",description:"List registered background polling operations and their current states.",inputSchema:e6.object({}),service:I,method:"list",arguments:()=>[],resultKey:"operations"}),rm({name:"get_credential_store_status",title:"Get credential store status",description:"Get credential-store health without returning credential values.",inputSchema:e6.object({}),service:A,method:"status",arguments:()=>[],resultKey:"status"}),rm({name:"get_credential_metadata",title:"Get credential metadata",description:"List redacted credential metadata; values are never returned.",inputSchema:e6.object({}),service:A,method:"list",arguments:()=>[],resultKey:"credentials"})]})),e.cacheServer&&e.jira&&e.github&&j.push((x=e.cacheServer,_=e.jira,C=e.github,R=e.gitlab,{id:"builtin:cache-administration",name:"Cache Administration",tools:[],children:[{id:"builtin:cache-administration:cache-server",name:"Cache Server",children:[],tools:[rm({name:"get_cache_server_entries",title:"Get cache-server entries",description:"List cache-server entries with filters and pagination.",inputSchema:e6.object({filters:e6.object({key:e6.string().nullable().optional(),version:e6.string().nullable().optional(),scope:e6.string().nullable().optional(),repoId:e6.string().nullable().optional(),itemsPerPage:e6.number().int().min(1).max(500).default(20),page:e6.number().int().min(1).default(1)}).default({itemsPerPage:20,page:1})}),service:x,method:"listCacheEntries",arguments:({filters:e})=>[e],resultKey:"page",annotations:ar}),rm({name:"get_cache_server_entry",title:"Get cache-server entry",description:"Get cache-entry detail without secret connection values.",inputSchema:e6.object({id:e6.string().min(1)}),service:x,method:"getCacheEntryDetail",arguments:({id:e})=>[e],resultKey:"entry",annotations:ar}),rm({name:"match_cache_server_entry",title:"Match cache-server entry",description:"Find a cache entry matching build cache keys.",inputSchema:e6.object({input:e6.object({primaryKey:e6.string().min(1),restoreKeys:e6.array(e6.string()).nullable().optional(),scopes:e6.array(e6.string()).min(1),repoId:e6.string().min(1),version:e6.string().min(1)})}),service:x,method:"matchCacheEntry",arguments:({input:e})=>[e],resultKey:"match",annotations:ar}),rm({name:"get_cache_storage_location",title:"Get cache storage location",description:"Get one cache storage-location summary.",inputSchema:e6.object({id:e6.string().min(1)}),service:x,method:"getStorageLocation",arguments:({id:e})=>[e],resultKey:"location",annotations:ar}),rm({name:"delete_cache_server_entries",title:"Delete cache-server entries",description:"Permanently delete selected cache-server entries.",inputSchema:e6.object({ids:e6.array(e6.string().min(1)).min(1)}),service:x,method:"deleteCacheEntriesByIds",arguments:({ids:e})=>[e],resultKey:"deleted",annotations:aa})]},{id:"builtin:cache-administration:jira",name:"Jira Cache",children:[],tools:[rm({name:"get_jira_cache_metrics",title:"Get Jira cache metrics",description:"Get Jira cache hit, live-call, error, and latency metrics.",inputSchema:e6.object({}),service:_,method:"cacheMetrics",arguments:()=>[],resultKey:"metrics"}),rm({name:"get_jira_api_calls",title:"Get Jira API calls",description:"List redacted Jira API-call history.",inputSchema:e6.object({limit:e6.number().int().min(1).max(500).default(100),offset:e6.number().int().min(0).default(0)}),service:_,method:"listApiCalls",arguments:e=>[e.limit,e.offset],resultKey:"page"}),rm({name:"get_jira_cached_entries",title:"Get Jira cached entries",description:"List cached Jira ticket entries.",inputSchema:e6.object({limit:e6.number().int().min(1).max(500).default(100),offset:e6.number().int().min(0).default(0)}),service:_,method:"listCachedTickets",arguments:e=>[e.limit,e.offset],resultKey:"page"}),rm({name:"clear_jira_cache",title:"Clear Jira cache",description:"Permanently clear all cached Jira tickets.",inputSchema:e6.object({}),service:_,method:"clearCache",arguments:()=>[],resultKey:"cleared",annotations:aa})]},{id:"builtin:cache-administration:github",name:"GitHub Cache",children:[],tools:[rm({name:"get_github_cache_metrics",title:"Get GitHub cache metrics",description:"Get GitHub cache and API-call metrics.",inputSchema:e6.object({}),service:C,method:"cacheMetrics",arguments:()=>[],resultKey:"metrics"}),rm({name:"get_github_api_calls",title:"Get GitHub API calls",description:"List redacted GitHub API-call history.",inputSchema:e6.object({limit:e6.number().int().min(1).max(500).default(100),offset:e6.number().int().min(0).default(0)}),service:C,method:"apiCalls",arguments:e=>[e.limit,e.offset,{}],resultKey:"page"}),rm({name:"get_github_cached_entries",title:"Get GitHub cached entries",description:"List cached GitHub API entries.",inputSchema:e6.object({limit:e6.number().int().min(1).max(500).default(100),offset:e6.number().int().min(0).default(0)}),service:C,method:"cachedEntries",arguments:e=>[e.limit,e.offset],resultKey:"page"}),rm({name:"clear_github_cache",title:"Clear GitHub cache",description:"Permanently clear cached GitHub API entries.",inputSchema:e6.object({}),service:C,method:"clearCache",arguments:()=>[],resultKey:"cleared",annotations:at})]},...R?[{id:"builtin:cache-administration:gitlab",name:"GitLab Cache",children:[],tools:[rm({name:"get_gitlab_cache_metrics",title:"Get GitLab cache metrics",description:"Get GitLab cache and API-call metrics.",inputSchema:e6.object({}),service:R,method:"cacheMetrics",arguments:()=>[],resultKey:"metrics"}),rm({name:"get_gitlab_api_calls",title:"Get GitLab API calls",description:"List redacted GitLab API-call history.",inputSchema:e6.object({limit:e6.number().int().min(1).max(500).default(100),offset:e6.number().int().min(0).default(0)}),service:R,method:"apiCalls",arguments:({limit:e,offset:t})=>[e,t],resultKey:"page"}),rm({name:"get_gitlab_cached_entries",title:"Get GitLab cached entries",description:"List cached GitLab REST API entries.",inputSchema:e6.object({limit:e6.number().int().min(1).max(500).default(100),offset:e6.number().int().min(0).default(0)}),service:R,method:"cachedEntries",arguments:({limit:e,offset:t})=>[e,t],resultKey:"page"}),rm({name:"clear_gitlab_cache",title:"Clear GitLab cache",description:"Permanently clear cached GitLab REST entries.",inputSchema:e6.object({}),service:R,method:"clearCache",arguments:()=>[],resultKey:"cleared",annotations:at})]}]:[]]})),e.toolAudit&&e.testExternalMcpServer&&j.push((T=e.toolAudit,D=e.testExternalMcpServer,{id:"builtin:tool-administration",name:"Tool Administration",children:[],tools:[rm({name:"test_external_mcp_server",title:"Test external MCP server",description:"Connect to a configured external MCP server and report its tool count without returning saved headers.",inputSchema:e6.object({id:e6.string().min(1)}),service:{testExternalServer:D},method:"testExternalServer",arguments:({id:e})=>[e],resultKey:"status",annotations:ar}),rm({name:"get_tool_call_history",title:"Get tool call history",description:"List redacted tool-call audit records. Arguments are represented only by SHA-256 hashes.",inputSchema:e6.object({first:e6.number().int().min(1).max(500).default(100),toolName:e6.string().nullable().optional(),resultStatus:e6.enum(["RUNNING","SUCCEEDED","FAILED"]).nullable().optional()}),service:T,method:"list",resultKey:"calls"}),rm({name:"get_tool_call",title:"Get tool call",description:"Get one redacted tool-call audit record by ID.",inputSchema:e6.object({id:e6.string().min(1)}),service:T,method:"get",arguments:({id:e})=>[e],resultKey:"call"})]})),e.workflows&&j.push((N=e.workflows,U={id:"builtin:workflows:discovery",name:"Discovery",children:[],tools:[an({name:"list_workflow_step_kinds",title:"List workflow step kinds",description:"Browse the step kinds a workflow can be built from, with a short description of each. Start here when authoring; use describe_workflow_kind for the config schema of one kind.",inputSchema:e6.object({category:e6.string().optional().describe("Restrict to one category, e.g. 'Jira' or 'Control flow'."),search:e6.string().optional().describe("Match against kind, label, category, and description.")}),outputSchema:e6.object({steps:e6.array(e6.object({kind:e6.string(),category:e6.string(),label:e6.string(),description:e6.string(),execution:e6.string(),requiredPaths:e6.array(e6.string()),providedPaths:e6.array(e6.string()),sourceHandles:e6.array(e6.string()),mutatesExternal:e6.boolean(),mutatesWorktree:e6.boolean()}))}),annotations:i7,handler:({category:e,search:t})=>({steps:iC.WORKFLOW_STEP_CATALOG.filter(r=>(!e||r.category===e)&&iY(`${r.kind} ${r.label} ${r.category} ${r.description}`,t)).map(e=>({kind:e.kind,category:e.category,label:e.label,description:e.description,execution:e.execution,requiredPaths:e.requiredPaths,providedPaths:e.providedPaths,sourceHandles:e.sourceHandles,mutatesExternal:e.mutatesExternal,mutatesWorktree:e.mutatesWorktree}))})}),an({name:"list_workflow_trigger_kinds",title:"List workflow trigger kinds",description:"Browse the trigger kinds that can start a workflow, with what each one seeds into session data. Every workflow needs at least one trigger.",inputSchema:e6.object({category:e6.string().optional(),search:e6.string().optional()}),outputSchema:e6.object({triggers:e6.array(e6.object({kind:e6.string(),category:e6.string(),label:e6.string(),description:e6.string(),seedPaths:e6.array(e6.string()),sourceHandles:e6.array(e6.string())}))}),annotations:i7,handler:({category:e,search:t})=>({triggers:iC.WORKFLOW_TRIGGER_CATALOG.filter(r=>(!e||r.category===e)&&iY(`${r.kind} ${r.label} ${r.category} ${r.description}`,t)).map(e=>({kind:e.kind,category:e.category,label:e.label,description:e.description,seedPaths:e.seedPaths,sourceHandles:e.sourceHandles}))})}),an({name:"describe_workflow_kind",title:"Describe a workflow step or trigger kind",description:"Full detail for one kind: long-form notes on preconditions and side effects, the JSON Schema for its config, the session paths it requires and provides, and the handles edges may leave it from.",inputSchema:e6.object({kind:e6.string().min(1).describe("A step or trigger kind.")}),outputSchema:e6.object({scope:e6.enum(["step","trigger"]),kind:e6.string(),category:e6.string(),label:e6.string(),description:e6.string(),details:e6.string(),execution:e6.string().nullable(),configSchema:e6.unknown(),requiredPaths:e6.array(e6.string()),providedPaths:e6.array(e6.string()),seedPaths:e6.array(e6.string()),sourceHandles:e6.array(e6.string()),mutatesExternal:e6.boolean(),mutatesWorktree:e6.boolean()}),annotations:i7,handler:({kind:e})=>{let t=iC.WORKFLOW_STEP_CATALOG.find(t=>t.kind===e);if(t)return{scope:"step",...t,configSchema:re(t.configSchema),seedPaths:[]};let r=iX(e);return{scope:"trigger",...r,configSchema:re(r.configSchema),execution:null,requiredPaths:[],providedPaths:[],mutatesExternal:!1,mutatesWorktree:!1}}}),an({name:"list_workflow_session_paths",title:"List workflow session-data paths",description:"The session-data vocabulary a step's config can bind to — concrete paths like `ticket.key` or `pr.number`, with what each holds. Use it to write bindings that resolve at run time.",inputSchema:e6.object({namespace:e6.string().optional().describe("Restrict to one namespace, e.g. 'ticket' or 'pr'.")}),outputSchema:e6.object({paths:e6.array(e6.object({path:e6.string(),description:e6.string().nullable()}))}),annotations:i7,handler:({namespace:e})=>({paths:(function(e){let t=new Map,r=e=>{t.has(e.path)||t.set(e.path,e)};for(let t of e){let e=t.trim();if(e&&"*"!==e){if(e.endsWith(".*")){let t=e.slice(0,-2),i=iL[iU(t)];if(i)for(let e of i)r({path:`${t}.${e.name}`,description:e.description});else r({path:e});continue}r({path:e,description:function(e){let t=e.split(".");if(t.length<2)return;let r=t[t.length-1];return iB.get(`${iU(e)}.${r}`)}(e)})}}return[...t.values()].sort((e,t)=>e.path.localeCompare(t.path))})(e?[`${e}.*`]:[...new Set(iC.WORKFLOW_TRIGGER_CATALOG.flatMap(({seedPaths:e})=>e))]).map(({path:e,description:t})=>({path:e,description:t??null}))})}),an({name:"get_workflow_path_availability",title:"Get workflow path availability",description:"Per step, the session paths guaranteed to exist before it runs and the ones it contributes. This is what decides whether a config binding is legal — check it before binding a step to a path.",inputSchema:ij,outputSchema:e6.object({steps:e6.array(e6.object({nodeId:e6.string(),kind:e6.string(),availableBefore:e6.array(e6.string()),provides:e6.array(e6.string())})),triggerSeeds:e6.array(e6.object({triggerId:e6.string(),kind:e6.string(),seedPaths:e6.array(e6.string())})),violations:e6.array(e6.object({nodeId:e6.string(),triggerId:e6.string(),triggerName:e6.string(),path:e6.string()}))}),annotations:i7,handler:async({workflowId:e})=>{let t=await iZ(N,e),r=(0,iC.computeWorkflowPathAvailability)(t);return{steps:t.nodes.map(e=>({nodeId:e.id,kind:e.kind,availableBefore:r.availableBefore.get(e.id)??[],provides:r.provides.get(e.id)??[]})),triggerSeeds:t.triggers.map(e=>({triggerId:e.id,kind:e.kind,seedPaths:["workflow.*",...iX(e.kind).seedPaths,...(0,iC.resourceManualSeedPaths)(e.kind,e.config)]})),violations:r.requirementViolations}}})]},{id:"builtin:workflows",name:"Workflows",tools:[],children:[U,{id:"builtin:workflows:authoring",name:"Authoring",children:[],tools:[an({name:"list_workflows",title:"List workflows",description:"List workflows with their publish and enablement state.",inputSchema:e6.object({search:e6.string().optional().describe("Match name or description."),archive:e6.enum(["ACTIVE","ARCHIVED","ALL"]).optional().describe("Defaults to ACTIVE."),enabled:e6.boolean().optional(),first:e6.number().int().min(1).max(200).optional(),after:e6.string().optional().describe("Cursor from a previous page.")}),outputSchema:e6.object({workflows:e6.array(iH),nextCursor:e6.string().nullable(),totalCount:e6.number()}),annotations:i7,handler:async e=>{let t=await N().list(e);return{workflows:t.items.map(e=>rt(e)),nextCursor:t.nextCursor,totalCount:t.totalCount}}}),an({name:"get_workflow",title:"Get workflow",description:"Read one workflow, optionally with its full draft definition — every trigger, step, and connection.",inputSchema:e6.object({workflowId:e6.string().min(1),includeDefinition:e6.boolean().optional().describe("Include the draft graph. Defaults to true.")}),outputSchema:e6.object({workflow:iH,definition:e6.unknown().nullable(),activeVersion:e6.unknown().nullable()}),annotations:i7,handler:async({workflowId:e,includeDefinition:t})=>{let r=await N().get(e);if(!r)throw Error(`Workflow ${e} was not found`);return{workflow:rt(r),definition:!1===t?null:JSON.parse(r.draftDefinitionJson),activeVersion:r.activeVersion?rr(r.activeVersion):null}}}),an({name:"create_workflow",title:"Create workflow",description:"Create a workflow. Without a definition it starts as a draft holding one manual trigger and no steps, ready for add_workflow_step.",inputSchema:e6.object({name:e6.string().min(1).max(200),description:e6.string().max(2e3).optional(),definition:e6.unknown().optional().describe("A complete definition, e.g. from export_workflow."),overlapPolicy:e6.enum(["QUEUE","CONCURRENT","COALESCE_LATEST"]).optional().describe("What happens when a run starts while one is in flight. Defaults to QUEUE."),overlapScope:e6.enum(["WORKTREE","GLOBAL"]).optional().describe("Which runs the overlap policy counts: WORKTREE keeps a queue per worktree so worktrees never wait on each other, GLOBAL counts every run of the workflow. Defaults to WORKTREE."),maxConcurrentRuns:e6.number().int().min(1).optional(),completionNotificationsEnabled:e6.boolean().optional().describe("Whether successful runs create completion notifications. Defaults to true."),exclusiveWorktree:e6.boolean().optional().describe("Reserve a run's worktree and queue other workflows, plans, and sessions until it finishes. Defaults to false."),worktreeConcurrency:e6.enum(["EXCLUSIVE","NON_EXCLUSIVE","EXCLUDED"]).optional().describe("How runs participate in worktree admission. Defaults to NON_EXCLUSIVE."),blocksGitOperations:e6.boolean().optional().describe("Whether command and terminal steps block concurrent Git operations. Exclusive workflows always enable this.")}),outputSchema:e6.object({workflow:iH,definition:e6.unknown()}),annotations:ae,handler:async e=>{let t=await N().create(e);if(!t)throw Error("Workflow could not be created");return{workflow:rt(t),definition:JSON.parse(t.draftDefinitionJson)}}}),an({name:"update_workflow_settings",title:"Update workflow settings",description:"Change a workflow's name, description, concurrency, worktree exclusivity, or successful-run completion notifications. Name and description live inside the definition, so this rewrites the draft.",inputSchema:e6.object({workflowId:e6.string().min(1),name:e6.string().min(1).max(200).optional(),description:e6.string().max(2e3).optional(),overlapPolicy:e6.enum(["QUEUE","CONCURRENT","COALESCE_LATEST"]).optional(),overlapScope:e6.enum(["WORKTREE","GLOBAL"]).optional().describe("Which runs the overlap policy counts: WORKTREE keeps a queue per worktree, GLOBAL counts every run of the workflow."),maxConcurrentRuns:e6.number().int().min(1).optional(),completionNotificationsEnabled:e6.boolean().optional().describe("Set false to suppress successful-run completion notifications for this workflow. Failure and attention notifications remain enabled."),exclusiveWorktree:e6.boolean().optional().describe("Reserve the worktree for each top-level run of this workflow."),worktreeConcurrency:e6.enum(["EXCLUSIVE","NON_EXCLUSIVE","EXCLUDED"]).optional(),blocksGitOperations:e6.boolean().optional()}),outputSchema:iK,annotations:ae,handler:async e=>{let t=await iZ(N,e.workflowId),r={...t,name:e.name??t.name,description:e.description??t.description};return await N().saveDraft({id:e.workflowId,definition:r,overlapPolicy:e.overlapPolicy??null,overlapScope:e.overlapScope??null,maxConcurrentRuns:e.maxConcurrentRuns??null,completionNotificationsEnabled:e.completionNotificationsEnabled??null,exclusiveWorktree:e.exclusiveWorktree??null,worktreeConcurrency:e.worktreeConcurrency??null,blocksGitOperations:e.blocksGitOperations??null}),iQ(N,e.workflowId,r)}}),an({name:"set_workflow_enabled",title:"Enable or pause workflow",description:"Enable a workflow or pause it. A paused workflow ignores its triggers and refuses manual runs.",inputSchema:e6.object({workflowId:e6.string().min(1),enabled:e6.boolean()}),outputSchema:e6.object({workflow:iH}),annotations:ae,handler:async({workflowId:e,enabled:t})=>({workflow:rt(await N().setEnabled(e,t))})}),an({name:"archive_workflow",title:"Archive or restore workflow",description:"Move a workflow out of the active list, or bring it back. Reversible — use delete_workflow to remove it for good.",inputSchema:e6.object({workflowId:e6.string().min(1),archived:e6.boolean()}),outputSchema:e6.object({workflow:iH}),annotations:ae,handler:async({workflowId:e,archived:t})=>({workflow:rt(await N().archive(e,t))})}),an({name:"delete_workflow",title:"Delete workflow",description:"Permanently delete a workflow and its published versions. Refused once the workflow has run history — archive_workflow is the way to retire one that has run. Not reversible.",inputSchema:e6.object({workflowId:e6.string().min(1)}),outputSchema:e6.object({deleted:e6.boolean()}),annotations:at,handler:async({workflowId:e})=>({deleted:await N().delete(e)})}),an({name:"add_workflow_step",title:"Add workflow step",description:"Add a step to the draft and optionally wire it to an existing trigger or step. Returns the new step's id and the validator's view of the result.",inputSchema:e6.object({workflowId:e6.string().min(1),kind:e6.enum(iR.WORKFLOW_STEP_KINDS).describe("Step kind. See list_workflow_step_kinds."),name:e6.string().max(200).optional().describe("Display name. Defaults to the kind's label."),config:iq.optional(),connectFrom:e6.object({from:e6.string().min(1).describe("Trigger or step id this one follows."),sourceHandle:e6.string().optional().describe("Handle to leave from — 'success' by default, 'true'/'false' on an If, 'body'/'empty' on a For each, an option key on a choice trigger.")}).optional(),position:iM.optional(),failurePolicy:e6.enum(["FAIL","CONTINUE"]).optional().describe("CONTINUE lets the run carry on past a failure."),retry:e6.object({maxAttempts:e6.number().int().min(1).max(20),strategy:e6.enum(["FIXED","EXPONENTIAL"]),delaySeconds:e6.number().int().min(1).max(86400)}).optional(),providedPaths:i$.optional(),requiredPaths:iF.optional()}),outputSchema:iK,annotations:ae,handler:async e=>{let t=function(e,t){let r=iT(e,"node"),i={id:r,kind:t.kind,name:t.name??void 0,position:t.position??function(e,t){let r=t?iD(e,t):void 0,i=r?r.position.x+320:320,a=r?r.position.y:120,n=[...e.nodes,...e.triggers].filter(e=>160>Math.abs(e.position.x-i)).map(e=>e.position.y),s=a;for(;n.some(e=>80>Math.abs(e-s));)s+=160;return{x:i,y:s}}(e,t.connectFrom?.from??null),config:t.config??{},requiredPaths:t.requiredPaths??[],providedPaths:t.providedPaths??[],retry:t.retry??{maxAttempts:1,strategy:"EXPONENTIAL",delaySeconds:5},failurePolicy:t.failurePolicy??"FAIL"},a={...e,nodes:[...e.nodes,i]};if(!t.connectFrom)return{definition:a,nodeId:r,edgeId:null};let n=iP(a,{source:t.connectFrom.from,target:r,sourceHandle:t.connectFrom.sourceHandle??null});return{definition:n.definition,nodeId:r,edgeId:n.edgeId}}(await iZ(N,e.workflowId),{...e,name:e.name??function(e){let t=iC.WORKFLOW_STEP_CATALOG.find(t=>t.kind===e);if(!t)throw Error(`Unknown step kind ${e}`);return t}(e.kind).label});return iQ(N,e.workflowId,t.definition,{nodeId:t.nodeId,edgeId:t.edgeId})}}),an({name:"update_workflow_step",title:"Update workflow step",description:"Change a step's name, config, retry, or failure policy. Prefer configPatch, which merges — config replaces the object wholesale.",inputSchema:e6.object({workflowId:e6.string().min(1),nodeId:e6.string().min(1),name:e6.string().max(200).optional(),config:iq.optional().describe("Replaces the entire config. Keys left out are dropped."),configPatch:e6.record(e6.string(),e6.unknown()).optional().describe("Merges into the existing config. A null value removes that key."),position:iM.optional(),failurePolicy:e6.enum(["FAIL","CONTINUE"]).optional(),retry:e6.object({maxAttempts:e6.number().int().min(1).max(20),strategy:e6.enum(["FIXED","EXPONENTIAL"]),delaySeconds:e6.number().int().min(1).max(86400)}).optional(),providedPaths:i$.optional(),requiredPaths:iF.optional()}),outputSchema:iK,annotations:ae,handler:async e=>{let t=await iZ(N,e.workflowId);return iQ(N,e.workflowId,function(e,t){if(!e.nodes.some(({id:e})=>e===t.nodeId))throw Error(`Step ${t.nodeId} is not in this workflow`);if(t.config&&t.configPatch)throw Error("Pass either config or configPatch, not both");return{...e,nodes:e.nodes.map(e=>e.id===t.nodeId?{...e,name:t.name??e.name,config:iO(e.config,t),position:t.position??e.position,retry:t.retry??e.retry,failurePolicy:t.failurePolicy??e.failurePolicy,requiredPaths:t.requiredPaths??e.requiredPaths,providedPaths:t.providedPaths??e.providedPaths}:e)}}(t,e),{nodeId:e.nodeId})}}),an({name:"add_workflow_trigger",title:"Add workflow trigger",description:"Add a trigger to the draft. A workflow needs at least one, and each must reach a step before it can be published.",inputSchema:e6.object({workflowId:e6.string().min(1),kind:e6.enum(iR.WORKFLOW_TRIGGER_KINDS).describe("Trigger kind. See list_workflow_trigger_kinds."),name:e6.string().max(200).optional(),config:iq.optional().describe("Trigger config. Resource triggers need `resourceKind`; choice triggers need keyed `choices`; issue-command triggers need `allowedLogins` and an anchored `commandPattern`."),position:iM.optional()}),outputSchema:iK,annotations:ae,handler:async e=>{var t,r;let i,a,n=(t=await iZ(N,e.workflowId),r={...e,name:e.name??iX(e.kind).label},a={id:i=iT(t,"trigger"),kind:r.kind,name:r.name??void 0,config:r.config??{},position:r.position??{x:0,y:100+140*t.triggers.length}},{definition:{...t,triggers:[...t.triggers,a]},triggerId:i});return iQ(N,e.workflowId,n.definition,{triggerId:n.triggerId})}}),an({name:"update_workflow_trigger",title:"Update workflow trigger",description:"Change a trigger's name or config. Narrowing a choice trigger's options also removes the connections that left the options you dropped.",inputSchema:e6.object({workflowId:e6.string().min(1),triggerId:e6.string().min(1),name:e6.string().max(200).optional(),config:iq.optional(),configPatch:e6.record(e6.string(),e6.unknown()).optional(),position:iM.optional()}),outputSchema:iK,annotations:ae,handler:async e=>{let t=await iZ(N,e.workflowId);return iQ(N,e.workflowId,function(e,t){let r=e.triggers.find(({id:e})=>e===t.triggerId);if(!r)throw Error(`Trigger ${t.triggerId} is not in this workflow`);if(t.config&&t.configPatch)throw Error("Pass either config or configPatch, not both");let i={...r,name:t.name??r.name,config:iO(r.config,t),position:t.position??r.position},a=new Set(iN(i)),n=(0,iR.isChoiceTriggerKind)(i.kind)?e.edges.filter(e=>e.source!==i.id||a.has(e.sourceHandle)):e.edges;return{...e,triggers:e.triggers.map(e=>e.id===i.id?i:e),edges:n}}(t,e),{triggerId:e.triggerId})}}),an({name:"remove_workflow_node",title:"Remove workflow step or trigger",description:"Delete a step or trigger from the draft along with its connections. Set reconnect to stitch its predecessors to its successors so the chain survives.",inputSchema:e6.object({workflowId:e6.string().min(1),id:e6.string().min(1).describe("Step or trigger id."),reconnect:e6.boolean().optional().describe("Join what came before to what came after.")}),outputSchema:iK,annotations:at,handler:async({workflowId:e,id:t,reconnect:r})=>{let i=await iZ(N,e);return iQ(N,e,function(e,t,r={}){if(!iD(e,t))throw Error(`${t} is not in this workflow`);let i=e.edges.filter(e=>e.target===t),a=e.edges.filter(e=>e.source===t),n=e.edges.filter(e=>e.source!==t&&e.target!==t),s={...e,nodes:e.nodes.filter(e=>e.id!==t),triggers:e.triggers.filter(e=>e.id!==t),edges:n};if(!r.reconnect)return s;for(let e of i)for(let t of a)s=iP(s,{source:e.source,sourceHandle:e.sourceHandle,target:t.target,targetHandle:t.targetHandle}).definition;return s}(i,t,{reconnect:r}))}}),an({name:"connect_workflow_nodes",title:"Connect workflow nodes",description:"Draw a connection from a trigger or step to a step. A step with more than one incoming connection must be a CONTROL_JOIN.",inputSchema:e6.object({workflowId:e6.string().min(1),source:e6.string().min(1).describe("Trigger or step id."),target:e6.string().min(1).describe("Step id. Triggers take no input."),sourceHandle:e6.string().optional().describe("Handle to leave from. Defaults to the source's first — 'success' for a step.")}),outputSchema:iK,annotations:ae,handler:async e=>{let t=iP(await iZ(N,e.workflowId),e);return iQ(N,e.workflowId,t.definition,{edgeId:t.edgeId})}}),an({name:"disconnect_workflow_nodes",title:"Disconnect workflow nodes",description:"Remove a connection, either by its edge id or by the pair of nodes it joins.",inputSchema:e6.object({workflowId:e6.string().min(1),edgeId:e6.string().optional(),source:e6.string().optional(),target:e6.string().optional(),sourceHandle:e6.string().optional()}),outputSchema:iK.extend({removedEdgeIds:e6.array(e6.string())}),annotations:ae,handler:async e=>{let t=function(e,t){let r=e.edges.filter(e=>t.edgeId?e.id===t.edgeId:(!!t.source||!!t.target)&&(!t.source||e.source===t.source)&&(!t.target||e.target===t.target)&&(!t.sourceHandle||e.sourceHandle===t.sourceHandle));if(!r.length)throw Error("No matching connection to remove");let i=new Set(r.map(({id:e})=>e));return{definition:{...e,edges:e.edges.filter(e=>!i.has(e.id))},removedEdgeIds:[...i]}}(await iZ(N,e.workflowId),e);return{...await iQ(N,e.workflowId,t.definition),removedEdgeIds:t.removedEdgeIds}}}),an({name:"layout_workflow",title:"Lay out workflow graph",description:"Reposition every trigger and step into readable left-to-right columns. Worth calling once after building a workflow, so it does not open as a pile of overlapping cards.",inputSchema:ij,outputSchema:iK,annotations:ae,handler:async({workflowId:e})=>{let t=await iZ(N,e);return iQ(N,e,function(e){let t=new Map;for(let r of e.edges)t.set(r.source,[...t.get(r.source)??[],r.target]);let r=new Map;for(let t of e.triggers)r.set(t.id,0);let i=e.triggers.map(({id:e})=>e),a=e.nodes.length*e.edges.length+1;for(;i.length&&a-- >0;){let e=i.shift(),a=r.get(e)??0;for(let n of t.get(e)??[])(r.get(n)??-1)>=a+1||(r.set(n,a+1),i.push(n))}let n=Math.max(0,...r.values());for(let t of e.nodes)r.has(t.id)||r.set(t.id,n+1);let s=new Map,o=e=>{let t=r.get(e.id)??0,i=s.get(t)??0;return s.set(t,i+1),{...e,position:{x:320*t,y:160*i}}},l=e.triggers.map(o),c=e.nodes.map(o);return{...e,triggers:l,nodes:c}}(t))}}),an({name:"set_workflow_definition",title:"Replace workflow definition",description:"Overwrite the entire draft graph. The bulk escape hatch — prefer the granular tools for single edits, which cannot clobber work they did not read.",inputSchema:e6.object({workflowId:e6.string().min(1),definition:e6.unknown().describe("A complete definition object, as returned by get_workflow.")}),outputSchema:iK,annotations:ae,handler:async({workflowId:e,definition:t})=>iQ(N,e,(0,iC.parseWorkflowDefinition)(t))}),an({name:"validate_workflow",title:"Validate workflow draft",description:"Check the draft without saving anything. Errors block publishing; the codes name the problem — REQUIREMENT_UNSATISFIED means a step binds a path its trigger cannot seed.",inputSchema:ij,outputSchema:e6.object({valid:e6.boolean(),diagnostics:e6.array(iG)}),annotations:i7,handler:async({workflowId:e})=>{let t=await N().validateDraft(e);return{valid:t.valid,diagnostics:t.diagnostics.map(e=>({severity:e.severity,code:e.code,message:e.message,nodeId:e.nodeId??null,triggerId:e.triggerId??null,path:e.path??null}))}}}),an({name:"publish_workflow",title:"Publish workflow",description:"Publish the draft as a new immutable version. Only a published version can run, and publishing fails if the draft has errors.",inputSchema:ij,outputSchema:e6.object({version:e6.unknown()}),annotations:ae,handler:async({workflowId:e})=>({version:rr(await N().publish(e))})}),an({name:"export_workflow",title:"Export workflow",description:"Export a workflow as a portable document, with secrets and machine-specific paths stripped. Pass a version id to export a published version instead of the draft.",inputSchema:e6.object({workflowId:e6.string().min(1),versionId:e6.string().optional()}),outputSchema:e6.object({export:e6.unknown()}),annotations:i7,handler:async({workflowId:e,versionId:t})=>({export:re(await N().export(e,t))})}),an({name:"import_workflow",title:"Import workflow",description:"Create a workflow from an exported document. References that cannot be resolved on this machine come in marked unresolved and must be fixed before publishing.",inputSchema:e6.object({payload:e6.unknown().describe("A document from export_workflow."),name:e6.string().max(200).optional()}),outputSchema:e6.object({workflow:iH,definition:e6.unknown()}),annotations:ae,handler:async e=>{let t=await N().import(e);if(!t)throw Error("Workflow could not be imported");return{workflow:rt(t),definition:JSON.parse(t.draftDefinitionJson)}}})]},{id:"builtin:workflows:runs",name:"Runs",children:[],tools:[an({name:"trigger_workflow",title:"Trigger workflow run",description:"Start a run of a published, enabled workflow. Runs whatever the workflow's steps do, including external side effects.",inputSchema:e6.object({workflowId:e6.string().min(1),sessionData:e6.record(e6.string(),e6.unknown()).optional().describe("Initial session data, merged with the trigger's seeds."),resourceKind:e6.enum(iR.WORKFLOW_RESOURCE_KINDS).optional().describe("Launch through a resource trigger of this kind."),resourceId:e6.string().optional().describe("The resource to launch against."),choice:e6.string().optional().describe("Option key when the workflow's trigger offers choices. Omitting it on a choice-only workflow returns the valid keys."),subjectKey:e6.string().optional().describe("Dedupe key. Defaults to the resource or a fresh id.")}),outputSchema:e6.object({run:iV}),annotations:iz,handler:async e=>{let t=await N().trigger(e);if(!t)throw Error("Workflow run could not be started");return{run:ri(t)}}}),an({name:"list_workflow_runs",title:"List workflow runs",description:"List runs, newest first, optionally filtered.",inputSchema:e6.object({workflowId:e6.string().optional(),status:e6.enum(["QUEUED","RUNNING","PAUSING","PAUSED","WAITING","BLOCKED","SUCCEEDED","FAILED","CANCELLED"]).optional(),search:e6.string().optional().describe("A run number, or part of a workflow name."),first:e6.number().int().min(1).max(200).optional(),after:e6.string().optional()}),outputSchema:e6.object({runs:e6.array(iV),nextCursor:e6.string().nullable(),totalCount:e6.number()}),annotations:i7,handler:async e=>{let t=await N().runs(e);return{runs:t.items.map(e=>ri(e)),nextCursor:t.nextCursor,totalCount:t.totalCount}}}),an({name:"get_workflow_run",title:"Get workflow run",description:"Read a run's status and session data, with its per-step attempts and any questions it is blocked on. Poll this after trigger_workflow.",inputSchema:e6.object({runId:e6.string().min(1),includeAttempts:e6.boolean().optional().describe("Include per-step attempts. Defaults to true.")}),outputSchema:e6.object({run:iV,attempts:e6.array(e6.unknown()),pendingQuestions:e6.array(iJ)}),annotations:i7,handler:async({runId:e,includeAttempts:t})=>{let r=await N().run(e);if(!r)throw Error(`Workflow run ${e} was not found`);let i=r.attempts??[];return{run:ri(r),attempts:!1===t?[]:i.map(e=>({id:String(e.id),nodeId:String(e.nodeId),kind:String(e.kind),generation:Number(e.generation),iterationKey:String(e.iterationKey??""),attempt:Number(e.attempt),status:String(e.status),phase:String(e.phase),input:t6(e.inputJson),output:t6(e.outputJson),error:"string"==typeof e.error?e.error:null,startedAt:t8(e.startedAt),finishedAt:t8(e.finishedAt)})),pendingQuestions:i.flatMap(e=>e.questionBatches??[]).filter(e=>"PENDING"===e.status).map(e=>{let t;return t=Array.isArray(e.questions)?e.questions:[],{batchId:String(e.id),runId:"string"==typeof e.runId?e.runId:null,status:String(e.status),createdAt:t8(e.createdAt),questions:t.map(e=>{let t=Array.isArray(e.options)?e.options:[];return{id:String(e.id),header:"string"==typeof e.header?e.header:null,prompt:String(e.prompt??""),multiSelect:!0===e.multiSelect,allowCustom:!0===e.allowCustom,options:t.map(e=>({label:String(e.label??""),description:"string"==typeof e.description?e.description:null}))}})}})}}}),an({name:"get_workflow_run_events",title:"Get workflow run events",description:"Read a run's event log in order. Pass the last sequence you saw to tail only what is new.",inputSchema:e6.object({runId:e6.string().min(1),afterSequence:e6.number().int().optional(),first:e6.number().int().min(1).max(500).optional()}),outputSchema:e6.object({events:e6.array(iW)}),annotations:i7,handler:async({runId:e,afterSequence:t,first:r})=>({events:(await N().runEvents(e,t,r)).map(e=>({id:String(e.id),runId:String(e.runId),attemptId:"string"==typeof e.attemptId?e.attemptId:null,sequence:Number(e.sequence),type:String(e.type),message:String(e.message??""),detail:t6(e.detailJson),createdAt:t8(e.createdAt)}))})}),an({name:"control_workflow_run",title:"Pause, resume, or cancel a run",description:"Change an in-flight run's lifecycle. Cancelling is final, and leaves any external effects already applied in place.",inputSchema:e6.object({runId:e6.string().min(1),action:e6.enum(["PAUSE","RESUME","CANCEL"])}),outputSchema:e6.object({run:iV}),annotations:at,handler:async({runId:e,action:t})=>{let r=await N().lifecycle(e,t);if(!r)throw Error("Workflow run lifecycle change failed");return{run:ri(r)}}}),an({name:"answer_workflow_question",title:"Answer a workflow question",description:"Answer the question a run is parked on so it can continue. Find the batch id and the questions through get_workflow_run.",inputSchema:e6.object({batchId:e6.string().min(1).describe("From get_workflow_run."),answers:e6.record(e6.string(),e6.unknown()).describe("Answers keyed by question id. A value is the chosen option label, a list of labels for a multi-select, or free text where a custom answer is allowed.")}),outputSchema:e6.object({run:iV}),annotations:ae,handler:async({batchId:e,answers:t})=>{let r=await N().answerQuestion(e,t);if(!r)throw Error("Workflow question could not be answered");return{run:ri(r)}}}),an({name:"prepare_workflow_replay",title:"Preview a workflow replay",description:"See what replaying a run from a given step would affect: the downstream steps, the external effects that would happen again, and whether a Git checkpoint is available. Read-only — call it before replay_workflow_run.",inputSchema:e6.object({runId:e6.string().min(1),nodeId:e6.string().min(1).describe("Step to replay from.")}),outputSchema:e6.object({preview:e6.unknown()}),annotations:i7,handler:async({runId:e,nodeId:t})=>({preview:re(await N().prepareReplay(e,t))})}),an({name:"replay_workflow_run",title:"Replay a workflow run from a step",description:"Re-run a workflow from one step onward. Every external effect downstream happens again — merges, comments, deploys — so preview it with prepare_workflow_replay first.",inputSchema:e6.object({runId:e6.string().min(1),nodeId:e6.string().min(1),restore:e6.boolean().optional().describe("Restore the worktree to the Git checkpoint at that step, discarding later changes."),stash:e6.boolean().optional().describe("Stash uncommitted changes before restoring.")}),outputSchema:e6.object({run:iV}),annotations:at,handler:async({runId:e,nodeId:t,restore:r,stash:i})=>{let a=await N().replay(e,t,{restore:r,stash:i});if(!a)throw Error("Workflow run could not be replayed");return{run:ri(a)}}}),an({name:"archive_workflow_runs",title:"Archive workflow runs",description:"Archive or restore workflow runs.",inputSchema:e6.object({ids:e6.array(e6.string().min(1)).min(1),archived:e6.boolean().default(!0)}),outputSchema:e6.object({count:e6.unknown()}),annotations:ae,handler:async({ids:e,archived:t})=>({count:await N().archiveRuns(e,t)})}),an({name:"delete_workflow_runs",title:"Delete workflow runs",description:"Permanently delete workflow runs and their retained execution history.",inputSchema:e6.object({ids:e6.array(e6.string().min(1)).min(1)}),outputSchema:e6.object({count:e6.unknown()}),annotations:at,handler:async({ids:e})=>({count:await N().deleteRuns(e)})}),an({name:"repair_workflow_run_data",title:"Repair workflow run data",description:"Repair session data for a blocked or paused workflow run.",inputSchema:e6.object({runId:e6.string().min(1),patch:e6.unknown()}),outputSchema:e6.object({run:e6.unknown()}),annotations:at,handler:async({runId:e,patch:t})=>({run:await N().repairRunData(e,t)})})]}]})),e.worktreeAutomations&&j.push((O=e.worktreeAutomations,{id:"builtin:worktree-automations",name:"Worktree Automations",children:[],tools:[an({name:"get_worktree_automations",title:"Get worktree automations",description:"Inspect the persisted Auto Sync and Auto Merge configuration and state for a worktree.",inputSchema:e6.object({worktreeId:e6.string().min(1)}),outputSchema:e6.object({autoSync:i5.nullable(),autoMerge:i9.nullable()}),annotations:i7,handler:async({worktreeId:e})=>({autoSync:await O().autoSync(e),autoMerge:await O().autoMerge(e)})}),an({name:"configure_worktree_auto_sync",title:"Configure worktree Auto Sync",description:"Enable or update Auto Sync. Optionally select a merge-conflict quick-action workflow and one of its trigger choices.",inputSchema:e6.object({worktreeId:e6.string().min(1),conflictWorkflowId:e6.string().min(1).nullable().optional(),conflictWorkflowChoice:e6.string().min(1).nullable().optional()}),outputSchema:e6.object({autoSync:i5}),annotations:ae,handler:async e=>({autoSync:await O().configureAutoSync(e)})}),an({name:"retry_worktree_auto_sync",title:"Retry worktree Auto Sync",description:"Resume a paused Auto Sync rule.",inputSchema:e6.object({worktreeId:e6.string().min(1)}),outputSchema:e6.object({autoSync:i5}),annotations:ae,handler:async({worktreeId:e})=>({autoSync:await O().retryAutoSync(e)})}),an({name:"force_worktree_auto_sync",title:"Force worktree Auto Sync",description:"Force an Auto Sync paused specifically by a preparation conflict. Managed paths are reset, the sync runs, and current preparations are reapplied.",inputSchema:e6.object({worktreeId:e6.string().min(1),requestId:e6.string().min(1)}),outputSchema:e6.object({job:e6.unknown()}),annotations:at,handler:async({worktreeId:e,requestId:t})=>({job:await O().forceAutoSync(e,t)})}),an({name:"cancel_worktree_auto_sync",title:"Cancel worktree Auto Sync",description:"Cancel any active job and remove the Auto Sync rule.",inputSchema:e6.object({worktreeId:e6.string().min(1)}),outputSchema:e6.object({cancelled:e6.boolean()}),annotations:at,handler:async({worktreeId:e})=>({cancelled:await O().cancelAutoSync(e)})}),an({name:"configure_worktree_auto_merge",title:"Configure worktree Auto Merge",description:"Enable or update GitHub-native Auto Merge and its optional Jira/worktree post-merge actions.",inputSchema:e6.object({worktreeId:e6.string().min(1),repositoryNameWithOwner:e6.string().min(3),pullRequestNumber:e6.number().int().positive(),method:e6.enum(["MERGE","REBASE","SQUASH"]),commitHeadline:e6.string().min(1),commitBody:e6.string(),authorEmail:e6.string().email().nullable().optional(),deleteWorktree:e6.boolean(),moveTicketToDone:e6.boolean()}),outputSchema:e6.object({autoMerge:i9}),annotations:ae,handler:async e=>({autoMerge:await O().configureAutoMerge(e)})}),an({name:"retry_worktree_auto_merge",title:"Retry worktree Auto Merge",description:"Retry an Auto Merge rule that needs attention, including its safe post-merge actions.",inputSchema:e6.object({worktreeId:e6.string().min(1)}),outputSchema:e6.object({autoMerge:i9}),annotations:ae,handler:async({worktreeId:e})=>({autoMerge:await O().retryAutoMerge(e)})}),an({name:"cancel_worktree_auto_merge",title:"Cancel worktree Auto Merge",description:"Disable GitHub-native Auto Merge when still active and remove the persisted rule.",inputSchema:e6.object({worktreeId:e6.string().min(1)}),outputSchema:e6.object({cancelled:e6.boolean()}),annotations:at,handler:async({worktreeId:e})=>({cancelled:await O().cancelAutoMerge(e)})})]})),new al(j)}({codebaseTools:e,builds:t,...r,toolAudit:this.audit,testExternalMcpServer:e=>this.testExternalServer(e)})}async mcpToolPresets(e){let t=e?.trim().toUpperCase()??null;if(t&&!["PLAN","SESSION"].includes(t))throw Error("Run kind is not supported");let r=await (0,t1.getPrismaClient)();return(await r.mcpToolPreset.findMany({where:"PLAN"===t?{enabledForPlans:!0}:"SESSION"===t?{enabledForSessions:!0}:void 0,orderBy:{name:"asc"},include:{tools:!0}})).map(ay)}async toolCallAudits(e={}){return this.audit.list(e)}async clearToolCallAudits(){return this.audit.clear()}async createMcpToolPreset(e){return this.saveMcpToolPreset(null,e)}async updateMcpToolPreset(e,t){return this.saveMcpToolPreset(e,t)}async saveMcpToolPreset(e,t){let r=t.name.trim(),i=t.description?.trim()??"";if(!r)throw Error("Preset name is required");if(r.length>80)throw Error("Preset name must be 80 characters or fewer");if(i.length>1e3)throw Error("Preset description must be 1,000 characters or fewer");if(!ah.has(t.iconKey))throw Error("Preset icon is not supported");if(!t.toolNames.length)throw Error("Select at least one built-in tool");if(new Set(t.toolNames).size!==t.toolNames.length)throw Error("Preset tool membership must not contain duplicates");let a=new Set(this.builtInTools.definitions().map(({name:e})=>e)),n=t.toolNames.map(e=>e.trim()),s=n.find(e=>!e||!a.has(e));if(void 0!==s)throw Error(`Unknown built-in tool: ${s||"(empty)"}`);let o=await (0,t1.getPrismaClient)();if((await o.mcpToolPreset.findMany({select:{id:!0,name:!0}})).some(t=>t.id!==e&&t.name.toLocaleLowerCase()===r.toLocaleLowerCase()))throw Error("An MCP tool preset with this name already exists");if(e&&!await o.mcpToolPreset.findUnique({where:{id:e}}))throw Error("MCP tool preset not found");let l=e??(0,b.randomUUID)();return await o.$transaction(async e=>{await e.mcpToolPreset.upsert({where:{id:l},create:{id:l,name:r,description:i,iconKey:t.iconKey,enabledForPlans:t.enabledForPlans,enabledForSessions:t.enabledForSessions},update:{name:r,description:i,iconKey:t.iconKey,enabledForPlans:t.enabledForPlans,enabledForSessions:t.enabledForSessions}}),await e.mcpToolPresetTool.deleteMany({where:{presetId:l}}),await e.mcpToolPresetTool.createMany({data:n.map(e=>({presetId:l,toolName:e}))})}),ay(await o.mcpToolPreset.findUniqueOrThrow({where:{id:l},include:{tools:!0}}))}async deleteMcpToolPreset(e){let t=await (0,t1.getPrismaClient)();return await t.mcpToolPreset.delete({where:{id:e}}),{id:e}}async resolveRunMcpPresets(e,t){let r=[...new Set(t)];if(!r.length)return{presetIds:[],toolNames:[]};let i=await (0,t1.getPrismaClient)(),a=new Map((await i.mcpToolPreset.findMany({where:{id:{in:r},..."PLAN"===e?{enabledForPlans:!0}:{enabledForSessions:!0}},include:{tools:!0}})).map(e=>[e.id,e])),n=r.filter(e=>a.has(e)),s=new Set(this.builtInTools.definitions().map(({name:e})=>e)),o=new Set;for(let e of n)for(let{toolName:t}of a.get(e).tools)s.has(t)&&o.add(t);return{presetIds:n,toolNames:[...o].sort()}}async mcpPresetToolNames(e){let t=await (0,t1.getPrismaClient)(),r=await t.mcpToolPreset.findUnique({where:{id:e},include:{tools:!0}});if(!r)return null;let i=new Set(this.builtInTools.definitions().map(({name:e})=>e));return r.tools.map(({toolName:e})=>e).filter(e=>i.has(e))}async mcpRunToolNames(e,t){let r=await (0,t1.getPrismaClient)(),i=await r.agentRun.findUnique({where:{id:e},select:{agentId:!0,mcpToolNamesJson:!0,repositoryId:!0}});if(!i)return{status:"NOT_FOUND"};if(i.agentId!==t)return{status:"FORBIDDEN"};let a=JSON.parse(i.mcpToolNamesJson),n=new Set(Array.isArray(a)?a.filter(e=>"string"==typeof e):[]);return{status:"OK",repositoryId:i.repositoryId,toolNames:this.builtInTools.definitions().map(({name:e})=>e).filter(e=>n.has(e))}}async externalServers(){let e=await (0,t1.getPrismaClient)();return Promise.all((await e.externalMcpServer.findMany({orderBy:{name:"asc"},include:{headers:!0}})).map(async e=>ag(e,0===e.headers.length||await this.credentials.isConfigured((0,t2.externalMcpHeadersCredential)(e.id)))))}async createExternalServer(e){return this.saveExternalServer(null,e)}async updateExternalServer(e,t){return this.saveExternalServer(e,t)}async saveExternalServer(e,t){let r=function(e){let t,r=e.name.trim();if(!r)throw Error("Server name is required");if(r.length>80)throw Error("Server name must be 80 characters or fewer");try{t=new URL(e.url.trim())}catch{throw Error("Server URL must be a valid HTTP or HTTPS URL")}if(!["http:","https:"].includes(t.protocol)||t.username||t.password)throw Error("Server URL must be an HTTP or HTTPS URL without embedded credentials");if("STREAMABLE_HTTP"!==e.transport&&"SSE"!==e.transport)throw Error("Transport must be Streamable HTTP or SSE");let i=e.toolNamePrefix?.trim()??"";if(i.length>64||!/^[A-Za-z0-9_.-]*$/.test(i))throw Error("Tool name prefix may contain up to 64 letters, numbers, underscores, periods, or hyphens");let a=new Set,n=e.headers.map(e=>{let t=e.name.trim();if(!t)throw Error("Header name is required");let r=t.toLowerCase();if(ap.has(r))throw Error(`${t} is managed by the MCP transport`);if(a.has(r))throw Error(`Duplicate header name: ${t}`);a.add(r);try{new Headers([[t,e.value??"validation"]])}catch{throw Error(`Invalid HTTP header: ${t}`)}return{id:e.id??null,name:t,value:e.value}});return{name:r,url:t.toString(),transport:e.transport,toolNamePrefix:i,headers:n}}(t),i=await (0,t1.getPrismaClient)();if((await i.externalMcpServer.findMany({select:{id:!0,name:!0}})).some(t=>t.id!==e&&t.name.toLocaleLowerCase()===r.name.toLocaleLowerCase()))throw Error("An MCP server with this name already exists");let a=e?await i.externalMcpServer.findUnique({where:{id:e},include:{headers:!0}}):null;if(e&&!a)throw Error("External MCP server not found");let n=new Map(a?.headers.map(e=>[e.id,e])??[]),s=e??(0,b.randomUUID)(),o=(0,t2.externalMcpHeadersCredential)(s),l=e?await this.credentials.getJson(o)??[]:[],c=new Map(l.map(e=>[e.id,e]));for(let e of r.headers){if(e.id&&!n.has(e.id))throw Error(`Header ${e.name} does not belong to this server`);if(!e.id&&!e.value)throw Error(`A value is required for the new ${e.name} header`)}let u=r.headers.map(e=>{let t=e.id??(0,b.randomUUID)(),r=e.value||c.get(t)?.value;if(!r)throw Error(`A value is required for ${e.name}`);return{id:t,name:e.name,value:r}}),d=async e=>{await e.externalMcpServer.upsert({where:{id:s},create:{id:s,name:r.name,url:r.url,transport:r.transport,toolNamePrefix:r.toolNamePrefix},update:{name:r.name,url:r.url,transport:r.transport,toolNamePrefix:r.toolNamePrefix}}),await e.externalMcpServerHeader.deleteMany({where:{serverId:s}}),u.length&&await e.externalMcpServerHeader.createMany({data:u.map(e=>({id:e.id,serverId:s,name:e.name}))})},p=JSON.stringify(u)!==JSON.stringify(l);return u.length&&p?await this.credentials.setJson(o,u,d):!u.length&&l.length?await this.credentials.delete(o,d):await i.$transaction(d),ag(await i.externalMcpServer.findUniqueOrThrow({where:{id:s},include:{headers:!0}}),!0)}async deleteExternalServer(e){return await this.credentials.delete((0,t2.externalMcpHeadersCredential)(e),async t=>{await t.externalMcpServer.delete({where:{id:e}})}),{id:e}}async testExternalServer(e){let t=await this.externalServerWithSecrets(e),r=await this.listRemoteTools(t);return{id:t.id,name:t.name,toolCount:r.length}}async catalog(){let e=await (0,t1.getPrismaClient)(),t=await e.externalMcpServer.findMany({orderBy:{name:"asc"},include:{headers:!0}}),r=await Promise.all(t.map(async e=>{try{let t=await this.listRemoteTools(await this.externalServerWithSecrets(e.id));return{id:`${ad}${e.id}`,name:e.name,source:"EXTERNAL",transport:af(e.transport),url:e.url,error:null,tools:t.map(t=>({...t,name:`${e.toolNamePrefix}${t.name}`})),children:[]}}catch(t){return{id:`${ad}${e.id}`,name:e.name,source:"EXTERNAL",transport:af(e.transport),url:e.url,error:t instanceof Error?t.message:String(t),tools:[],children:[]}}})),[i,a]=await Promise.all([this.credentials.isConfigured(t2.CREDENTIALS.githubPersonalAccessToken),this.credentials.isConfigured(t2.CREDENTIALS.gitlabAccessToken)]);return{groups:[...this.builtInTools.catalog().filter(e=>"builtin:github"===e.id?i:"builtin:gitlab"!==e.id||a).map(e=>"builtin:cache-administration"===e.id?{...e,children:e.children.filter(e=>"builtin:cache-administration:github"===e.id?i:"builtin:cache-administration:gitlab"!==e.id||a)}:e),...r]}}async callTool(e,t){let r=()=>this.invokeTool(e);return t?this.audit.execute({...t,groupId:e.groupId,toolName:e.name,arguments:e.arguments},r):r()}async callBuiltInTool(e,t,r){let i=this.builtInTools.groupIdForName(e);if(!i)throw Error(`Unknown built-in tool: ${e}`);await this.assertProviderToolConfigured(i);let a=()=>this.builtInTools.callByName(e,t);return r?this.audit.execute({...r,groupId:i,toolName:e,arguments:t},a):a()}async callRunBuiltInTool(e,t,r,i){if(am.has(e)){let e="object"!=typeof t||null===t||Array.isArray(t)?null:t;if(!r||e?.repositoryId!==r)throw Error("Run-scoped MCP may only access preparations for the run repository")}return this.callBuiltInTool(e,t,i)}async invokeTool(e){if(this.builtInTools.hasGroup(e.groupId))return await this.assertProviderToolConfigured(e.groupId),this.builtInTools.call(e.groupId,e.name,e.arguments);if(!e.groupId.startsWith(ad))throw Error("Unknown tool group");let t=e.groupId.slice(ad.length),r=await this.externalServerWithSecrets(t);if(!e.name.startsWith(r.toolNamePrefix))throw Error("Tool name does not use this server's configured prefix");let i=e.name.slice(r.toolNamePrefix.length);if(!i)throw Error("Tool name is required");return this.withClient(r,t=>t.callTool({name:i,arguments:e.arguments},void 0,{timeout:12e4,resetTimeoutOnProgress:!0}))}async assertProviderToolConfigured(e){let t="builtin:github"===e||"builtin:cache-administration:github"===e?t2.CREDENTIALS.githubPersonalAccessToken:"builtin:gitlab"===e||"builtin:cache-administration:gitlab"===e?t2.CREDENTIALS.gitlabAccessToken:null;if(t&&!await this.credentials.isConfigured(t))throw Error(`${e.includes("github")?"GitHub":"GitLab"} tools are unavailable until the provider's primary access token is configured`)}async externalServerWithSecrets(e){let t=await (0,t1.getPrismaClient)(),r=await t.externalMcpServer.findUnique({where:{id:e},include:{headers:!0}});if(!r)throw Error("External MCP server not found");if(af(r.transport),!r.headers.length)return{...r,headers:[]};let i=await this.credentials.getJson((0,t2.externalMcpHeadersCredential)(r.id));if(!i)throw Error("External MCP server headers are not configured; re-enter them in Settings");let a=new Map(i.map(e=>[e.id,e]));return{...r,headers:r.headers.map(e=>{let t=a.get(e.id);if(!t?.value)throw Error(`External MCP header ${e.name} is missing; re-enter it in Settings`);return{id:e.id,name:e.name,value:t.value}})}}async withClient(e,t){var r;let i,a=new em({name:"ai-development-environment-tools",version:"0.1.0"}),n=(r=e,async(e,t)=>{let i=new Headers(r.headers.map(e=>[e.name,e.value]));return e instanceof Request&&e.headers.forEach((e,t)=>i.set(t,e)),new Headers(t?.headers).forEach((e,t)=>i.set(t,e)),fetch(e,{...t,headers:i})}),s="STREAMABLE_HTTP"===af(e.transport)?new t0(new URL(e.url),{fetch:n}):new tY(new URL(e.url),{fetch:n}),o=()=>i??=a.close().catch(()=>void 0);try{let e;try{await Promise.race([a.connect(s,{timeout:15e3}),new Promise((t,r)=>{e=setTimeout(()=>{o(),r(Error("External MCP server connection timed out after 15000ms"))},15e3)})])}finally{e&&clearTimeout(e)}return await t(a)}finally{await o()}}async listRemoteTools(e){return this.withClient(e,async e=>{let t,r=[],i=new Set,a=0;do{let n=await e.listTools(t?{cursor:t}:void 0,{timeout:15e3});a+=1,r.push(...n.tools.map(e=>({name:e.name,title:e.title??null,description:e.description??null,inputSchema:e.inputSchema,outputSchema:e.outputSchema??null,annotations:e.annotations?{readOnlyHint:e.annotations.readOnlyHint??!1,destructiveHint:e.annotations.destructiveHint??!1,idempotentHint:e.annotations.idempotentHint??!1,openWorldHint:e.annotations.openWorldHint??!0}:null})));let s=n.nextCursor;if(s){if(i.has(s))throw Error("External MCP server returned a repeated tools/list cursor");if(a>=100)throw Error("External MCP server exceeded the tools/list pagination limit of 100 pages");i.add(s)}t=s}while(t)return r})}}e.i(406478);var ab=e.i(406315),av=e.i(354470);function ak(e){let t=e.headers.get("x-request-id")?.trim();return t&&t.length<=128?t:(0,b.randomUUID)()}function aE(e){return e.headers.get("cf-connecting-ip")??e.headers.get("x-forwarded-for")?.split(",")[0]?.trim()??"unknown"}function aS(e){return Response.json({error:{code:"TOOL_API_UNAUTHORIZED",message:e}},{status:401,headers:{"www-authenticate":"Bearer"}})}async function aI(e,t){let r=(0,ab.crossOriginError)(e);if(r)return{response:r};try{let r=await (0,av.resolveRequestPrincipal)(e.headers);if("user"!==r.kind&&("MCP"!==t||"apiKey"!==r.kind))return{response:aS("TOOLS_PAGE"===t?"A user session is required":"A user session or X-API-Key is required")};let i="user"===r.kind?`user:${r.userId}`:`api-key:${r.apiKeyId}`;return{context:{caller:`${i}@${aE(e)}`,correlationId:ak(e),source:t}}}catch(e){if(e instanceof av.PrincipalResolutionError)return{response:aS(e.message)};throw e}}async function aA(e){return aI(e,"MCP")}async function ax(e,t){try{let r=await (0,av.resolveRequestPrincipal)(e.headers,t);if("agent"!==r.kind)return{response:aS("A valid enrolled agent credential is required")};return{agentId:r.agentId,context:{caller:`agent:${r.agentId}@${aE(e)}`,correlationId:ak(e),source:"MCP"}}}catch(e){if(e instanceof av.PrincipalResolutionError)return{response:aS(e.message)};throw e}}e.s(["authorizeMcpPresetRequest",0,aA,"authorizeRunMcpRequest",0,ax,"authorizeToolRequest",0,aI],583801);class a_{constructor(e){this._server=e}requestStream(e,t,r){return this._server.requestStream(e,t,r)}createMessageStream(e,t){let r=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!r?.sampling?.tools)throw Error("Client does not support sampling tools capability.");if(e.messages.length>0){let t=e.messages[e.messages.length-1],r=Array.isArray(t.content)?t.content:[t.content],i=r.some(e=>"tool_result"===e.type),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,n=a?Array.isArray(a.content)?a.content:[a.content]:[],s=n.some(e=>"tool_use"===e.type);if(i){if(r.some(e=>"tool_result"!==e.type))throw Error("The last message must contain only tool_result content if any is present");if(!s)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(s){let e=new Set(n.filter(e=>"tool_use"===e.type).map(e=>e.id)),t=new Set(r.filter(e=>"tool_result"===e.type).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},E.CreateMessageResultSchema,t)}elicitInputStream(e,t){let r=this._server.getClientCapabilities(),i=e.mode??"form";switch(i){case"url":if(!r?.elicitation?.url)throw Error("Client does not support url elicitation.");break;case"form":if(!r?.elicitation?.form)throw Error("Client does not support form elicitation.")}let a="form"===i&&void 0===e.mode?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:a},E.ElicitResultSchema,t)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,r){return this._server.getTaskResult({taskId:e},t,r)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}}class aC extends en{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(E.LoggingLevelSchema.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{let r=this._loggingLevels.get(t);return!!r&&this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(r)},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new eu,this.setRequestHandler(E.InitializeRequestSchema,e=>this._oninitialize(e)),this.setNotificationHandler(E.InitializedNotificationSchema,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(E.SetLevelRequestSchema,async(e,t)=>{let r=t.sessionId||t.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=e.params,a=E.LoggingLevelSchema.safeParse(i);return a.success&&this._loggingLevels.set(r,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new a_(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=eo(this._capabilities,e)}setRequestHandler(e,t){let r,i=(0,k.getObjectShape)(e),a=i?.method;if(!a)throw Error("Schema is missing a method literal");if((0,k.isZ4Schema)(a)){let e=a._zod?.def;r=e?.value??a.value}else{let e=a._def;r=e?.value??a.value}if("string"!=typeof r)throw Error("Schema method literal must be a string");if("tools/call"===r){let r=async(e,r)=>{let i=(0,k.safeParse)(E.CallToolRequestSchema,e);if(!i.success){let e=i.error instanceof Error?i.error.message:String(i.error);throw new E.McpError(E.ErrorCode.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:a}=i.data,n=await Promise.resolve(t(e,r));if(a.task){let e=(0,k.safeParse)(E.CreateTaskResultSchema,n);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new E.McpError(E.ErrorCode.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let s=(0,k.safeParse)(E.CallToolResultSchema,n);if(!s.success){let e=s.error instanceof Error?s.error.message:String(s.error);throw new E.McpError(E.ErrorCode.InvalidParams,`Invalid tools/call result: ${e}`)}return s.data};return super.setRequestHandler(e,r)}return super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`)}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`)}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${e})`)}}assertTaskCapability(e){eh(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&ep(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:E.SUPPORTED_PROTOCOL_VERSIONS.includes(t)?t:E.LATEST_PROTOCOL_VERSION,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},E.EmptyResultSchema)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.");if(e.messages.length>0){let t=e.messages[e.messages.length-1],r=Array.isArray(t.content)?t.content:[t.content],i=r.some(e=>"tool_result"===e.type),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,n=a?Array.isArray(a.content)?a.content:[a.content]:[],s=n.some(e=>"tool_use"===e.type);if(i){if(r.some(e=>"tool_result"!==e.type))throw Error("The last message must contain only tool_result content if any is present");if(!s)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(s){let e=new Set(n.filter(e=>"tool_use"===e.type).map(e=>e.id)),t=new Set(r.filter(e=>"tool_result"===e.type).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},E.CreateMessageResultWithToolsSchema,t):this.request({method:"sampling/createMessage",params:e},E.CreateMessageResultSchema,t)}async elicitInput(e,t){switch(e.mode??"form"){case"url":if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");return this.request({method:"elicitation/create",params:e},E.ElicitResultSchema,t);case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let r="form"===e.mode?e:{...e,mode:"form"},i=await this.request({method:"elicitation/create",params:r},E.ElicitResultSchema,t);if("accept"===i.action&&i.content&&r.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(r.requestedSchema)(i.content);if(!e.valid)throw new E.McpError(E.ErrorCode.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){if(e instanceof E.McpError)throw e;throw new E.McpError(E.ErrorCode.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return i}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:"roots/list",params:e},E.ListRootsResultSchema,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}let aR=Symbol.for("mcp.completable");function aT(e){return!!e&&"object"==typeof e&&aR in e}(i||(i={})).Completable="McpCompletable";let aD=/^[A-Za-z0-9._-]{1,128}$/;function aN(e){let t=function(e){let t=[];if(0===e.length)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(" ")&&t.push("Tool name contains spaces, which may cause parsing issues"),e.includes(",")&&t.push("Tool name contains commas, which may cause parsing issues"),(e.startsWith("-")||e.endsWith("-"))&&t.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(e.startsWith(".")||e.endsWith("."))&&t.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!aD.test(e)){let r=e.split("").filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,r)=>r.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${r.map(e=>`"${e}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}(e);var r=t.warnings;if(r.length>0){for(let t of(console.warn(`Tool name validation warning for "${e}":`),r))console.warn(` - ${t}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}return t.isValid}class aO{constructor(e){this._mcpServer=e}registerToolTask(e,t,r){let i={taskSupport:"required",...t.execution};if("forbidden"===i.taskSupport)throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,i,t._meta,r)}}class aP{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new aC(e,t)}get experimental(){return this._experimental||(this._experimental={tasks:new aO(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(aq(E.ListToolsRequestSchema)),this.server.assertCanSetRequestHandler(aq(E.CallToolRequestSchema)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(E.ListToolsRequestSchema,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let r,i={name:e,title:t.title,description:t.description,inputSchema:(r=(0,k.normalizeObjectSchema)(t.inputSchema))?er(r,{strictUnions:!0,pipeStrategy:"input"}):aL,annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=(0,k.normalizeObjectSchema)(t.outputSchema);e&&(i.outputSchema=er(e,{strictUnions:!0,pipeStrategy:"output"}))}return i})})),this.server.setRequestHandler(E.CallToolRequestSchema,async(e,t)=>{try{let r=this._registeredTools[e.params.name];if(!r)throw new E.McpError(E.ErrorCode.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new E.McpError(E.ErrorCode.InvalidParams,`Tool ${e.params.name} disabled`);let i=!!e.params.task,a=r.execution?.taskSupport,n="createTask"in r.handler;if(("required"===a||"optional"===a)&&!n)throw new E.McpError(E.ErrorCode.InternalError,`Tool ${e.params.name} has taskSupport '${a}' but was not registered with registerToolTask`);if("required"===a&&!i)throw new E.McpError(E.ErrorCode.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if("optional"===a&&!i&&n)return await this.handleAutomaticTaskPolling(r,e,t);let s=await this.validateToolInput(r,e.params.arguments,e.params.name),o=await this.executeToolHandler(r,s,t);if(i)return o;return await this.validateToolOutput(r,o,e.params.name),o}catch(e){if(e instanceof E.McpError&&e.code===E.ErrorCode.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,t,r){if(!e.inputSchema)return;let i=(0,k.normalizeObjectSchema)(e.inputSchema)??e.inputSchema,a=await (0,k.safeParseAsync)(i,t);if(!a.success){let e="error"in a?a.error:"Unknown error",t=(0,k.getParseErrorMessage)(e);throw new E.McpError(E.ErrorCode.InvalidParams,`Input validation error: Invalid arguments for tool ${r}: ${t}`)}return a.data}async validateToolOutput(e,t,r){if(!e.outputSchema||!("content"in t)||t.isError)return;if(!t.structuredContent)throw new E.McpError(E.ErrorCode.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);let i=(0,k.normalizeObjectSchema)(e.outputSchema),a=await (0,k.safeParseAsync)(i,t.structuredContent);if(!a.success){let e="error"in a?a.error:"Unknown error",t=(0,k.getParseErrorMessage)(e);throw new E.McpError(E.ErrorCode.InvalidParams,`Output validation error: Invalid structured content for tool ${r}: ${t}`)}}async executeToolHandler(e,t,r){let i=e.handler;if("createTask"in i){if(!r.taskStore)throw Error("No task store provided.");let a={...r,taskStore:r.taskStore};return e.inputSchema?await Promise.resolve(i.createTask(t,a)):await Promise.resolve(i.createTask(a))}return e.inputSchema?await Promise.resolve(i(t,r)):await Promise.resolve(i(r))}async handleAutomaticTaskPolling(e,t,r){if(!r.taskStore)throw Error("No task store provided for task-capable tool.");let i=await this.validateToolInput(e,t.params.arguments,t.params.name),a=e.handler,n={...r,taskStore:r.taskStore},s=i?await Promise.resolve(a.createTask(i,n)):await Promise.resolve(a.createTask(n)),o=s.task.taskId,l=s.task,c=l.pollInterval??5e3;for(;"completed"!==l.status&&"failed"!==l.status&&"cancelled"!==l.status;){await new Promise(e=>setTimeout(e,c));let e=await r.taskStore.getTask(o);if(!e)throw new E.McpError(E.ErrorCode.InternalError,`Task ${o} not found during polling`);l=e}return await r.taskStore.getTaskResult(o)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(aq(E.CompleteRequestSchema)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(E.CompleteRequestSchema,async e=>{switch(e.params.ref.type){case"ref/prompt":return(0,E.assertCompleteRequestPrompt)(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return(0,E.assertCompleteRequestResourceTemplate)(e),this.handleResourceCompletion(e,e.params.ref);default:throw new E.McpError(E.ErrorCode.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,t){let r,i=this._registeredPrompts[t.name];if(!i)throw new E.McpError(E.ErrorCode.InvalidParams,`Prompt ${t.name} not found`);if(!i.enabled)throw new E.McpError(E.ErrorCode.InvalidParams,`Prompt ${t.name} disabled`);if(!i.argsSchema)return aF;let a=(0,k.getObjectShape)(i.argsSchema),n=a?.[e.params.argument.name];if(!aT(n))return aF;let s=(r=n[aR],r?.complete);return s?a$(await s(e.params.argument.value,e.params.context)):aF}async handleResourceCompletion(e,t){let r=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!r){if(this._registeredResources[t.uri])return aF;throw new E.McpError(E.ErrorCode.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let i=r.resourceTemplate.completeCallback(e.params.argument.name);return i?a$(await i(e.params.argument.value,e.params.context)):aF}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(aq(E.ListResourcesRequestSchema)),this.server.assertCanSetRequestHandler(aq(E.ListResourceTemplatesRequestSchema)),this.server.assertCanSetRequestHandler(aq(E.ReadResourceRequestSchema)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(E.ListResourcesRequestSchema,async(e,t)=>{let r=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),i=[];for(let e of Object.values(this._registeredResourceTemplates))if(e.resourceTemplate.listCallback)for(let r of(await e.resourceTemplate.listCallback(t)).resources)i.push({...e.metadata,...r});return{resources:[...r,...i]}}),this.server.setRequestHandler(E.ListResourceTemplatesRequestSchema,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(E.ReadResourceRequestSchema,async(e,t)=>{let r=new URL(e.params.uri),i=this._registeredResources[r.toString()];if(i){if(!i.enabled)throw new E.McpError(E.ErrorCode.InvalidParams,`Resource ${r} disabled`);return i.readCallback(r,t)}for(let e of Object.values(this._registeredResourceTemplates)){let i=e.resourceTemplate.uriTemplate.match(r.toString());if(i)return e.readCallback(r,i,t)}throw new E.McpError(E.ErrorCode.InvalidParams,`Resource ${r} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(aq(E.ListPromptsRequestSchema)),this.server.assertCanSetRequestHandler(aq(E.GetPromptRequestSchema)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(E.ListPromptsRequestSchema,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>{var r;let i;return{name:e,title:t.title,description:t.description,arguments:t.argsSchema?(r=t.argsSchema,(i=(0,k.getObjectShape)(r))?Object.entries(i).map(([e,t])=>({name:e,description:(0,k.getSchemaDescription)(t),required:!(0,k.isSchemaOptional)(t)})):[]):void 0}})})),this.server.setRequestHandler(E.GetPromptRequestSchema,async(e,t)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new E.McpError(E.ErrorCode.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new E.McpError(E.ErrorCode.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let i=(0,k.normalizeObjectSchema)(r.argsSchema),a=await (0,k.safeParseAsync)(i,e.params.arguments);if(!a.success){let t="error"in a?a.error:"Unknown error",r=(0,k.getParseErrorMessage)(t);throw new E.McpError(E.ErrorCode.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${r}`)}let n=a.data,s=r.callback;return await Promise.resolve(s(n,t))}{let e=r.callback;return await Promise.resolve(e(t))}}),this._promptHandlersInitialized=!0)}resource(e,t,...r){let i;"object"==typeof r[0]&&(i=r.shift());let a=r[0];if("string"==typeof t){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let r=this._createRegisteredResource(e,void 0,t,i,a);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),r}{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let r=this._createRegisteredResourceTemplate(e,void 0,t,i,a);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),r}}registerResource(e,t,r,i){if("string"==typeof t){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let a=this._createRegisteredResource(e,r.title,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let a=this._createRegisteredResourceTemplate(e,r.title,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}}_createRegisteredResource(e,t,r,i,a){let n={name:e,title:t,metadata:i,readCallback:a,enabled:!0,disable:()=>n.update({enabled:!1}),enable:()=>n.update({enabled:!0}),remove:()=>n.update({uri:null}),update:e=>{void 0!==e.uri&&e.uri!==r&&(delete this._registeredResources[r],e.uri&&(this._registeredResources[e.uri]=n)),void 0!==e.name&&(n.name=e.name),void 0!==e.title&&(n.title=e.title),void 0!==e.metadata&&(n.metadata=e.metadata),void 0!==e.callback&&(n.readCallback=e.callback),void 0!==e.enabled&&(n.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[r]=n,n}_createRegisteredResourceTemplate(e,t,r,i,a){let n={resourceTemplate:r,title:t,metadata:i,readCallback:a,enabled:!0,disable:()=>n.update({enabled:!1}),enable:()=>n.update({enabled:!0}),remove:()=>n.update({name:null}),update:t=>{void 0!==t.name&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=n)),void 0!==t.title&&(n.title=t.title),void 0!==t.template&&(n.resourceTemplate=t.template),void 0!==t.metadata&&(n.metadata=t.metadata),void 0!==t.callback&&(n.readCallback=t.callback),void 0!==t.enabled&&(n.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=n;let s=r.uriTemplate.variableNames;return Array.isArray(s)&&s.some(e=>!!r.completeCallback(e))&&this.setCompletionRequestHandler(),n}_createRegisteredPrompt(e,t,r,i,a){let n={title:t,description:r,argsSchema:void 0===i?void 0:(0,k.objectFromShape)(i),callback:a,enabled:!0,disable:()=>n.update({enabled:!1}),enable:()=>n.update({enabled:!0}),remove:()=>n.update({name:null}),update:t=>{void 0!==t.name&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=n)),void 0!==t.title&&(n.title=t.title),void 0!==t.description&&(n.description=t.description),void 0!==t.argsSchema&&(n.argsSchema=(0,k.objectFromShape)(t.argsSchema)),void 0!==t.callback&&(n.callback=t.callback),void 0!==t.enabled&&(n.enabled=t.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=n,i&&Object.values(i).some(e=>aT(e instanceof e6.ZodOptional?e._def?.innerType:e))&&this.setCompletionRequestHandler(),n}_createRegisteredTool(e,t,r,i,a,n,s,o,l){aN(e);let c={title:t,description:r,inputSchema:aM(i),outputSchema:aM(a),annotations:n,execution:s,_meta:o,handler:l,enabled:!0,disable:()=>c.update({enabled:!1}),enable:()=>c.update({enabled:!0}),remove:()=>c.update({name:null}),update:t=>{void 0!==t.name&&t.name!==e&&("string"==typeof t.name&&aN(t.name),delete this._registeredTools[e],t.name&&(this._registeredTools[t.name]=c)),void 0!==t.title&&(c.title=t.title),void 0!==t.description&&(c.description=t.description),void 0!==t.paramsSchema&&(c.inputSchema=(0,k.objectFromShape)(t.paramsSchema)),void 0!==t.outputSchema&&(c.outputSchema=(0,k.objectFromShape)(t.outputSchema)),void 0!==t.callback&&(c.handler=t.callback),void 0!==t.annotations&&(c.annotations=t.annotations),void 0!==t._meta&&(c._meta=t._meta),void 0!==t.enabled&&(c.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=c,this.setToolRequestHandlers(),this.sendToolListChanged(),c}tool(e,...t){let r,i,a,n;if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);if("string"==typeof t[0]&&(r=t.shift()),t.length>1){let r=t[0];if(aj(r))i=t.shift(),t.length>1&&"object"==typeof t[0]&&null!==t[0]&&!aj(t[0])&&(n=t.shift());else if("object"==typeof r&&null!==r){if(Object.values(r).some(e=>"object"==typeof e&&null!==e))throw Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);n=t.shift()}}let s=t[0];return this._createRegisteredTool(e,void 0,r,i,a,n,{taskSupport:"forbidden"},void 0,s)}registerTool(e,t,r){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:i,description:a,inputSchema:n,outputSchema:s,annotations:o,_meta:l}=t;return this._createRegisteredTool(e,i,a,n,s,o,{taskSupport:"forbidden"},l,r)}prompt(e,...t){let r,i;if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);"string"==typeof t[0]&&(r=t.shift()),t.length>1&&(i=t.shift());let a=t[0],n=this._createRegisteredPrompt(e,void 0,r,i,a);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),n}registerPrompt(e,t,r){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:i,description:a,argsSchema:n}=t,s=this._createRegisteredPrompt(e,i,a,n,r);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}isConnected(){return void 0!==this.server.transport}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}}let aL={type:"object",properties:{}};function aB(e){return null!==e&&"object"==typeof e&&"parse"in e&&"function"==typeof e.parse&&"safeParse"in e&&"function"==typeof e.safeParse}function aU(e){return"_def"in e||"_zod"in e||aB(e)}function aj(e){return!("object"!=typeof e||null===e||aU(e))&&(0===Object.keys(e).length||Object.values(e).some(aB))}function aM(e){if(e){if(aj(e))return(0,k.objectFromShape)(e);if(!aU(e))throw Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return e}}function aq(e){let t=(0,k.getObjectShape)(e),r=t?.method;if(!r)throw Error("Schema is missing a method literal");let i=(0,k.getLiteralValue)(r);if("string"==typeof i)return i;throw Error("Schema method literal must be a string")}function a$(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}let aF={completion:{values:[],hasMore:!1}};e.s(["createBuiltInMcpServer",0,function(e,t=(t,r)=>e.callByName(t,r),r){let i=new aP({name:"ai-development-environment",version:"0.1.0"}),a=i.registerTool.bind(i);for(let i of e.definitions())(!r||r.has(i.name))&&a(i.name,{title:i.title,description:i.description,inputSchema:i.inputSchema,outputSchema:i.outputSchema,annotations:i.annotations},async e=>t(i.name,e));return i}],700909),e.s([],719961);let aG="server:worktree-automations",aK=new Set(["SUCCEEDED","FAILED","CANCELLED","TIMED_OUT"]),aH=new Set(["SUCCEEDED","FAILED","CANCELLED"]);function aV(e){let[t,r,i]=e.split("/");if(!t||!r||i)throw Error("A GitHub repository must be in owner/name format");return{owner:t,name:r}}function aW(e){return{worktreeId:e.worktreeId,state:e.state,conflictWorkflowId:e.conflictWorkflowId,conflictWorkflowChoice:e.conflictWorkflowChoice,lastError:e.lastError,pauseReason:e.pauseReason,lastSyncedAt:e.lastSyncedAt?.toISOString()??null,updatedAt:e.updatedAt.toISOString()}}function aJ(e){return{...e,mergeMethod:e.mergeMethod,updatedAt:e.updatedAt.toISOString()}}class az{worktrees;github;jira;workflows;agentControl;polling;timer;running;rerunRequested;constructor(e,t,r,i,a,n){this.worktrees=e,this.github=t,this.jira=r,this.workflows=i,this.agentControl=a,this.polling=n,this.timer=null,this.running=!1,this.rerunRequested=!1,this.agentControl.registerCompletionObserver(async e=>{e.kind===i0.WORKTREE_AUTO_SYNC_JOB_KIND&&this.changed()}),this.polling?.register({id:aG,kind:"WORKTREE_AUTOMATION",runtime:"SERVER",enabled:!0,cadenceSeconds:60,details:{}})}startRuntime(){queueMicrotask(()=>void this.reconcile())}schedule(){this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>void this.reconcile(),6e4),this.timer.unref(),this.polling?.schedule(aG,new Date(Date.now()+6e4))}changed(){if(this.running){this.rerunRequested=!0;return}this.timer&&clearTimeout(this.timer),this.timer=null,queueMicrotask(()=>void this.reconcile())}async stopAutoSyncWork(e){e?.activeJobId&&await this.agentControl.cancelJob(e.activeJobId).catch(()=>null),e?.workflowRunId&&await this.workflows.lifecycle(e.workflowRunId,"CANCEL").catch(()=>null)}async autoSync(e){let t=await (0,t1.getPrismaClient)(),r=await t.worktreeAutoSync.findUnique({where:{worktreeId:e}});return r?aW(r):null}async configureAutoSync(e){let t=await (0,t1.getPrismaClient)(),r=await t.worktree.findFirst({where:{id:e.worktreeId,missingAt:null},select:{id:!0,branch:!0,codebaseId:!0,codebase:{select:{repositoryId:!0}}}});if(!r?.branch)throw Error("Auto Sync requires a branch");await this.stopAutoSyncWork(await t.worktreeAutoSync.findUnique({where:{worktreeId:r.id},select:{activeJobId:!0,workflowRunId:!0}}));let i=e.conflictWorkflowId?.trim()||null;if(i){let e=await t.workflow.findUnique({where:{id:i},select:{enabled:!0,archivedAt:!0,activeVersionId:!0,quickActionKind:!0,quickActionRepositories:{select:{repositoryId:!0}}}});if(!e?.enabled||e.archivedAt||!e.activeVersionId||"MERGE_CONFLICT"!==e.quickActionKind)throw Error("Select an enabled merge-conflict quick action workflow");if(e.quickActionRepositories.length>0&&!e.quickActionRepositories.some(({repositoryId:e})=>e===r.codebase.repositoryId))throw Error("The merge-conflict workflow is not available for this repository")}let a=await t.worktreeAutoSync.upsert({where:{worktreeId:r.id},create:{worktreeId:r.id,branch:r.branch,conflictWorkflowId:i,conflictWorkflowChoice:e.conflictWorkflowChoice?.trim()||null},update:{state:"ACTIVE",branch:r.branch,conflictWorkflowId:i,conflictWorkflowChoice:e.conflictWorkflowChoice?.trim()||null,activeJobId:null,workflowRunId:null,lastError:null,pauseReason:null}});return this.worktrees.publishAutomationChange(r.id,r.codebaseId),this.changed(),aW(a)}async cancelAutoSync(e){let t=await (0,t1.getPrismaClient)(),r=await t.worktreeAutoSync.findUnique({where:{worktreeId:e},select:{activeJobId:!0,workflowRunId:!0}});await this.stopAutoSyncWork(r);let i=await t.worktreeAutoSync.deleteMany({where:{worktreeId:e}});return this.worktrees.publishAutomationChange(e),i.count>0}async retryAutoSync(e){let t=await (0,t1.getPrismaClient)(),r=await t.worktreeAutoSync.update({where:{worktreeId:e},data:{state:"ACTIVE",activeJobId:null,workflowRunId:null,lastError:null,pauseReason:null}});return this.worktrees.publishAutomationChange(e),this.changed(),aW(r)}async autoMerge(e){let t=await (0,t1.getPrismaClient)(),r=await t.worktreeAutoMerge.findUnique({where:{worktreeId:e}});return r?aJ(r):null}async configureAutoMerge(e){let t=await (0,t1.getPrismaClient)(),r=await t.worktree.findFirst({where:{id:e.worktreeId,missingAt:null},select:{id:!0,primary:!0,branch:!0,codebaseId:!0,codebase:{select:{repository:{select:{canonicalOrigin:!0}}}}}});if(!r?.branch)throw Error("Auto Merge requires a branch");if(e.deleteWorktree&&r.primary)throw Error("The primary worktree cannot be deleted after merge");let i=await t.worktreeAutoMerge.findUnique({where:{worktreeId:r.id}}),a=await this.worktrees.ticketKeyForWorktree(r.id);if(e.moveTicketToDone){if(!a)throw Error("This worktree is not linked to a Jira ticket");let e=await t.jiraProject.findUnique({where:{key:a.split("-")[0]??""},select:{doneStatusId:!0}});if(!e?.doneStatusId)throw Error("Configure this Jira project's done status before enabling this option")}let n=aV(e.repositoryNameWithOwner),s=await this.github.pullRequestAutomationState(n.owner,n.name,e.pullRequestNumber);if(s.headRefName!==r.branch)throw Error("The pull request does not belong to this worktree branch");if(!s.headRepositoryNameWithOwner)throw Error("The pull request head repository is unavailable");if(r.codebase.repository.canonicalOrigin.toLowerCase()!==`github.com/${s.headRepositoryNameWithOwner.toLowerCase()}`)throw Error("The pull request head repository does not match this worktree");let o=!!(i&&(i.repositoryNameWithOwner.toLowerCase()!==e.repositoryNameWithOwner.toLowerCase()||i.pullRequestNumber!==e.pullRequestNumber)),l=!1,c=!1;try{if(i&&o){let e=aV(i.repositoryNameWithOwner),t=await this.github.pullRequestAutomationState(e.owner,e.name,i.pullRequestNumber);"OPEN"===t.state&&t.autoMergeEnabled&&(await this.github.disablePullRequestAutoMerge({...e,number:i.pullRequestNumber},"WORKTREE_AUTOMATION"),l=!0)}c=!0,await this.github.enablePullRequestAutoMerge({...n,number:e.pullRequestNumber,method:e.method,commitHeadline:e.commitHeadline,commitBody:e.commitBody,authorEmail:e.authorEmail},"WORKTREE_AUTOMATION");let s=await t.worktreeAutoMerge.upsert({where:{worktreeId:r.id},create:{worktreeId:r.id,repositoryNameWithOwner:e.repositoryNameWithOwner,pullRequestNumber:e.pullRequestNumber,branch:r.branch,mergeMethod:e.method,commitHeadline:e.commitHeadline.trim(),commitBody:e.commitBody,authorEmail:e.authorEmail?.trim()||null,deleteWorktree:e.deleteWorktree,moveTicketToDone:e.moveTicketToDone,ticketKey:a},update:{state:"ACTIVE",repositoryNameWithOwner:e.repositoryNameWithOwner,pullRequestNumber:e.pullRequestNumber,branch:r.branch,mergeMethod:e.method,commitHeadline:e.commitHeadline.trim(),commitBody:e.commitBody,authorEmail:e.authorEmail?.trim()||null,deleteWorktree:e.deleteWorktree,moveTicketToDone:e.moveTicketToDone,ticketKey:a,ticketMovedAt:null,deleteJobId:null,lastError:null}});return this.worktrees.publishAutomationChange(r.id,r.codebaseId),this.changed(),aJ(s)}catch(t){if(c&&await this.github.disablePullRequestAutoMerge({...n,number:e.pullRequestNumber},"WORKTREE_AUTOMATION").catch(()=>null),i&&(l||!o)){let e=aV(i.repositoryNameWithOwner);await this.github.enablePullRequestAutoMerge({...e,number:i.pullRequestNumber,method:i.mergeMethod,commitHeadline:i.commitHeadline,commitBody:i.commitBody,authorEmail:i.authorEmail},"WORKTREE_AUTOMATION").catch(()=>null)}throw t}}async forceAutoSync(e,t){if(!t.trim())throw Error("requestId is required");let r=await (0,t1.getPrismaClient)(),i=await r.worktreeAutoSync.findUnique({where:{worktreeId:e}});if(!i||"PAUSED"!==i.state||"PREPARATION_CONFLICT"!==i.pauseReason)throw Error("Auto Sync is not paused for a preparation conflict");let a=await this.worktrees.createAutoSyncJob(e,"SYNC",i.branch,t,!0);return await r.worktreeAutoSync.update({where:{worktreeId:e},data:{state:"SYNCING",activeJobId:a.id,workflowRunId:null,lastError:null,pauseReason:null}}),this.worktrees.publishAutomationChange(e),this.changed(),a}async cancelAutoMerge(e){let t=await (0,t1.getPrismaClient)(),r=await t.worktreeAutoMerge.findUnique({where:{worktreeId:e}});if(!r)return!1;let i=aV(r.repositoryNameWithOwner),a=await this.github.pullRequestAutomationState(i.owner,i.name,r.pullRequestNumber);return"OPEN"===a.state&&a.autoMergeEnabled&&await this.github.disablePullRequestAutoMerge({...i,number:r.pullRequestNumber},"WORKTREE_AUTOMATION"),await t.worktreeAutoMerge.delete({where:{worktreeId:e}}),this.worktrees.publishAutomationChange(e),!0}async retryAutoMerge(e){let t=await (0,t1.getPrismaClient)(),r=await t.worktreeAutoMerge.findUniqueOrThrow({where:{worktreeId:e}}),i=aV(r.repositoryNameWithOwner),a="MERGED"===(await this.github.pullRequestAutomationState(i.owner,i.name,r.pullRequestNumber)).state?"POST_MERGE":"ACTIVE",n=await t.worktreeAutoMerge.update({where:{worktreeId:e},data:{state:a,lastError:null,deleteJobId:null}});return this.worktrees.publishAutomationChange(e),this.changed(),aJ(n)}async reconcile(){if(this.running){this.rerunRequested=!0;return}this.running=!0;try{let e=async()=>{do this.rerunRequested=!1,await this.reconcileAutoSync(),await this.reconcileAutoMerge();while(this.rerunRequested)};this.polling?await this.polling.run(aG,e):await e()}catch{}finally{this.running=!1,this.schedule()}}async reconcileAutoSync(){let e=await (0,t1.getPrismaClient)();for(let t of(await e.worktreeAutoSync.findMany({where:{state:{in:["ACTIVE","SYNCING","RESOLVING"]}},include:{worktree:{select:{codebaseId:!0}}}})))try{let r=await e.worktree.findUnique({where:{id:t.worktreeId},select:{branch:!0}});if(r?.branch!==t.branch)throw Error("Auto Sync paused because the worktree branch changed");if("ACTIVE"===t.state){let r=await this.worktrees.createAutoSyncJob(t.worktreeId,"SYNC",t.branch,(0,b.randomUUID)());await e.worktreeAutoSync.update({where:{worktreeId:t.worktreeId},data:{state:"SYNCING",activeJobId:r.id,lastError:null,pauseReason:null}});continue}if("RESOLVING"===t.state){if(!t.workflowRunId)throw Error("The conflict workflow run is missing");let r=await this.workflows.run(t.workflowRunId);if(!r||!aH.has(r.status))continue;if("SUCCEEDED"!==r.status)throw Error(`The conflict workflow ${r.status.toLowerCase()}`);let i=await this.worktrees.createAutoSyncJob(t.worktreeId,"FINALIZE",t.branch,(0,b.randomUUID)());await e.worktreeAutoSync.update({where:{worktreeId:t.worktreeId},data:{state:"SYNCING",activeJobId:i.id,workflowRunId:null,pauseReason:null}});continue}if(!t.activeJobId)throw Error("The Auto Sync job is missing");let i=await this.agentControl.getJob(t.activeJobId);if(!i||!aK.has(i.status))continue;if("SUCCEEDED"!==i.status)throw Error(i.error||`Auto Sync ${i.status.toLowerCase()}`);let a=function(e){if(!e)return null;try{let t=JSON.parse(e);if(!t||"object"!=typeof t||Array.isArray(t))return null;return"string"==typeof t.outcome?String(t.outcome):null}catch{return null}}(i.resultJson);if("PREPARATION_CONFLICT"===a){let r=function(e){if(!e)return[];try{let t=JSON.parse(e);if(!t||"object"!=typeof t||Array.isArray(t))return[];let r=t.preparationConflictPaths;return Array.isArray(r)?r.filter(e=>"string"==typeof e):[]}catch{return[]}}(i.resultJson);await e.worktreeAutoSync.update({where:{worktreeId:t.worktreeId},data:{state:"PAUSED",activeJobId:null,workflowRunId:null,lastError:"Auto Sync paused because repository preparations block the rebase"+(r.length?`: ${r.join(", ")}`:""),pauseReason:"PREPARATION_CONFLICT"}});continue}if("CONFLICT"===a){if(!t.conflictWorkflowId){await e.worktreeAutoSync.update({where:{worktreeId:t.worktreeId},data:{state:"PAUSED",activeJobId:null,workflowRunId:null,lastError:"Auto Sync paused because the rebase has merge conflicts",pauseReason:"REBASE_CONFLICT"}});continue}let r=await this.workflows.trigger({workflowId:t.conflictWorkflowId,resourceKind:"WORKTREE",resourceId:t.worktreeId,subjectKey:`auto-sync:${t.worktreeId}:${i.id}`,choice:t.conflictWorkflowChoice});if(!r)throw Error("The conflict workflow did not start");await e.worktreeAutoSync.update({where:{worktreeId:t.worktreeId},data:{state:"RESOLVING",activeJobId:null,workflowRunId:r.id,lastError:null,pauseReason:null}});continue}if("UNRESOLVED"===a)throw Error("The conflict workflow did not fully resolve the rebase");if("SYNCED"!==a&&"NO_CHANGE"!==a)throw Error("The Auto Sync job returned an unknown result");await e.worktreeAutoSync.update({where:{worktreeId:t.worktreeId},data:{state:"ACTIVE",activeJobId:null,workflowRunId:null,lastError:null,pauseReason:null,..."SYNCED"===a?{lastSyncedAt:new Date}:{}}})}catch(n){let r=n instanceof Error?n.message:String(n),i=/offline|busy|already has an active job|temporarily/i.test(r),a=/branch changed/i.test(r)?"BRANCH_CHANGED":"ERROR";await e.worktreeAutoSync.updateMany({where:{worktreeId:t.worktreeId},data:{state:i?"ACTIVE":"PAUSED",activeJobId:null,workflowRunId:null,lastError:r,pauseReason:i?null:a}})}finally{this.worktrees.publishAutomationChange(t.worktreeId,t.worktree.codebaseId)}}async reconcileAutoMerge(){let e=await (0,t1.getPrismaClient)();for(let t of(await e.worktreeAutoMerge.findMany({where:{state:{in:["ACTIVE","POST_MERGE"]}},include:{worktree:{select:{codebaseId:!0,branch:!0,headSha:!0,primary:!0}}}})))try{let r=aV(t.repositoryNameWithOwner);if("ACTIVE"===t.state){let i=await this.github.pullRequestAutomationState(r.owner,r.name,t.pullRequestNumber);if("MERGED"===i.state)await e.worktreeAutoMerge.update({where:{worktreeId:t.worktreeId},data:{state:"POST_MERGE",lastError:null}}),this.rerunRequested=!0;else if("OPEN"!==i.state)throw Error("The pull request closed without merging");else if(!i.autoMergeEnabled)throw Error("GitHub Auto Merge is no longer enabled");continue}if(t.moveTicketToDone&&t.ticketKey&&!t.ticketMovedAt&&(await this.jira.transitionTicketToConfiguredDone(t.ticketKey),await e.worktreeAutoMerge.update({where:{worktreeId:t.worktreeId},data:{ticketMovedAt:new Date,lastError:null}})),!t.deleteWorktree){await e.worktreeAutoMerge.update({where:{worktreeId:t.worktreeId},data:{state:"COMPLETED",lastError:null}});continue}if(t.worktree.primary)throw Error("The primary worktree cannot be deleted");if(!t.deleteJobId){let i=await this.github.pullRequestAutomationState(r.owner,r.name,t.pullRequestNumber);if("MERGED"!==i.state)throw Error("The pull request is no longer merged");if(i.headRefName!==t.branch)throw Error("The merged pull request branch does not match the Auto Merge rule");if(t.worktree.branch!==t.branch)throw Error("The worktree branch changed after Auto Merge completed");if(!t.worktree.headSha||t.worktree.headSha!==i.headRefOid)throw Error("The worktree HEAD does not match the merged pull request");let a=await this.worktrees.deleteWorktree({worktreeId:t.worktreeId,deleteRemoteBranch:!1,requireClean:!0,expectedBranch:t.branch,expectedHeadSha:i.headRefOid,requestId:`auto-merge-${(0,b.randomUUID)()}`});await e.worktreeAutoMerge.update({where:{worktreeId:t.worktreeId},data:{deleteJobId:a.id,lastError:null}});continue}let i=await this.agentControl.getJob(t.deleteJobId);if(!i||!aK.has(i.status))continue;if("SUCCEEDED"!==i.status)throw Error(i.error||`Worktree deletion ${i.status.toLowerCase()}`);await e.worktreeAutoMerge.updateMany({where:{worktreeId:t.worktreeId},data:{state:"COMPLETED",lastError:null}})}catch(r){await e.worktreeAutoMerge.updateMany({where:{worktreeId:t.worktreeId},data:{state:"ACTION_REQUIRED",lastError:r instanceof Error?r.message:String(r)}})}finally{this.worktrees.publishAutomationChange(t.worktreeId,t.worktree.codebaseId)}}}var aY=e.i(750227),aZ=e.i(320058);function aQ(e,t){let r=[],i=e.includes("CLAUDE");return i&&r.push("CLAUDE"),(e.includes("CODEX")||!i&&e.length>0||"GLOBAL"===t&&e.includes("GITHUB_COPILOT"))&&r.push("AGENTS"),r}let aX="default",a0=["PREPARING","READY","APPLYING","NEEDS_RESOLUTION"],a1=["SCAN","READ"],a2=[...a1,"APPLY"],a3={files:{orderBy:{path:"asc"}},groups:{include:{group:!0}}},a4={skills:{include:{skill:{include:{files:!0}}}},repositories:{include:{repository:!0}}};function a6(e,t){if(!e)return t;try{return JSON.parse(e)}catch{return t}}function a8(e){return[...e.cursorEnabled?["CURSOR"]:[],...e.githubCopilotEnabled?["GITHUB_COPILOT"]:[],...e.codexEnabled?["CODEX"]:[],...e.claudeEnabled?["CLAUDE"]:[],...e.openCodeEnabled?["OPENCODE"]:[]]}function a5(e,t){return"AGENTS"===t?[".agents","skills"]:"CLAUDE"===t?[".claude","skills"]:"GLOBAL"===e?"CURSOR"===t?[".cursor","skills"]:"GITHUB_COPILOT"===t?[".copilot","skills"]:"CODEX_LEGACY"===t?[".codex","skills"]:[".config","opencode","skills"]:"CURSOR"===t?[".cursor","skills"]:"GITHUB_COPILOT"===t?[".github","skills"]:"CODEX_LEGACY"===t?[".codex","skills"]:[".opencode","skills"]}function a9(e){return/^[A-Za-z]:[\\/]/.test(e)||e.startsWith("\\\\")?aY.win32:aY.posix}function a7(e,...t){return a9(e).join(e,...t)}function ne(e){return a9(e).dirname(e)}class nt{agentControl;constructor(e){this.agentControl=e,this.agentControl.registerCompletionHandler(aZ.SKILL_SCAN_JOB_KIND,e=>this.completeScan(e)),this.agentControl.registerCompletionHandler(aZ.SKILL_READ_JOB_KIND,e=>this.completeRead(e)),this.agentControl.registerCompletionHandler(aZ.SKILL_APPLY_JOB_KIND,e=>this.completeApply(e)),this.agentControl.registerConnectionHandler(async()=>{await this.requestAutoReconcile()})}publish(e){ie.agentEventBus.publish(ie.SKILLS_CHANGED_TOPIC,{id:e??null}),e&&ie.agentEventBus.publish((0,ie.skillSyncRunTopic)(e),{id:e})}subscribe(){return ie.agentEventBus.iterate(ie.SKILLS_CHANGED_TOPIC)}subscribeRun(e){return ie.agentEventBus.iterate((0,ie.skillSyncRunTopic)(e))}async settings(){return(await (0,t1.getPrismaClient)()).skillSettings.upsert({where:{id:aX},create:{id:aX},update:{}})}async overview(e=""){let t=await (0,t1.getPrismaClient)(),r=e.trim().toLocaleLowerCase(),[i,a,n,s,o,l]=await Promise.all([t.skill.findMany({where:{deletedAt:null},include:a3,orderBy:{name:"asc"}}),t.skillGroup.findMany({include:a4,orderBy:{name:"asc"}}),t.skillToolObservation.findMany({include:{agent:!0},orderBy:[{tool:"asc"},{agent:{name:"asc"}}]}),t.skillInstallation.findMany({where:{present:!0},include:{agent:!0,codebase:{include:{repository:!0}},worktree:!0,baseline:!0,skill:!0},orderBy:[{skillName:"asc"},{rootPath:"asc"}]}),this.settings(),t.codebaseRepository.findMany({orderBy:{name:"asc"}})]);return{skills:r?i.filter(e=>[e.name,e.description,...e.groups.map(({group:e})=>e.name)].some(e=>e.toLocaleLowerCase().includes(r))):i,groups:a,observations:n,installations:r?s.filter(e=>[e.skillName,e.description,e.agent.name,e.rootPath,e.codebase?.repository.name??""].some(e=>e.toLocaleLowerCase().includes(r))):s,settings:o,repositories:l}}async getSkill(e){return(await (0,t1.getPrismaClient)()).skill.findFirst({where:{id:e,deletedAt:null},include:a3})}async saveSkill(e){let t,r=(t=e.files.map(e=>({path:e.path,contentsBase64:e.contentsBase64,executable:e.executable})),(0,aZ.parseSkillPackage)({name:e.name,description:e.description,packageHash:(0,aZ.hashSkillFiles)(t),files:t})),i=[...new Set(e.groupIds)].slice(0,100),a=await (0,t1.getPrismaClient)();if(await a.skillGroup.count({where:{id:{in:i}}})!==i.length)throw Error("One or more skill groups were not found");let n=await a.skill.findUnique({where:{name:r.name}});if(n&&n.id!==e.id)throw Error("Skill names must be unique");let s=e.id??(0,b.randomUUID)(),o=e.id?await a.skillGroupSkill.findMany({where:{skillId:s},select:{groupId:!0}}):[];return await a.$transaction(async t=>{await t.skill.upsert({where:{id:s},create:{id:s,name:r.name,description:r.description,syncGlobally:e.syncGlobally,packageHash:r.packageHash},update:{name:r.name,description:r.description,syncGlobally:e.syncGlobally,packageHash:r.packageHash,deletedAt:null}}),await t.skillFile.deleteMany({where:{skillId:s}}),await t.skillFile.createMany({data:r.files.map(e=>{let t=Buffer.from(e.contentsBase64,"base64");return{id:(0,b.randomUUID)(),skillId:s,path:e.path,contents:t,executable:e.executable,contentHash:(0,b.createHash)("sha256").update(t).digest("hex")}})}),await t.skillGroupSkill.deleteMany({where:{skillId:s}}),i.length&&await t.skillGroupSkill.createMany({data:i.map(e=>({groupId:e,skillId:s}))})}),this.publish(),await this.scheduleAutoSync([...i,...o.map(e=>e.groupId)]),await this.getSkill(s)}async deleteSkill(e){let t=await (0,t1.getPrismaClient)(),r=await t.skill.findUnique({where:{id:e},include:{groups:!0}});return!!r&&(await t.skill.update({where:{id:e},data:{deletedAt:new Date}}),this.publish(),await this.scheduleAutoSync(r.groups.map(e=>e.groupId)),!0)}async saveGroup(e){let t=e.name.trim();if(!t||t.length>80)throw Error("Group names must contain 1-80 characters");let r=[...new Set(e.skillIds)].slice(0,500),i=[...new Set(e.repositoryIds)].slice(0,500),a=await (0,t1.getPrismaClient)(),[n,s,o]=await Promise.all([a.skill.count({where:{id:{in:r},deletedAt:null}}),a.codebaseRepository.count({where:{id:{in:i}}}),a.skillGroup.findUnique({where:{name:t}})]);if(n!==r.length)throw Error("One or more skills were not found");if(s!==i.length)throw Error("One or more repositories were not found");if(o&&o.id!==e.id)throw Error("Group names must be unique");let l=e.id??(0,b.randomUUID)();return await a.$transaction(async e=>{await e.skillGroup.upsert({where:{id:l},create:{id:l,name:t},update:{name:t}}),await e.skillGroupSkill.deleteMany({where:{groupId:l}}),await e.codebaseRepositorySkillGroup.deleteMany({where:{groupId:l}}),r.length&&await e.skillGroupSkill.createMany({data:r.map(e=>({groupId:l,skillId:e}))}),i.length&&await e.codebaseRepositorySkillGroup.createMany({data:i.map(e=>({groupId:l,repositoryId:e}))})}),this.publish(),await this.scheduleAutoSync([l]),a.skillGroup.findUniqueOrThrow({where:{id:l},include:a4})}async validateGroupIds(e){let t=[...new Set(e)].slice(0,100),r=await (0,t1.getPrismaClient)();if(await r.skillGroup.count({where:{id:{in:t}}})!==t.length)throw Error("One or more skill groups were not found");return t}async groupsForRepository(e){let t=await (0,t1.getPrismaClient)();return(await t.codebaseRepositorySkillGroup.findMany({where:{repositoryId:e},include:{group:!0},orderBy:{group:{name:"asc"}}})).map(e=>e.group)}async deleteGroup(e){let t=await (0,t1.getPrismaClient)(),r=await t.skillGroup.deleteMany({where:{id:e}});return r.count&&this.publish(),r.count&&(await this.settings()).autoSyncProjectGroups&&await this.prepareSync("GROUP",null,!0),r.count>0}async saveSettings(e){let t=await (0,t1.getPrismaClient)(),r=await t.skillSettings.upsert({where:{id:aX},create:{id:aX,...e},update:e});return this.publish(),r.autoSyncProjectGroups&&await this.prepareSync("GROUP",null,!0),r}async setRepositoryGroups(e,t){let r=await this.validateGroupIds(t),i=await (0,t1.getPrismaClient)();await i.$transaction(async t=>{await t.codebaseRepositorySkillGroup.deleteMany({where:{repositoryId:e}}),r.length&&await t.codebaseRepositorySkillGroup.createMany({data:r.map(t=>({repositoryId:e,groupId:t}))})}),this.publish(),(await this.settings()).autoSyncProjectGroups&&await this.prepareSync("GROUP",null,!0)}async scheduleAutoSync(e){if((await this.settings()).autoSyncProjectGroups&&e.length)for(let t of[...new Set(e)])await this.prepareSync("GROUP",t,!0)}async requestAutoReconcile(){return(await this.settings()).autoSyncProjectGroups?this.prepareSync("GROUP",null,!0):null}async targets(e){let t=await (0,t1.getPrismaClient)(),r=await t.codebase.findMany({where:{agentId:e,availability:"AVAILABLE"},include:{worktrees:{where:{missingAt:null}}}}),i=new Map;for(let e of r)for(let t of(i.set(e.folder,{codebaseId:e.id,worktreeId:null,folder:e.folder}),e.worktrees))i.set(t.folder,{codebaseId:e.id,worktreeId:t.id,folder:t.folder});return[...i.values()]}async prepareSync(e,t,r=!1){let i=await (0,t1.getPrismaClient)();if(t&&!await i.skillGroup.findUnique({where:{id:t}}))throw Error("Skill group not found");if(r){let r=await i.skillSyncRun.findFirst({where:{kind:e,groupId:t??null,status:{in:a0}},orderBy:{createdAt:"desc"}});if(r)return r}let a=await i.skillSyncRun.create({data:{id:(0,b.randomUUID)(),kind:e,groupId:t??null,automatic:r,status:"PREPARING"}}),n=a8(await this.settings()),s=await i.agent.findMany({orderBy:{name:"asc"}});for(let e of s){let t=await i.skillSyncItem.create({data:{id:(0,b.randomUUID)(),runId:a.id,agentId:e.id,direction:"SCAN",status:"PENDING"}});await this.agentControl.createJob({agentId:e.id,kind:aZ.SKILL_SCAN_JOB_KIND,payload:{tools:n,targets:await this.targets(e.id),syncRunId:a.id,syncItemId:t.id},idempotencyKey:`skills:scan:${a.id}:${e.id}`,timeoutSeconds:300,visibility:r?"SYSTEM":"USER"})}return!s.length&&(await i.skillSyncRun.update({where:{id:a.id},data:{status:"READY"}}),r)?this.applyRun(a.id):(this.publish(a.id),this.getRun(a.id))}async getRun(e){return(await (0,t1.getPrismaClient)()).skillSyncRun.findUnique({where:{id:e},include:{group:!0,items:{include:{skill:!0,installation:{include:{agent:!0}},agent:!0},orderBy:{createdAt:"asc"}}}})}completionIds(e){return a6(e.payloadJson,{})}async completeScan(e){let{syncRunId:t,syncItemId:r}=this.completionIds(e);if(!t||!r)return;let i=await (0,t1.getPrismaClient)();if(await i.skillSyncItem.findFirst({where:{id:r,runId:t,direction:"SCAN",status:"PENDING"}})){if("SUCCEEDED"===e.status&&e.resultJson){let t=a6(e.resultJson,{configuredTools:[],installations:[],warnings:[]}),a=new Date;await i.$transaction(async i=>{for(let r of(await i.skillInstallation.updateMany({where:{agentId:e.agentId},data:{present:!1}}),t.configuredTools))aZ.AI_TOOLS.includes(r.tool)&&await i.skillToolObservation.upsert({where:{agentId_tool:{agentId:e.agentId,tool:r.tool}},create:{agentId:e.agentId,tool:r.tool,configured:r.configured,homePath:r.homePath,checkedAt:a},update:{configured:r.configured,homePath:r.homePath,checkedAt:a}});for(let r of t.installations){let t=await i.skill.findUnique({where:{name:r.skillName},select:{id:!0,deletedAt:!0}});await i.skillInstallation.upsert({where:{agentId_rootPath_skillName:{agentId:e.agentId,rootPath:r.rootPath,skillName:r.skillName}},create:{id:(0,b.randomUUID)(),agentId:e.agentId,skillId:t&&!t.deletedAt?t.id:null,codebaseId:r.codebaseId,worktreeId:r.worktreeId,scope:r.scope,rootKind:r.rootKind,rootPath:r.rootPath,skillName:r.skillName,description:r.description,packageHash:r.packageHash,present:!0,fileCount:r.fileCount,totalBytes:r.totalBytes,tracked:r.tracked,consumersJson:JSON.stringify(r.consumers),lastSeenAt:a},update:{skillId:t&&!t.deletedAt?t.id:void 0,codebaseId:r.codebaseId,worktreeId:r.worktreeId,scope:r.scope,rootKind:r.rootKind,description:r.description,packageHash:r.packageHash,present:!0,fileCount:r.fileCount,totalBytes:r.totalBytes,tracked:r.tracked,consumersJson:JSON.stringify(r.consumers),lastSeenAt:a}})}await i.skillSyncItem.updateMany({where:{id:r,status:"PENDING"},data:{status:"COMPLETE",error:t.warnings?.length?t.warnings.join("\n").slice(0,64e3):null}})})}else await i.skillSyncItem.updateMany({where:{id:r,status:"PENDING"},data:{status:"FAILED",error:e.error??"Skill scan failed"}});await i.skillSyncItem.count({where:{runId:t,direction:"SCAN",status:"PENDING"}})||await this.buildPlan(t),this.publish(t)}}async configuredByAgent(){let e=await (0,t1.getPrismaClient)(),t=new Set(a8(await this.settings())),r=await e.skillToolObservation.findMany({where:{configured:!0}}),i=new Map;for(let e of r){if(!t.has(e.tool))continue;let r=i.get(e.agentId)??[];r.push(e.tool),i.set(e.agentId,r)}return i}async desiredLocations(e,t=new Set){let r=await (0,t1.getPrismaClient)(),i=await this.configuredByAgent(),a=await r.skillToolObservation.findMany({where:{configured:!0}}),n=new Map;for(let e of a)n.set(e.agentId,e.homePath);let s=[];if("ALL"===e.kind){let e=await r.skill.findMany({where:{deletedAt:null,syncGlobally:!0},include:a3});for(let[r,a]of i){if(t.has(r))continue;let i=n.get(r);if(i)for(let t of aQ(a,"GLOBAL")){let a=a7(i,...a5("GLOBAL",t));for(let i of e)s.push({skill:i,agentId:r,codebaseId:null,worktreeId:null,scope:"GLOBAL",rootKind:t,folder:null,rootPath:a,targetPath:a7(a,i.name)})}}}for(let a of(await r.skillGroup.findMany({where:"GROUP"===e.kind&&e.groupId?{id:e.groupId}:void 0,include:{skills:{where:{skill:{deletedAt:null}},include:{skill:{include:a3}}},repositories:{include:{repository:{include:{codebases:{where:{availability:"AVAILABLE"},include:{worktrees:{where:{missingAt:null}}}}}}}}}})))for(let e of a.repositories)for(let r of e.repository.codebases){if(t.has(r.agentId))continue;let e=aQ(i.get(r.agentId)??[],"PROJECT");for(let t of[{folder:r.folder,worktreeId:null},...r.worktrees.map(e=>({folder:e.folder,worktreeId:e.id}))])for(let i of e){let e=a7(t.folder,...a5("PROJECT",i));for(let n of a.skills)s.push({skill:n.skill,agentId:r.agentId,codebaseId:r.id,worktreeId:t.worktreeId,scope:"PROJECT",rootKind:i,folder:t.folder,rootPath:e,targetPath:a7(e,n.skill.name)})}}return[...new Map(s.map(e=>[`${e.agentId}\0${e.targetPath}`,e])).values()]}installationWhere(e,t){return{present:!0,...t.size?{agentId:{notIn:[...t]}}:{},..."GROUP"===e.kind?{scope:"PROJECT",...e.groupId?{codebase:{repository:{skillGroups:{some:{groupId:e.groupId}}}}}:{}}:{}}}async buildPlan(e){let t=await (0,t1.getPrismaClient)(),r=await t.skillSyncRun.findUniqueOrThrow({where:{id:e}}),i=new Set((await t.skillSyncItem.findMany({where:{runId:e,direction:"SCAN",status:"SKIPPED"},select:{agentId:!0}})).flatMap(e=>e.agentId?[e.agentId]:[]));await t.skillSyncItem.deleteMany({where:{runId:e,direction:{not:"SCAN"}}});let[a,n,s,o,l]=await Promise.all([t.skill.findMany({where:{deletedAt:null},include:a3}),t.skill.findMany({where:{deletedAt:{not:null}}}),t.skillInstallation.findMany({where:this.installationWhere(r,i),include:{baseline:!0}}),this.desiredLocations(r,i),"GROUP"===r.kind&&r.groupId?this.desiredLocations({...r,groupId:null},i):this.desiredLocations(r,i)]),c=new Map(a.map(e=>[e.name,e])),u=new Map(a.map(e=>[e.id,e])),d=new Map(n.map(e=>[e.name,e])),p=new Map(n.map(e=>[e.id,e])),h=new Map;for(let e of s){let t=h.get(e.skillName)??[];t.push(e.packageHash),h.set(e.skillName,t)}let m=new Set([...h].flatMap(([e,t])=>{var r;return(r=c.get(e)?.packageHash??null,new Set(t.filter(e=>null===r||e!==r)).size>1)?[e]:[]})),f=[];for(let t of o)s.find(e=>e.agentId===t.agentId&&e.rootPath===t.rootPath&&e.skillName===t.skill.name)||f.push({id:(0,b.randomUUID)(),runId:e,skillId:t.skill.id,agentId:t.agentId,direction:"EXPORT",status:"READY",sourceHash:t.skill.packageHash,candidatePackageJson:JSON.stringify({location:t})});for(let r of s){let i=r.baseline?.skillId??r.skillId,a=(i?u.get(i):void 0)??c.get(r.skillName),n=(i?p.get(i):void 0)??d.get(r.skillName),s=!!r.baseline&&!!a&&a.name!==r.skillName,h=o.find(e=>e.agentId===r.agentId&&e.rootPath===r.rootPath&&e.skill.name===r.skillName),y=l.find(e=>e.agentId===r.agentId&&e.rootPath===r.rootPath&&e.skill.name===r.skillName);a&&r.packageHash===a.packageHash&&!r.baseline&&await t.skillSyncBaseline.upsert({where:{installationId:r.id},create:{id:(0,b.randomUUID)(),installationId:r.id,skillId:a.id,packageHash:a.packageHash},update:{skillId:a.id,packageHash:a.packageHash,syncedAt:new Date}});let w="UNCHANGED",v="COMPLETE";if(n&&r.baseline&&!r.tracked)w="DELETE_MANAGED",v="READY";else if(s)w=r.tracked?"CONFLICT":"DELETE_MANAGED",v=r.tracked?"BLOCKED":"READY";else if(y||!r.baseline||r.tracked)if(a)if(r.packageHash!==a.packageHash){var g;v="CONFLICT"===(w=m.has(r.skillName)?"CONFLICT":(g={databaseHash:a.packageHash,targetHash:r.packageHash,baselineHash:r.baseline?.packageHash??null,tracked:r.tracked}).databaseHash===g.targetHash?"UNCHANGED":g.tracked?"CONFLICT":g.baselineHash===g.databaseHash?"IMPORT":g.baselineHash===g.targetHash?"EXPORT":"CONFLICT")?"BLOCKED":"READY"}else!y&&["CURSOR","GITHUB_COPILOT","CODEX_LEGACY","OPENCODE"].includes(r.rootKind)&&l.some(e=>e.agentId===r.agentId&&e.scope===r.scope&&("GLOBAL"===r.scope||e.codebaseId===r.codebaseId&&e.worktreeId===r.worktreeId)&&e.skill.name===r.skillName&&e.skill.packageHash===r.packageHash)&&!r.tracked&&(w="DELETE_REDUNDANT",v="READY");else v="CONFLICT"==(w=m.has(r.skillName)?"CONFLICT":"IMPORT")||"PROJECT"===r.scope?"BLOCKED":"READY";else w="DELETE_MANAGED",v="READY";f.push({id:(0,b.randomUUID)(),runId:e,skillId:a?.id??n?.id??null,installationId:r.id,agentId:r.agentId,direction:w,status:v,sourceHash:a?.packageHash??null,targetHash:r.packageHash,candidatePackageJson:JSON.stringify({location:{scope:r.scope,rootKind:r.rootKind,folder:"PROJECT"===r.scope?h?.folder??null:null,skillName:r.skillName},projectGroupRequired:!a&&"PROJECT"===r.scope})})}f.length&&await t.skillSyncItem.createMany({data:f});let y=await t.skillSyncItem.findMany({where:{runId:e,installationId:{not:null},direction:{in:["IMPORT","CONFLICT"]}},include:{installation:!0}}),w=new Map;for(let e of y){if(!e.agentId||!e.installation)continue;let t=w.get(e.agentId)??[];t.push(e),w.set(e.agentId,t)}let v=a8(await this.settings());for(let[r,i]of w){let a=await t.skillSyncItem.create({data:{id:(0,b.randomUUID)(),runId:e,agentId:r,direction:"READ",status:"PENDING"}}),n=await this.targets(r);await this.agentControl.createJob({agentId:r,kind:aZ.SKILL_READ_JOB_KIND,payload:{tools:v,targets:n,requests:i.map(e=>({scope:e.installation.scope,rootKind:e.installation.rootKind,folder:"PROJECT"===e.installation.scope?n.find(t=>t.codebaseId===e.installation.codebaseId&&t.worktreeId===e.installation.worktreeId)?.folder??null:null,skillName:e.installation.skillName})),syncRunId:e,syncItemId:a.id},idempotencyKey:`skills:read:${e}:${r}`,timeoutSeconds:300})}await this.refreshRunStatus(e)}async completeRead(e){let{syncRunId:t,syncItemId:r}=this.completionIds(e);if(!t||!r)return;let i=await (0,t1.getPrismaClient)();if(await i.skillSyncItem.findFirst({where:{id:r,runId:t,direction:"READ",status:"PENDING"}})){if("SUCCEEDED"===e.status&&e.resultJson){let a=a6(e.resultJson,{packages:[]}),n=await i.skillSyncItem.findMany({where:{runId:t,agentId:e.agentId,installationId:{not:null},direction:{in:["IMPORT","CONFLICT"]}},include:{installation:!0}});for(let e of a.packages){let t=n.find(t=>t.installation?.skillName===e.package.name&&t.installation?.rootKind===e.rootKind&&t.installation?.scope===e.scope&&("GLOBAL"===e.scope||t.installation?.rootPath===a7(e.folder,...a5("PROJECT",e.rootKind))));if(!t)continue;let r=a6(t.candidatePackageJson,{});await i.skillSyncItem.update({where:{id:t.id},data:{candidatePackageJson:JSON.stringify({...r,package:e.package})}})}await i.skillSyncItem.updateMany({where:{id:r,status:"PENDING"},data:{status:"COMPLETE"}})}else await i.skillSyncItem.updateMany({where:{id:r,status:"PENDING"},data:{status:"FAILED",error:e.error??"Skill package read failed"}});await this.refreshRunStatus(t),this.publish(t)}}async refreshRunStatus(e){let t=await (0,t1.getPrismaClient)(),r=await t.skillSyncItem.findMany({where:{runId:e}});if(r.some(e=>a1.includes(e.direction)&&"PENDING"===e.status))return;let i=r.some(e=>"BLOCKED"===e.status),a=r.some(e=>"FAILED"===e.status),n=i?"NEEDS_RESOLUTION":a?"PARTIAL":"READY",s=await t.skillSyncRun.update({where:{id:e},data:{status:n}});this.publish(e),s.automatic&&"READY"===n&&await this.applyRun(e)}async skipPending(e){let t=await (0,t1.getPrismaClient)();await t.skillSyncRun.findUniqueOrThrow({where:{id:e}});let r=await t.skillSyncItem.findMany({where:{runId:e,direction:{in:a2},status:"PENDING",agentId:{not:null}}}),i=[];for(let a of r){if(1!==(await t.skillSyncItem.updateMany({where:{id:a.id,status:"PENDING"},data:{status:"SKIPPED",resolution:"SKIP"}})).count||!a.agentId)continue;i.push(a);let r=await t.agentJob.findUnique({where:{agentId_idempotencyKey:{agentId:a.agentId,idempotencyKey:`skills:${a.direction.toLowerCase()}:${e}:${a.agentId}`}}});r&&await this.agentControl.cancelJob(r.id)}if(!i.length)return this.getRun(e);let a=[...new Set(i.flatMap(e=>"READ"===e.direction&&e.agentId?[e.agentId]:[]))];a.length&&await t.skillSyncItem.updateMany({where:{runId:e,agentId:{in:a},direction:{notIn:a2},status:{in:["READY","BLOCKED"]}},data:{status:"SKIPPED",resolution:"SKIP"}});let n=i.filter(e=>"APPLY"===e.direction),s=n.flatMap(e=>{let{deployments:t=[]}=a6(e.candidatePackageJson,{});return t.map(e=>e.id)});return s.length&&await t.skillDeployment.updateMany({where:{id:{in:s},status:"PENDING"},data:{status:"SKIPPED"}}),i.some(e=>"SCAN"===e.direction)?await t.skillSyncItem.count({where:{runId:e,direction:"SCAN",status:"PENDING"}})||await this.buildPlan(e):a.length&&await this.refreshRunStatus(e),n.length&&(await t.skillSyncItem.count({where:{runId:e,direction:"APPLY",status:"PENDING"}})||await t.skillSyncRun.update({where:{id:e},data:{status:"PARTIAL",finishedAt:new Date}})),this.publish(e),this.getRun(e)}async resolveItem(e){let t=await (0,t1.getPrismaClient)(),r=await t.skillSyncItem.findUniqueOrThrow({where:{id:e.itemId}});if(!["BLOCKED","READY"].includes(r.status))throw Error("Sync item cannot be resolved");let i=a6(r.candidatePackageJson,{});if("MANUAL"===e.resolution&&(i.package=(0,aZ.parseSkillPackage)(e.package,"manual resolution package")),"TARGET"===e.resolution&&!i.package)throw Error("The target package is unavailable");if("DELETE"===e.resolution&&!r.installationId)throw Error("The client skill installation is unavailable");if(i.projectGroupRequired&&["TARGET","MANUAL"].includes(e.resolution)){if(!e.groupId||!await t.skillGroup.findUnique({where:{id:e.groupId}}))throw Error("A project skill import requires a skill group");i.groupId=e.groupId}if(await t.skillSyncItem.update({where:{id:r.id},data:{resolution:e.resolution,direction:"DELETE"===e.resolution?"DELETE_REDUNDANT":r.direction,candidatePackageJson:JSON.stringify(i),status:"SKIP"===e.resolution?"SKIPPED":"READY"}}),["TARGET","MANUAL"].includes(e.resolution)){let e=i.package?.name??null;if(e){let i=(await t.skillSyncItem.findMany({where:{runId:r.runId,id:{not:r.id},direction:"CONFLICT",status:{in:["BLOCKED","READY"]}},include:{skill:!0,installation:!0}})).flatMap(t=>(t.skill?.name??t.installation?.skillName)===e?[t.id]:[]);i.length&&await t.skillSyncItem.updateMany({where:{id:{in:i}},data:{resolution:"DATABASE",status:"READY"}})}}return await this.refreshRunStatus(r.runId),this.getRun(r.runId)}async importCandidates(e){let t=await (0,t1.getPrismaClient)();for(let r of(await t.skillSyncItem.findMany({where:{runId:e,status:"READY",OR:[{direction:"IMPORT"},{direction:"CONFLICT",resolution:{in:["TARGET","MANUAL"]}}]},include:{installation:!0}}))){let e=a6(r.candidatePackageJson,{});if(!e.package)continue;let i=await t.skill.findUnique({where:{name:e.package.name},include:a3}),a=await this.saveSkill({id:i?.id,name:e.package.name,description:e.package.description,syncGlobally:i?.syncGlobally??!e.groupId,groupIds:[...i?.groups.map(e=>e.groupId)??[],...e.groupId?[e.groupId]:[]],files:e.package.files});r.installationId&&(await t.skillInstallation.update({where:{id:r.installationId},data:{skillId:a.id}}),r.targetHash===a.packageHash&&await t.skillSyncBaseline.upsert({where:{installationId:r.installationId},create:{id:(0,b.randomUUID)(),installationId:r.installationId,skillId:a.id,packageHash:a.packageHash},update:{skillId:a.id,packageHash:a.packageHash,syncedAt:new Date}}))}}async applyRun(e){let t=await (0,t1.getPrismaClient)(),r=await t.skillSyncRun.findUniqueOrThrow({where:{id:e}});if(await t.skillSyncItem.count({where:{runId:e,status:"BLOCKED"}}))throw Error("Resolve all conflicts before applying sync");await this.importCandidates(e);let i=new Set((await t.skillSyncItem.findMany({where:{runId:e,direction:{in:a1},status:"SKIPPED"},select:{agentId:!0}})).flatMap(e=>e.agentId?[e.agentId]:[])),a=await this.desiredLocations(r,i),n=await t.skillInstallation.findMany({where:this.installationWhere(r,i)}),s=new Map,o=new Map,l=(e,t)=>{let r=s.get(e)??[];r.push(t),s.set(e,r)},c=(e,t)=>{let r=o.get(e)??[];r.push(t),o.set(e,r)};for(let e of a){let r=n.find(t=>t.agentId===e.agentId&&t.rootPath===e.rootPath&&t.skillName===e.skill.name);if(r?.packageHash===e.skill.packageHash||r?.tracked)continue;l(e.agentId,{kind:"WRITE",scope:e.scope,rootKind:e.rootKind,folder:e.folder,package:function(e){let t=e.files.map(e=>({path:e.path,contentsBase64:Buffer.from(e.contents).toString("base64"),executable:e.executable}));return{name:e.name,description:e.description,packageHash:e.packageHash,files:t}}(e.skill),manageGitExclude:"PROJECT"===e.scope});let i=await t.skillDeployment.upsert({where:{agentId_targetPath:{agentId:e.agentId,targetPath:e.targetPath}},create:{id:(0,b.randomUUID)(),skillId:e.skill.id,agentId:e.agentId,codebaseId:e.codebaseId,worktreeId:e.worktreeId,scope:e.scope,rootKind:e.rootKind,targetPath:e.targetPath,desiredHash:e.skill.packageHash,status:"PENDING"},update:{skillId:e.skill.id,desiredHash:e.skill.packageHash,status:"PENDING",lastError:null}});c(e.agentId,{id:i.id,desiredHash:e.skill.packageHash})}let u=await t.skillSyncItem.findMany({where:{runId:e,direction:{in:["DELETE_REDUNDANT","DELETE_MANAGED"]},status:"READY"},include:{installation:!0}}),d=new Set(u.flatMap(e=>e.installationId?[e.installationId]:[])),p=n.filter(e=>!d.has(e.id)&&!e.tracked&&["CURSOR","GITHUB_COPILOT","CODEX_LEGACY","OPENCODE"].includes(e.rootKind)&&!a.some(t=>t.agentId===e.agentId&&t.rootPath===e.rootPath&&t.skill.name===e.skillName)&&a.some(t=>t.agentId===e.agentId&&t.scope===e.scope&&("GLOBAL"===e.scope||t.codebaseId===e.codebaseId&&t.worktreeId===e.worktreeId)&&t.skill.name===e.skillName&&t.skill.packageHash===e.packageHash));for(let e of[...u.flatMap(e=>e.installation?[e.installation]:[]),...p]){if(!e||e.tracked)continue;let t=await this.targets(e.agentId),r="PROJECT"===e.scope?t.find(t=>t.codebaseId===e.codebaseId&&t.worktreeId===e.worktreeId)?.folder??null:null;("PROJECT"!==e.scope||r)&&l(e.agentId,{kind:"DELETE",scope:e.scope,rootKind:e.rootKind,folder:r,skillName:e.skillName,manageGitExclude:"PROJECT"===e.scope})}for(let[r,i]of s){let a=await t.skillSyncItem.create({data:{id:(0,b.randomUUID)(),runId:e,agentId:r,direction:"APPLY",status:"PENDING",candidatePackageJson:JSON.stringify({deployments:o.get(r)??[]})}});await this.agentControl.createJob({agentId:r,kind:aZ.SKILL_APPLY_JOB_KIND,payload:{operations:i,syncRunId:e,syncItemId:a.id},idempotencyKey:`skills:apply:${e}:${r}`,timeoutSeconds:600})}return await t.skillSyncRun.update({where:{id:e},data:s.size?{status:"APPLYING"}:{status:"SUCCEEDED",finishedAt:new Date}}),this.publish(e),this.getRun(e)}async completeApply(e){let{syncRunId:t,syncItemId:r}=this.completionIds(e);if(!t||!r)return;let i=await (0,t1.getPrismaClient)(),a=await i.skillSyncItem.findFirst({where:{id:r,runId:t,direction:"APPLY",status:"PENDING"}});if(!a)return;let n="SUCCEEDED"===e.status,{deployments:s=[]}=a6(a?.candidatePackageJson??null,{});await i.skillSyncItem.updateMany({where:{id:r,status:"PENDING"},data:{status:n?"COMPLETE":"FAILED",error:n?null:e.error??"Skill apply failed"}});let o=await i.skillDeployment.findMany({where:{id:{in:s.map(e=>e.id)},agentId:e.agentId,status:"PENDING"},include:{skill:{include:{files:!0}}}}),l=a6(e.resultJson,{});if(n){let t=await this.configuredByAgent();for(let e of o){let r=s.find(t=>t.id===e.id),a=l.results?.find(t=>"WRITE"===t.kind&&t.path===e.targetPath);if(!r||e.desiredHash!==r.desiredHash||a?.packageHash!==r.desiredHash)continue;let n=await i.skillInstallation.upsert({where:{agentId_rootPath_skillName:{agentId:e.agentId,rootPath:ne(e.targetPath),skillName:e.skill.name}},create:{id:(0,b.randomUUID)(),skillId:e.skillId,agentId:e.agentId,codebaseId:e.codebaseId,worktreeId:e.worktreeId,scope:e.scope,rootKind:e.rootKind,rootPath:ne(e.targetPath),skillName:e.skill.name,description:e.skill.description,packageHash:e.desiredHash,present:!0,fileCount:e.skill.files.length,totalBytes:e.skill.files.reduce((e,t)=>e+t.contents.byteLength,0),tracked:!1,consumersJson:JSON.stringify(t.get(e.agentId)??[]),lastSeenAt:new Date},update:{skillId:e.skillId,codebaseId:e.codebaseId,worktreeId:e.worktreeId,scope:e.scope,rootKind:e.rootKind,description:e.skill.description,packageHash:e.desiredHash,present:!0,fileCount:e.skill.files.length,totalBytes:e.skill.files.reduce((e,t)=>e+t.contents.byteLength,0),tracked:!1,consumersJson:JSON.stringify(t.get(e.agentId)??[]),lastSeenAt:new Date}});await i.skillSyncBaseline.upsert({where:{installationId:n.id},create:{id:(0,b.randomUUID)(),installationId:n.id,skillId:e.skillId,packageHash:e.desiredHash},update:{skillId:e.skillId,packageHash:e.desiredHash,syncedAt:new Date}}),await i.skillDeployment.update({where:{id:e.id},data:{status:"INSTALLED",installedHash:e.desiredHash,lastError:null}})}for(let t of l.results??[])if("DELETE"===t.kind){var c;await i.skillInstallation.updateMany({where:{agentId:e.agentId,rootPath:ne(t.path),skillName:a9(c=t.path).basename(c)},data:{present:!1,lastSeenAt:new Date}})}}else for(let t of s)await i.skillDeployment.updateMany({where:{id:t.id,agentId:e.agentId,desiredHash:t.desiredHash,status:"PENDING"},data:{status:"FAILED",lastError:e.error??"Skill apply failed"}});if(!await i.skillSyncItem.count({where:{runId:t,direction:"APPLY",status:"PENDING"}})){let e=await i.skillSyncItem.count({where:{runId:t,direction:"APPLY",status:{in:["FAILED","SKIPPED"]}}});await i.skillSyncRun.update({where:{id:t},data:{status:e?"PARTIAL":"SUCCEEDED",finishedAt:new Date}})}this.publish(t)}}e.i(464841);var nr=e.i(220629),ni=e.i(692680);e.i(493015);var na=e.i(49172);function nn(e){if(!e)return{};let t=JSON.parse(e);return t&&"object"==typeof t&&!Array.isArray(t)?t:{}}function ns(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.valueOf())?null:t}function no(e){try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}catch{return[]}}class nl{agentControl;fetcher;credentials;constructor(e,t=fetch,r=new t3.CredentialService){for(const i of(this.agentControl=e,this.fetcher=t,this.credentials=r,this.agentControl.registerCompletionHandler(ni.SIGNING_ASSETS_SCAN_JOB_KIND,e=>this.completeScan(e)),[ni.SIGNING_PROFILE_READ_JOB_KIND,ni.SIGNING_PROFILE_INSTALL_JOB_KIND,ni.SIGNING_PROFILE_DELETE_JOB_KIND,ni.SIGNING_IDENTITY_IMPORT_JOB_KIND,ni.SIGNING_IDENTITY_DELETE_JOB_KIND]))this.agentControl.registerCompletionHandler(i,e=>this.completeOperation(e))}changed(){ie.agentEventBus.publish(ie.SIGNING_ASSETS_CHANGED_TOPIC,{changed:!0})}deleteTransferJobSoon(e){setTimeout(()=>{(0,t1.getPrismaClient)().then(t=>t.agentJob.deleteMany({where:{id:e,visibility:"SYSTEM"}}))},3e4).unref()}subscribe(){return ie.agentEventBus.iterate(ie.SIGNING_ASSETS_CHANGED_TOPIC)}async completeScan(e){if("SUCCEEDED"!==e.status)return;let t=(0,ni.parseSigningAssetsScanResult)(nn(e.resultJson)),r=await (0,t1.getPrismaClient)(),i=new Date;await r.$transaction(async r=>{for(let a of(await r.signingProfileAsset.updateMany({where:{agentId:e.agentId,missingAt:null},data:{missingAt:i}}),await r.signingCertificateAsset.updateMany({where:{agentId:e.agentId,missingAt:null},data:{missingAt:i}}),t.profiles))await r.signingProfileAsset.upsert({where:{agentId_uuid:{agentId:e.agentId,uuid:a.uuid}},create:{id:(0,b.randomUUID)(),agentId:e.agentId,uuid:a.uuid,contentHash:a.contentHash,name:a.name,profileType:a.profileType,bundleId:a.bundleId,teamId:a.teamId,teamName:a.teamName,platformsJson:JSON.stringify(a.platforms),deviceCount:a.deviceCount,deviceUdidsJson:JSON.stringify(a.deviceUdids),certificateSha1sJson:JSON.stringify(a.certificateSha1s),createdAt:ns(a.createdAt),expiresAt:ns(a.expiresAt),expired:a.expired,xcodeManaged:a.xcodeManaged,observedAt:i},update:{contentHash:a.contentHash,name:a.name,profileType:a.profileType,bundleId:a.bundleId,teamId:a.teamId,teamName:a.teamName,platformsJson:JSON.stringify(a.platforms),deviceCount:a.deviceCount,deviceUdidsJson:JSON.stringify(a.deviceUdids),certificateSha1sJson:JSON.stringify(a.certificateSha1s),createdAt:ns(a.createdAt),expiresAt:ns(a.expiresAt),expired:a.expired,xcodeManaged:a.xcodeManaged,observedAt:i,missingAt:null}});for(let a of t.certificates)await r.signingCertificateAsset.upsert({where:{agentId_sha1:{agentId:e.agentId,sha1:a.sha1}},create:{id:(0,b.randomUUID)(),agentId:e.agentId,sha1:a.sha1,sha256:a.sha256,name:a.name,teamId:a.teamId,certificateType:a.certificateType,notBefore:ns(a.notBefore),expiresAt:ns(a.expiresAt),expired:a.expired,hasPrivateKey:a.hasPrivateKey,observedAt:i},update:{sha256:a.sha256,name:a.name,teamId:a.teamId,certificateType:a.certificateType,notBefore:ns(a.notBefore),expiresAt:ns(a.expiresAt),expired:a.expired,hasPrivateKey:a.hasPrivateKey,observedAt:i,missingAt:null}})}),this.deleteTransferJobSoon(e.id),this.changed()}async refreshAfterMutation(e,t){await this.agentControl.createJob({agentId:e,kind:ni.SIGNING_ASSETS_SCAN_JOB_KIND,payload:{},idempotencyKey:`signing:${t}:${e}:refresh`,timeoutSeconds:60,visibility:"SYSTEM"})}async finishOperation(e){let t=await (0,t1.getPrismaClient)(),r=await t.signingOperationItem.findMany({where:{operationId:e}});if(r.some(e=>["WAITING","QUEUED","RUNNING"].includes(e.status)))return;let i=r.filter(e=>"SUCCEEDED"!==e.status);await t.signingOperation.update({where:{id:e},data:{status:i.length?"FAILED":"SUCCEEDED",error:i.map(e=>e.error).filter(Boolean).join("; ")||null,finishedAt:new Date}}),this.changed()}async completeOperation(e){let t=await (0,t1.getPrismaClient)(),r=await t.signingOperationItem.findUnique({where:{jobId:e.id},include:{operation:!0}});if(r){if(await t.signingOperationItem.update({where:{id:r.id},data:{status:e.status,error:e.error,finishedAt:new Date}}),e.kind===ni.SIGNING_PROFILE_READ_JOB_KIND&&"SUCCEEDED"===e.status&&"SYNC_PROFILE"===r.operation.kind){let i=nn(e.resultJson).contentBase64;if("string"==typeof i&&i)for(let e of(await t.signingOperationItem.findMany({where:{operationId:r.operationId,status:"WAITING"}}))){let a=await this.agentControl.createJob({agentId:e.agentId,kind:ni.SIGNING_PROFILE_INSTALL_JOB_KIND,payload:{contentBase64:i},idempotencyKey:`signing:${r.operationId}:${e.agentId}:install`,timeoutSeconds:60,visibility:"SYSTEM"});await t.signingOperationItem.update({where:{id:e.id},data:{jobId:a.id,status:a.status}})}else await t.signingOperation.update({where:{id:r.operationId},data:{status:"FAILED",error:"Profile read returned no content"}})}e.kind===ni.SIGNING_PROFILE_READ_JOB_KIND&&"SUCCEEDED"!==e.status&&"SYNC_PROFILE"===r.operation.kind&&await t.signingOperationItem.updateMany({where:{operationId:r.operationId,status:"WAITING"},data:{status:"FAILED",error:"Source profile could not be read",finishedAt:new Date}}),"SUCCEEDED"===e.status&&e.kind!==ni.SIGNING_PROFILE_READ_JOB_KIND&&await this.refreshAfterMutation(e.agentId,r.operationId),await this.finishOperation(r.operationId),this.deleteTransferJobSoon(e.id)}}async refresh(e){let t=await (0,t1.getPrismaClient)(),r=await t.agent.findMany({where:e?.length?{id:{in:[...new Set(e)]}}:void 0,orderBy:{name:"asc"}}),i=[];for(let e of r)no(e.capabilitiesJson).includes(ni.SIGNING_ASSETS_SCAN_JOB_KIND)&&i.push(await this.agentControl.createJob({agentId:e.id,kind:ni.SIGNING_ASSETS_SCAN_JOB_KIND,payload:{},idempotencyKey:`signing:scan:${Date.now()}:${e.id}`,timeoutSeconds:60,visibility:"SYSTEM"}));return i}async agents(){let e=await (0,t1.getPrismaClient)();return(await e.agent.findMany({orderBy:{name:"asc"}})).map(e=>({id:e.id,name:e.name,hostname:e.hostname,supported:no(e.capabilitiesJson).includes(ni.SIGNING_ASSETS_SCAN_JOB_KIND),lastSeenAt:e.lastSeenAt?.toISOString()??null}))}async profiles(){let e=await (0,t1.getPrismaClient)(),t=await e.signingProfileAsset.findMany({where:{missingAt:null},include:{agent:{select:{id:!0,name:!0}}},orderBy:[{expiresAt:"asc"},{name:"asc"}]}),r=new Map;for(let e of t){let t=`${e.uuid}:${e.contentHash}`;r.set(t,[...r.get(t)??[],e])}return[...r.values()].map(e=>{let t=e[0];return{id:`${t.uuid}:${t.contentHash}`,uuid:t.uuid,contentHash:t.contentHash,name:t.name,profileType:t.profileType,bundleId:t.bundleId,teamId:t.teamId,teamName:t.teamName,platforms:no(t.platformsJson),deviceCount:t.deviceCount,deviceUdids:no(t.deviceUdidsJson),certificateSha1s:no(t.certificateSha1sJson),createdAt:t.createdAt?.toISOString()??null,expiresAt:t.expiresAt?.toISOString()??null,expired:t.expired,xcodeManaged:t.xcodeManaged,installedAgents:e.map(({agent:e})=>e)}})}async profile(e){return(await this.profiles()).find(t=>t.id===e)??null}async profileDevices(e){let t=new Set,r=e.filter(e=>{let r=e.toUpperCase();return!t.has(r)&&(t.add(r),!0)}),i=r.map(e=>e.toUpperCase());if(!i.length)return[];let a=await (0,t1.getPrismaClient)(),n=new Map((await a.iosDevice.findMany({where:{udid:{in:i}},select:{id:!0,udid:!0,displayName:!0,product:!0,osVersion:!0,status:!0}})).map(e=>[e.udid.toUpperCase(),e]));return r.map(e=>{let t=n.get(e.toUpperCase());return{udid:e,deviceId:t?.id??null,displayName:t?.displayName??null,product:t?.product??null,osVersion:t?.osVersion??null,status:t?.status??null}})}async certificates(){let e=await (0,t1.getPrismaClient)(),t=await e.signingCertificateAsset.findMany({where:{missingAt:null},include:{agent:{select:{id:!0,name:!0}}},orderBy:[{expiresAt:"asc"},{name:"asc"}]}),r=new Map;for(let e of t)r.set(e.sha1,[...r.get(e.sha1)??[],e]);return[...r.values()].map(e=>{let t=e[0];return{id:t.sha1,sha1:t.sha1,sha256:t.sha256,name:t.name,teamId:t.teamId,certificateType:t.certificateType,notBefore:t.notBefore?.toISOString()??null,expiresAt:t.expiresAt?.toISOString()??null,expired:t.expired,hasPrivateKey:e.some(e=>e.hasPrivateKey),installedAgents:e.map(({agent:e})=>e),privateKeyAgents:e.filter(e=>e.hasPrivateKey).map(({agent:e})=>e)}})}async operations(e=50){return(await (0,t1.getPrismaClient)()).signingOperation.findMany({include:{items:{include:{agent:{select:{id:!0,name:!0}}},orderBy:{createdAt:"asc"}}},orderBy:{createdAt:"desc"},take:Math.max(1,Math.min(e,200))})}async operation(e,t,r,i=null,a=[]){let n=await (0,t1.getPrismaClient)(),s=(0,b.randomUUID)();return n.signingOperation.create({data:{id:s,kind:e,assetKey:t,sourceAgentId:i,items:{create:[...new Set(r)].map(e=>({id:(0,b.randomUUID)(),agentId:e,status:a.includes(e)?"WAITING":"QUEUED"}))}},include:{items:{include:{agent:{select:{id:!0,name:!0}}}}}})}async attachJob(e,t){let r=await (0,t1.getPrismaClient)();await r.signingOperationItem.update({where:{id:e},data:{jobId:t.id,status:t.status}})}async uploadProfile(e,t){if(!t.length)throw Error("Select at least one agent");let r=(0,b.createHash)("sha256").update(Buffer.from(e,"base64")).digest("hex").toUpperCase(),i=await this.operation("INSTALL_PROFILE",r,t);for(let t of i.items){let r=await this.agentControl.createJob({agentId:t.agentId,kind:ni.SIGNING_PROFILE_INSTALL_JOB_KIND,payload:{contentBase64:e},idempotencyKey:`signing:${i.id}:${t.agentId}:install`,timeoutSeconds:60,visibility:"SYSTEM"});await this.attachJob(t.id,r)}return this.changed(),i}async downloadProfile(e,t){let r=(0,b.randomUUID)(),i=await this.agentControl.createJob({agentId:t,kind:ni.SIGNING_PROFILE_READ_JOB_KIND,payload:{uuid:e},idempotencyKey:`signing:download:${r}:${e}`,timeoutSeconds:60,visibility:"SYSTEM"}),a=await (0,t1.getPrismaClient)();try{let t=Date.now()+55e3;for(;Date.now()<t;){let t=await this.agentControl.getJob(i.id);if(!t)throw Error("Profile download job was removed");if(["FAILED","CANCELLED","TIMED_OUT"].includes(t.status))throw Error(t.error||"Could not read provisioning profile");if("SUCCEEDED"===t.status){let r=nn(t.resultJson);if("string"!=typeof r.contentBase64)throw Error("Agent returned no provisioning profile content");return{uuid:e,filename:`${e}.mobileprovision`,contentBase64:r.contentBase64}}await new Promise(e=>setTimeout(e,250))}throw Error("Timed out reading provisioning profile")}finally{await a.agentJob.deleteMany({where:{id:i.id,visibility:"SYSTEM"}})}}async syncProfile(e,t,r){let i=[...new Set(r)].filter(e=>e!==t);if(!i.length)throw Error("Select at least one target agent");let a=await this.operation("SYNC_PROFILE",e,[t,...i],t,i),n=a.items.find(e=>e.agentId===t),s=await this.agentControl.createJob({agentId:t,kind:ni.SIGNING_PROFILE_READ_JOB_KIND,payload:{uuid:e},idempotencyKey:`signing:${a.id}:${t}:read`,timeoutSeconds:60,visibility:"SYSTEM"});return await this.attachJob(n.id,s),this.changed(),a}async deleteProfile(e,t){if(!t.length)throw Error("Select at least one agent");let r=await this.operation("DELETE_PROFILE",e,t);for(let t of r.items){let i=await this.agentControl.createJob({agentId:t.agentId,kind:ni.SIGNING_PROFILE_DELETE_JOB_KIND,payload:{uuid:e},idempotencyKey:`signing:${r.id}:${t.agentId}:delete`,timeoutSeconds:60,visibility:"SYSTEM"});await this.attachJob(t.id,i)}return this.changed(),r}async deleteExpiredProfiles(e){let t=await (0,t1.getPrismaClient)(),r=await t.signingProfileAsset.findMany({where:{expired:!0,missingAt:null,...e?.length?{agentId:{in:e}}:{}}}),i=new Map;for(let e of r)i.set(e.uuid,[...i.get(e.uuid)??[],e.agentId]);let a=[];for(let[e,t]of i)a.push(await this.deleteProfile(e,t));return a}async importIdentity(e){if(!e.targetAgentIds.length)throw Error("Select at least one agent");let t=Buffer.from(e.p12Base64,"base64");if(!t.length||t.length>0x1400000)throw Error("The .p12 file is empty or larger than 20 MiB");let r=[...new Set(e.targetAgentIds)],i=await (0,t1.getPrismaClient)(),n=new Map((await i.agent.findMany({where:{id:{in:r}},select:{id:!0,name:!0,capabilitiesJson:!0,lastSeenAt:!0,disconnectedAt:!0,heartbeatIntervalSeconds:!0}})).map(e=>[e.id,e])),s=Date.now(),o=r.filter(e=>{let t=n.get(e);return!t||!function(e,t=Date.now()){return null!==e.lastSeenAt&&t-e.lastSeenAt.getTime()<=(0,a.agentOnlineWindowMs)(e)&&null===e.disconnectedAt}(t,s)||!no(t.capabilitiesJson).includes(ni.SIGNING_IDENTITY_IMPORT_JOB_KIND)});if(o.length)throw Error(`Identity imports require online supported agents: ${o.map(e=>n.get(e)?.name??e).join(", ")}`);let l=(0,b.createHash)("sha256").update(t).digest("hex").toUpperCase(),c=await this.operation("IMPORT_IDENTITY",l,r);for(let t of c.items){let r=this.agentControl.createSigningSecretTransfer(t.agentId,{p12Base64:e.p12Base64,passphrase:e.passphrase});try{let e=await this.agentControl.createJob({agentId:t.agentId,kind:ni.SIGNING_IDENTITY_IMPORT_JOB_KIND,payload:{transferId:r,sha256:l},idempotencyKey:`signing:${c.id}:${t.agentId}:import`,timeoutSeconds:120,visibility:"SYSTEM"});await this.attachJob(t.id,e)}catch(e){throw this.agentControl.revokeSigningSecretTransfer(r),e}}return this.changed(),c}async deleteIdentity(e,t){if(!t.length)throw Error("Select at least one agent");let r=e.toUpperCase(),i=[...new Set(t)],a=await (0,t1.getPrismaClient)(),n=new Set((await a.signingCertificateAsset.findMany({where:{sha1:r,agentId:{in:i},hasPrivateKey:!0,missingAt:null},select:{agentId:!0}})).map(e=>e.agentId)),s=i.filter(e=>n.has(e));if(!s.length)throw Error("The identity has no private key on the selected agents");let o=await this.operation("DELETE_IDENTITY",r,s);for(let e of o.items){let t=await this.agentControl.createJob({agentId:e.agentId,kind:ni.SIGNING_IDENTITY_DELETE_JOB_KIND,payload:{sha1:r},idempotencyKey:`signing:${o.id}:${e.agentId}:delete`,timeoutSeconds:60,visibility:"SYSTEM"});await this.attachJob(e.id,t)}return this.changed(),o}async appleClient(){return new na.AppleDeveloperClient(await (0,na.storedAppleDeveloperCredentials)(this.credentials),this.fetcher)}async portalInventory(){let e=await this.appleClient(),[t,r,i,a]=await Promise.all([e.listProfiles(),e.listCertificates(),e.listBundleIds(),e.listDevices()]);return{profiles:t,certificates:r,bundleIds:i,devices:a}}async createPortalProfile(e){let t=await (await this.appleClient()).createProfile(e);return this.changed(),t.data}async deletePortalProfile(e){return await (await this.appleClient()).deleteProfile(e),this.changed(),!0}async revokePortalCertificate(e){return await (await this.appleClient()).revokeCertificate(e),this.changed(),!0}}var nc=e.i(308810),nu=e.i(783396),nd=e.i(247287),np=e.i(726355);let nh=/^[A-Za-z0-9][A-Za-z0-9.-]{0,254}$/;function nm(e,t,r){if("string"!=typeof e||!e.trim())throw Error(`${t} is required`);let i=e.trim();if(i.length>r||i.includes("\0"))throw Error(`${t} is invalid`);return i}function nf(e,t,r){return null==e||""===e?null:nm(e,t,r)}let ng={IOS_BUILD_SUCCEEDED:{key:"IOS_BUILD_SUCCEEDED",category:"BUILDS",label:"iOS build succeeded",description:"An iOS build finishes successfully.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1,defaultApnsEnabled:!0},IOS_BUILD_FAILED:{key:"IOS_BUILD_FAILED",category:"BUILDS",label:"iOS build failed",description:"An iOS build finishes with a failure.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1,defaultApnsEnabled:!0},COMMAND_RUN_SUCCEEDED:{key:"COMMAND_RUN_SUCCEEDED",category:"COMMANDS",label:"Command run succeeded",description:"A saved command finishes successfully.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1,defaultApnsEnabled:!0},COMMAND_RUN_FAILED:{key:"COMMAND_RUN_FAILED",category:"COMMANDS",label:"Command run failed",description:"A saved command finishes with a failure.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1,defaultApnsEnabled:!0},GITHUB_ACTIONS_SUCCEEDED:{key:"GITHUB_ACTIONS_SUCCEEDED",category:"GITHUB",label:"GitHub Actions succeeded",description:"A GitHub Actions workflow finishes successfully.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1,defaultApnsEnabled:!0},GITHUB_ACTIONS_FAILED:{key:"GITHUB_ACTIONS_FAILED",category:"GITHUB",label:"GitHub Actions failed",description:"A GitHub Actions workflow finishes with a failure.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1,defaultApnsEnabled:!0},GITLAB_PIPELINE_SUCCEEDED:{key:"GITLAB_PIPELINE_SUCCEEDED",category:"GITLAB",label:"GitLab pipeline succeeded",description:"A GitLab CI/CD pipeline finishes successfully.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1,defaultApnsEnabled:!0},GITLAB_PIPELINE_FAILED:{key:"GITLAB_PIPELINE_FAILED",category:"GITLAB",label:"GitLab pipeline failed",description:"A GitLab CI/CD pipeline finishes with a failure.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1,defaultApnsEnabled:!0},GITLAB_REVIEW_REQUESTED:{key:"GITLAB_REVIEW_REQUESTED",category:"GITLAB",label:"GitLab review requested",description:"A GitLab merge request requests a review.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1,defaultApnsEnabled:!0},RUN_NEEDS_ANSWER:{key:"RUN_NEEDS_ANSWER",category:"RUNS",label:"Plan or session needs an answer",description:"A managed plan or session asks for user input.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1,defaultApnsEnabled:!0},RUN_COMPLETED:{key:"RUN_COMPLETED",category:"RUNS",label:"Plan or session completed",description:"A managed plan or session completes successfully.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1,defaultApnsEnabled:!0},RUN_FAILED:{key:"RUN_FAILED",category:"RUNS",label:"Plan or session failed",description:"A managed plan or session fails.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1,defaultApnsEnabled:!0},RUN_CANCELLED:{key:"RUN_CANCELLED",category:"RUNS",label:"Plan or session cancelled",description:"A managed plan or session is cancelled.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!1,defaultWebPushEnabled:!1,defaultApnsEnabled:!1},RUN_RECOVERY_PAUSED:{key:"RUN_RECOVERY_PAUSED",category:"RUNS",label:"Plan or session paused after recovery",description:"A managed plan or session is paused after its agent restarts.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1,defaultApnsEnabled:!0},WORKFLOW_MESSAGE:{key:"WORKFLOW_MESSAGE",category:"WORKFLOWS",label:"Workflow message",description:"A workflow sends a generic notification.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1,defaultApnsEnabled:!0},WORKFLOW_NEEDS_ATTENTION:{key:"WORKFLOW_NEEDS_ATTENTION",category:"WORKFLOWS",label:"Workflow needs attention",description:"A workflow is waiting for data or a decision.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1,defaultApnsEnabled:!0},WORKFLOW_COMPLETED:{key:"WORKFLOW_COMPLETED",category:"WORKFLOWS",label:"Workflow completed",description:"A workflow run completes successfully.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1,defaultApnsEnabled:!0},WORKFLOW_FAILED:{key:"WORKFLOW_FAILED",category:"WORKFLOWS",label:"Workflow failed",description:"A workflow run fails.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1,defaultApnsEnabled:!0},WORKFLOW_RECOVERY_PAUSED:{key:"WORKFLOW_RECOVERY_PAUSED",category:"WORKFLOWS",label:"Workflow paused after recovery",description:"A workflow pauses while recovering durable work.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1,defaultApnsEnabled:!0}};function ny(e){return e in ng?ng[e]:null}let nw="default",nb=new Set(["BadDeviceToken","DeviceTokenNotForTopic","Unregistered"]);function nv(e,t,r){let i=e.trim();if(!i)throw Error(`${t} is required`);if(i.length>r)throw Error(`${t} is too long`);return i}function nk(e){let t,r=nv(e,"Push endpoint",4e3);try{t=new URL(r)}catch{throw Error("Push endpoint must be a valid URL")}if("https:"!==t.protocol)throw Error("Push endpoint must use HTTPS");return r}function nE(e,t){let r=new Date(e);if(!Number.isFinite(r.getTime()))throw Error(`${t} is invalid`);return r}function nS(){let e=process.env.PUBLIC_BASE_URL?.trim();if(e)try{let t=new URL(e);if("https:"===t.protocol)return t.origin}catch{}return"mailto:notifications@ai-development-environment.local"}function nI(e){if(!e||"object"!=typeof e)return null;let t=e.statusCode;return"number"==typeof t?t:null}function nA(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function nx(e,t,r){if(4096>=nA(r(e)))return e;let i=Array.from(e),a=e=>0===e?"":`${i.slice(0,e).join("")}${t}`,n=0,s=i.length-1;for(;n<s;){let e=Math.ceil((n+s)/2);4096>=nA(r(a(e)))?n=e:s=e-1}return a(n)}class n_{credentialService;apns;vapidPreparation;constructor(e,t=new nd.ApnsClient){this.credentialService=e,this.apns=t,this.vapidPreparation=null}publish(e){ie.agentEventBus.publish(ie.APP_NOTIFICATIONS_CHANGED_TOPIC,{notificationsChanged:e})}subscribe(){return ie.agentEventBus.iterate(ie.APP_NOTIFICATIONS_CHANGED_TOPIC)}async preferences(){let e=await (0,t1.getPrismaClient)(),t=new Map((await e.notificationPreference.findMany()).map(e=>[e.typeKey,e]));return Object.values(ng).map(e=>{let r=t.get(e.key);return{...e,sidebarEnabled:r?.sidebarEnabled??e.defaultSidebarEnabled,browserEnabled:r?.browserEnabled??e.defaultBrowserEnabled,webPushEnabled:r?.webPushEnabled??e.defaultWebPushEnabled,apnsEnabled:r?.apnsEnabled??e.defaultApnsEnabled,updatedAt:r?.updatedAt??null}})}async savePreference(e){let t=ny(e.typeKey);if(!t)throw Error("Unknown notification type");let r=await (0,t1.getPrismaClient)(),i=await r.notificationPreference.findUnique({where:{typeKey:t.key}}),a=e.apnsEnabled??i?.apnsEnabled??t.defaultApnsEnabled,n=await r.notificationPreference.upsert({where:{typeKey:t.key},create:{typeKey:t.key,sidebarEnabled:e.sidebarEnabled,browserEnabled:e.browserEnabled,webPushEnabled:e.webPushEnabled,apnsEnabled:a},update:{sidebarEnabled:e.sidebarEnabled,browserEnabled:e.browserEnabled,webPushEnabled:e.webPushEnabled,apnsEnabled:a}});return this.publish({kind:"PREFERENCES_UPDATED",notification:null,notificationId:null}),{...t,...n}}async recordInTransaction(e,t){let r=ny(t.typeKey);if(!r)throw Error("Unknown notification type");let i=await e.notificationPreference.findUnique({where:{typeKey:r.key}}),a=i?.sidebarEnabled??r.defaultSidebarEnabled,n=i?.browserEnabled??r.defaultBrowserEnabled,s=i?.webPushEnabled??r.defaultWebPushEnabled,o=i?.apnsEnabled??r.defaultApnsEnabled;if(!a&&!n&&!s&&!o)return null;let l=nv(t.dedupeKey,"Deduplication key",500);return await e.appNotification.findUnique({where:{dedupeKey:l}})?null:e.appNotification.create({data:{id:(0,b.randomUUID)(),dedupeKey:l,typeKey:r.key,title:nv(t.title,"Notification title",240),body:nv(t.body,"Notification body",1e3),href:function(e){let t=nv(e,"Notification link",2e3);if(!t.startsWith("/")||t.startsWith("//"))throw Error("Notification links must be same-origin paths");return t}(t.href),resourceKind:nv(t.resourceKind,"Resource kind",100),resourceId:nv(t.resourceId,"Resource ID",500),worktreeId:t.worktreeId??null,highlightColor:t.highlightColor?.trim()||null,sidebarRequested:a,browserRequested:n,webPushRequested:s,apnsRequested:o}})}created(e){e&&(this.publish({kind:"CREATED",notification:e,notificationId:e.id}),e.webPushRequested&&this.deliverWebPush(e).catch(e=>{console.error("Web Push delivery failed:",e)}),e.apnsRequested&&this.deliverApns(e).catch(e=>{console.error("APNs delivery failed:",e)}))}async history(e={}){let t=Math.max(1,Math.min(e.first??100,200)),r=await (0,t1.getPrismaClient)(),[i,a]=await Promise.all([r.appNotification.findMany({orderBy:[{createdAt:"desc"},{id:"desc"}],take:t+1,...e.after?{cursor:{id:e.after},skip:1}:void 0}),r.appNotification.count()]);return{items:i.slice(0,t),nextCursor:i.length>t?i[t-1].id:null,totalCount:a}}async sidebar(e=50){return(await (0,t1.getPrismaClient)()).appNotification.findMany({where:{sidebarRequested:!0,sidebarDismissedAt:null},orderBy:[{createdAt:"desc"},{id:"desc"}],take:Math.max(1,Math.min(e,100))})}async dismiss(e){let t=await (0,t1.getPrismaClient)(),r=await t.appNotification.updateMany({where:{id:e,sidebarRequested:!0,sidebarDismissedAt:null},data:{sidebarDismissedAt:new Date}});return r.count&&this.publish({kind:"DISMISSED",notification:null,notificationId:e}),r.count>0}async dismissAll(){let e=await (0,t1.getPrismaClient)(),t=await e.appNotification.updateMany({where:{sidebarRequested:!0,sidebarDismissedAt:null},data:{sidebarDismissedAt:new Date}});return t.count&&this.publish({kind:"SIDEBAR_CLEARED",notification:null,notificationId:null}),t.count}selectionWhere(e){let t=e.excludedRanges??[],r=e.all&&0===t.length?[]:[...new Set(e.ids??[])],i=[...new Set(e.excludedIds??[])],a=e.ranges??[];if(r.length>5e3||i.length>5e3)throw Error("Notification selection is too large");if(a.length>366||t.length>366)throw Error("Notification date selection is too large");let n=t.map(e=>{let t=nE(e.start,"Excluded selection start"),r=nE(e.end,"Excluded selection end");if(t>=r)throw Error("Excluded selection range is invalid");return{createdAt:{gte:t,lt:r}}}),s={NOT:{OR:n}},o=[];if(r.length&&o.push({id:{in:r}}),e.all)o.push(n.length?s:{});else if(a.length){let e=a.map(e=>{let t=nE(e.start,"Selection start"),r=nE(e.end,"Selection end");if(t>=r)throw Error("Selection range is invalid");return{createdAt:{gte:t,lt:r}}});o.push({AND:[{OR:e},...n.length?[s]:[]]})}if(!o.length)return{id:{in:[]}};let l=1===o.length?o[0]:{OR:o};return i.length?{AND:[l,{id:{notIn:i}}]}:l}async deleteSelection(e){let t=await (0,t1.getPrismaClient)(),r=await t.appNotification.deleteMany({where:this.selectionWhere(e)});return r.count&&this.publish({kind:"DELETED",notification:null,notificationId:null}),r.count}async deleteAll(){let e=await (0,t1.getPrismaClient)(),t=await e.appNotification.deleteMany();return t.count&&this.publish({kind:"HISTORY_CLEARED",notification:null,notificationId:null}),t.count}async webPushState(){let e=await (0,t1.getPrismaClient)(),[t,r]=await Promise.all([e.webPushSettings.findUnique({where:{id:nw}}),e.webPushSubscription.count()]),i=await this.credentialService.isConfigured(t2.CREDENTIALS.webPushVapidPrivateKey);return{configured:!!(t?.vapidPublicKey&&i),publicKey:t?.vapidPublicKey??null,subscriptionCount:r}}async webPushSubscriptions(){return(await (0,t1.getPrismaClient)()).webPushSubscription.findMany({orderBy:[{lastSeenAt:"desc"},{createdAt:"desc"}],select:{id:!0,endpoint:!0,expirationTime:!0,locale:!0,userAgent:!0,lastSeenAt:!0,createdAt:!0,updatedAt:!0}})}async prepareWebPush(){return this.vapidPreparation||(this.vapidPreparation=this.prepareWebPushOnce().finally(()=>{this.vapidPreparation=null})),this.vapidPreparation}async prepareWebPushOnce(){let e=await (0,t1.getPrismaClient)(),t=await e.webPushSettings.findUnique({where:{id:nw}});if(t?.vapidPublicKey){if(!await this.credentialService.getText(t2.CREDENTIALS.webPushVapidPrivateKey))throw Error("The Web Push private key is unavailable");return{publicKey:t.vapidPublicKey}}let r=np.default.generateVAPIDKeys();return await this.credentialService.setText(t2.CREDENTIALS.webPushVapidPrivateKey,r.privateKey,e=>e.webPushSettings.upsert({where:{id:nw},create:{id:nw,vapidPublicKey:r.publicKey,vapidGeneratedAt:new Date},update:{vapidPublicKey:r.publicKey,vapidGeneratedAt:new Date}}).then(()=>void 0)),{publicKey:r.publicKey}}async registerWebPush(e){let t=nk(e.endpoint),r=nv(e.p256dh,"Push p256dh key",1e3),i=nv(e.auth,"Push auth key",1e3),a=null===e.expirationTime||void 0===e.expirationTime?null:new Date(e.expirationTime);if(a&&!Number.isFinite(a.getTime()))throw Error("Push subscription expiration is invalid");return await this.prepareWebPush(),(await (0,t1.getPrismaClient)()).webPushSubscription.upsert({where:{endpoint:t},create:{id:(0,b.randomUUID)(),endpoint:t,p256dh:r,auth:i,expirationTime:a,locale:e.locale?.trim().slice(0,35)||null,userAgent:e.userAgent?.trim().slice(0,1e3)||null},update:{p256dh:r,auth:i,expirationTime:a,locale:e.locale?.trim().slice(0,35)||null,userAgent:e.userAgent?.trim().slice(0,1e3)||null,lastSeenAt:new Date}})}async unregisterWebPush(e){let t=nk(e),r=await (0,t1.getPrismaClient)();return(await r.webPushSubscription.deleteMany({where:{endpoint:t}})).count>0}async deleteWebPushSubscription(e){let t=nv(e,"Push subscription",200),r=await (0,t1.getPrismaClient)();return(await r.webPushSubscription.deleteMany({where:{id:t}})).count>0}async testWebPushSubscription(e){let t=nv(e,"Push subscription",200),r=await (0,t1.getPrismaClient)(),[i,a]=await Promise.all([r.webPushSettings.findUnique({where:{id:nw}}),r.webPushSubscription.findUnique({where:{id:t}})]);if(!a)throw Error("Push subscription was not found");if(!i?.vapidPublicKey)throw Error("Web Push is not configured");let n=await this.credentialService.getText(t2.CREDENTIALS.webPushVapidPrivateKey);if(!n)throw Error("The Web Push private key is unavailable");np.default.setVapidDetails(nS(),i.vapidPublicKey,n);try{return await np.default.sendNotification({endpoint:a.endpoint,expirationTime:a.expirationTime?.getTime()??null,keys:{p256dh:a.p256dh,auth:a.auth}},JSON.stringify({id:`test:${Date.now()}`,title:"Test notification",body:"Web Push is working for this browser.",href:"/notifications",icon:"/icon-192.png",badge:"/icon-192.png"}),{TTL:60,timeout:1e4}),!0}catch(e){if([404,410].includes(nI(e)??0))throw await r.webPushSubscription.deleteMany({where:{id:t}}),Error("The browser subscription expired and was removed");throw e}}async apnsState(){let e=await (0,t1.getPrismaClient)(),[t,r]=await Promise.all([(0,nu.readConnectionSettings)(this.credentialService,t2.CREDENTIALS.apnsTokenSettings,nu.apnsTokenConnectionSettings),e.notificationDevice.count({where:{status:"ACTIVE"}})]),i=await this.credentialService.isConfigured(t2.CREDENTIALS.apnsTokenPrivateKey);return{configured:!!(t&&i),deviceCount:r}}async notificationDevices(){let e=await (0,t1.getPrismaClient)();return(await e.notificationDevice.findMany({orderBy:[{status:"asc"},{lastRegisteredAt:"desc"}]})).map(({token:e,tokenHash:t,...r})=>({...r,tokenMasked:`${e.slice(0,8)}…${e.slice(-8)}`}))}async registerDevice(e,t){let r=function(e){let t=function(e,t){if(!e||"object"!=typeof e||Array.isArray(e))throw Error(`${t} must be an object`);return e}(e,"device"),r=new Set(["clientRegistrationId","token","tokenEncoding","topic","environment","displayName","deviceModel","osVersion","appVersion","appBuild","locale"]),i=Object.keys(t).filter(e=>!r.has(e));if(i.length)throw Error(`device has unsupported fields: ${i.join(", ")}`);let a=t.tokenEncoding??"HEX";if("HEX"!==a&&"BASE64"!==a)throw Error("tokenEncoding must be HEX or BASE64");let n=t.environment;if("SANDBOX"!==n&&"PRODUCTION"!==n)throw Error("environment must be SANDBOX or PRODUCTION");let s=nm(t.topic,"topic",255);if(!nh.test(s))throw Error("topic is invalid");return{clientRegistrationId:nm(t.clientRegistrationId,"clientRegistrationId",200),token:(0,rN.normalizeDeviceToken)(nm(t.token,"token",500),a),topic:s,environment:n,displayName:nm(t.displayName,"displayName",120),deviceModel:nf(t.deviceModel,"deviceModel",120),osVersion:nf(t.osVersion,"osVersion",60),appVersion:nf(t.appVersion,"appVersion",60),appBuild:nf(t.appBuild,"appBuild",60),locale:nf(t.locale,"locale",35)}}(e);return this.registerDeviceValidated(r,t)}async registerDeviceValidated(e,t){let r=await (0,t1.getPrismaClient)(),i=(0,b.createHash)("sha256").update(e.token).digest("hex"),a=new Date,n={token:e.token,tokenHash:i,topic:e.topic,environment:e.environment,displayName:e.displayName,deviceModel:e.deviceModel,osVersion:e.osVersion,appVersion:e.appVersion,appBuild:e.appBuild,locale:e.locale,lastIpAddress:t,status:"ACTIVE",lastFailureReason:null,lastFailureAt:null,lastRegisteredAt:a},s=await r.$transaction(async t=>{let r=await t.notificationDevice.findUnique({where:{clientRegistrationId:e.clientRegistrationId}}),a=await t.notificationDevice.findUnique({where:{tokenHash:i}});return a&&a.id!==r?.id&&await t.notificationDevice.delete({where:{id:a.id}}),{device:r?await t.notificationDevice.update({where:{id:r.id},data:n}):await t.notificationDevice.create({data:{id:(0,b.randomUUID)(),clientRegistrationId:e.clientRegistrationId,...n}}),created:!r}});return this.publish({kind:"DEVICES_CHANGED",notification:null,notificationId:null}),s}async deleteNotificationDevice(e){let t=nv(e,"Notification device",200),r=await (0,t1.getPrismaClient)(),i=await r.notificationDevice.deleteMany({where:{id:t}});return i.count&&this.publish({kind:"DEVICES_CHANGED",notification:null,notificationId:null}),i.count>0}async renameNotificationDevice(e,t){let r=nv(e,"Notification device",200),i=nv(t,"Display name",120),a=await (0,t1.getPrismaClient)(),n=await a.notificationDevice.update({where:{id:r},data:{displayName:i}});return this.publish({kind:"DEVICES_CHANGED",notification:null,notificationId:null}),n}async apnsAuthentication(){let e=await (0,nu.readConnectionSettings)(this.credentialService,t2.CREDENTIALS.apnsTokenSettings,nu.apnsTokenConnectionSettings),t=await this.credentialService.getText(t2.CREDENTIALS.apnsTokenPrivateKey);if(!e||!t)throw Error("APNs token authentication is not configured. Add the team ID, key ID, and .p8 key under Settings.");return{kind:"TOKEN",teamId:e.value.teamId,keyId:e.value.keyId,privateKey:t}}async sendApns(e,t,r){let i,a=await (0,t1.getPrismaClient)(),n=new Date;try{i=await this.apns.send({environment:e.environment,authentication:t,deviceToken:e.token,payload:function(e){let t=e.title,r=e.body,i=e.href,a=(a=t,n=r,s=i)=>({aps:{alert:{title:a,body:n},sound:"default","thread-id":e.typeKey,"interruption-level":"active"},notificationId:e.id,typeKey:e.typeKey,href:s});r=nx(r,"…",e=>a(t,e,i)),i=nx(i,"",e=>a(t,r,e)),t=nx(t,"…",e=>a(e,r,i));let n=a();if(nA(n)>4096)throw Error("APNs payload exceeds the 4096-byte alert limit");return n}(r),headers:{"apns-topic":e.topic,"apns-push-type":"alert","apns-priority":"10","apns-expiration":String(Math.floor(n.getTime()/1e3)+3600),...r.collapseId?{"apns-collapse-id":r.collapseId.slice(0,64)}:{}}})}catch(t){throw await a.notificationDevice.updateMany({where:{id:e.id,token:e.token},data:{lastFailureReason:t instanceof Error?t.message.slice(0,200):"SendFailed",lastFailureAt:n}}),t}if(200===i.status)return await a.notificationDevice.updateMany({where:{id:e.id,token:e.token},data:{lastDeliveredAt:n,lastFailureReason:null,lastFailureAt:null}}),!0;let s=i.reason??`HTTP ${i.status}`,o=410===i.status||nb.has(s),l=await a.notificationDevice.updateMany({where:{id:e.id,token:e.token},data:{lastFailureReason:s,lastFailureAt:n,...o?{status:"INACTIVE"}:{}}});return o&&l.count>0&&this.publish({kind:"DEVICES_CHANGED",notification:null,notificationId:null}),!1}async testNotificationDevice(e){let t=nv(e,"Notification device",200),r=await (0,t1.getPrismaClient)(),i=await r.notificationDevice.findUnique({where:{id:t}});if(!i)throw Error("Notification device was not found");let a=await this.apnsAuthentication();if(!await this.sendApns(i,a,{id:`test:${Date.now()}`,title:"Test notification",body:"Native notifications are working on this device.",href:"/notifications",typeKey:"TEST"})){let e=await r.notificationDevice.findUnique({where:{id:t}});throw Error(e?.lastFailureReason?`APNs rejected the notification: ${e.lastFailureReason}`:"APNs rejected the notification")}return!0}async deliverApns(e){let t;if(!e.apnsRequested)return;let r=await (0,t1.getPrismaClient)(),i=await r.notificationDevice.findMany({where:{status:"ACTIVE"}});if(i.length){try{t=await this.apnsAuthentication()}catch(e){console.error("APNs delivery skipped:",e);return}await Promise.allSettled(i.map(async r=>{try{await this.sendApns(r,t,{id:e.id,title:e.title,body:e.body,href:e.href,typeKey:e.typeKey,collapseId:e.dedupeKey})}catch(e){console.error(`APNs delivery to ${r.displayName} failed:`,e)}}))}}async deliverWebPush(e){if(!e.webPushRequested)return;let t=await (0,t1.getPrismaClient)(),[r,i]=await Promise.all([t.webPushSettings.findUnique({where:{id:nw}}),t.webPushSubscription.findMany()]);if(!r?.vapidPublicKey||!i.length)return;let a=await this.credentialService.getText(t2.CREDENTIALS.webPushVapidPrivateKey);if(!a)return;np.default.setVapidDetails(nS(),r.vapidPublicKey,a);let n=JSON.stringify({id:e.id,title:e.title,body:e.body,href:e.href,icon:"/icon-192.png",badge:"/icon-192.png"});await Promise.allSettled(i.map(async e=>{try{await np.default.sendNotification({endpoint:e.endpoint,expirationTime:e.expirationTime?.getTime()??null,keys:{p256dh:e.p256dh,auth:e.auth}},n,{TTL:3600,timeout:1e4})}catch(r){if([404,410].includes(nI(r)??0))return void await t.webPushSubscription.deleteMany({where:{endpoint:e.endpoint}});console.error(`Web Push delivery to ${e.endpoint} failed:`,r)}}))}}var nC=e.i(986847);let nR=e=>e?.toISOString()??null;function nT(e,t,r,i,a){return e?t?"RUNNING":a?"ERROR":r&&!i||r&&i&&Date.now()-i.getTime()>2e3*r+5e3?"STALE":"HEALTHY":"DISABLED"}class nD{operations=new Map;register(e){let t=this.operations.get(e.id);this.operations.set(e.id,{...e,lastStartedAt:t?.lastStartedAt??null,lastCompletedAt:t?.lastCompletedAt??null,lastSucceededAt:t?.lastSucceededAt??null,nextScheduledAt:t?.nextScheduledAt??null,durationMs:t?.durationMs??null,lastError:t?.lastError??null}),this.changed(e.id)}configure(e,t){let r=this.operations.get(e);r&&(Object.assign(r,t),r.enabled||(r.nextScheduledAt=null),this.changed(e))}schedule(e,t){let r=this.operations.get(e);r&&(r.nextScheduledAt=t,this.changed(e))}async run(e,t,r){let i=this.operations.get(e);if(!i)throw Error(`Polling operation ${e} is not registered`);let a=new Date;i.lastStartedAt=a,i.lastError=null,this.changed(e);try{let e=await t(),n=new Date;return i.lastCompletedAt=n,i.lastSucceededAt=n,i.durationMs=n.getTime()-a.getTime(),i.lastError=null,r&&(i.details={...i.details,...r(e)}),e}catch(t){let e=new Date;throw i.lastCompletedAt=e,i.durationMs=e.getTime()-a.getTime(),i.lastError=t instanceof Error?t.message:String(t),t}finally{this.changed(e)}}changed(e){ie.agentEventBus.publish(ie.POLLING_CHANGED_TOPIC,{pollingOperationChanged:e})}subscribe(){return ie.agentEventBus.iterate(ie.POLLING_CHANGED_TOPIC)}serverViews(){return[...this.operations.values()].map(e=>({...e,status:nT(e.enabled,!!(e.lastStartedAt&&(!e.lastCompletedAt||e.lastStartedAt>e.lastCompletedAt)),e.cadenceSeconds,e.lastCompletedAt,e.lastError),lastStartedAt:nR(e.lastStartedAt),lastCompletedAt:nR(e.lastCompletedAt),lastSucceededAt:nR(e.lastSucceededAt),nextScheduledAt:nR(e.nextScheduledAt)}))}async list(){let e=await (0,t1.getPrismaClient)(),[t,r,i]=await Promise.all([e.codebaseSettings.findUnique({where:{id:"default"}}),e.agent.findMany({orderBy:{name:"asc"},select:{id:!0,name:!0,lastSeenAt:!0,disconnectedAt:!0,codebaseScanIntervalSeconds:!0,jobReconciliationIntervalSeconds:!0,gitFetchIntervalSeconds:!0,heartbeatIntervalSeconds:!0,codebases:{select:{lastCheckedAt:!0,lastFetchedAt:!0,lastFetchAttemptAt:!0,lastFetchError:!0}},diskSpaceState:{select:{enabled:!0,lastReportedAt:!0,lastError:!0,volumesJson:!0}}}}),e.agentJob.groupBy({by:["agentId","status"],where:{status:{in:["QUEUED","RUNNING"]}},_count:{_all:!0}})]),n=t?.refreshIntervalSeconds??30,s=t?.fetchIntervalSeconds??300,o=new Map;for(let e of i)o.set(e.agentId,(o.get(e.agentId)??0)+e._count._all);let l=[];for(let e of r){let t=e.heartbeatIntervalSeconds??nC.DEFAULT_AGENT_HEARTBEAT_INTERVAL_SECONDS,r=e.jobReconciliationIntervalSeconds??nC.DEFAULT_AGENT_JOB_RECONCILIATION_INTERVAL_SECONDS,i=e.codebaseScanIntervalSeconds??n,c=e.gitFetchIntervalSeconds??s,u=null!==e.lastSeenAt&&null===e.disconnectedAt&&Date.now()-e.lastSeenAt.getTime()<=(0,a.agentOnlineWindowMs)(e);l.push({id:`agent-heartbeat:${e.id}`,kind:"AGENT_HEARTBEAT",runtime:"AGENT",status:u?"HEALTHY":"STALE",enabled:!0,cadenceSeconds:t,lastStartedAt:null,lastCompletedAt:nR(e.lastSeenAt),lastSucceededAt:nR(e.lastSeenAt),nextScheduledAt:e.lastSeenAt?new Date(e.lastSeenAt.getTime()+1e3*t).toISOString():null,durationMs:null,lastError:null,details:{agentId:e.id,agentName:e.name,connection:u?"ONLINE":"OFFLINE"}});let d=e.diskSpaceState,p=d?.enabled??!0,h=d?.lastReportedAt??null,m=0;try{let e=JSON.parse(d?.volumesJson??"[]");m=Array.isArray(e)?e.length:0}catch{m=0}l.push({id:`agent-disk-space:${e.id}`,kind:"AGENT_DISK_SPACE",runtime:"AGENT",status:p?nT(!0,!1,r7.DISK_SPACE_POLL_INTERVAL_SECONDS,h,d?.lastError??null):"DISABLED",enabled:p,cadenceSeconds:r7.DISK_SPACE_POLL_INTERVAL_SECONDS,lastStartedAt:null,lastCompletedAt:nR(h),lastSucceededAt:d?.lastError?null:nR(h),nextScheduledAt:p&&h?new Date(h.getTime()+1e3*r7.DISK_SPACE_POLL_INTERVAL_SECONDS).toISOString():null,durationMs:null,lastError:d?.lastError??null,details:{agentId:e.id,agentName:e.name,volumes:m}}),l.push({id:`agent-job-reconciliation:${e.id}`,kind:"AGENT_JOB_RECONCILIATION",runtime:"AGENT",status:u?"HEALTHY":"STALE",enabled:!0,cadenceSeconds:r,lastStartedAt:null,lastCompletedAt:nR(e.lastSeenAt),lastSucceededAt:nR(e.lastSeenAt),nextScheduledAt:e.lastSeenAt?new Date(e.lastSeenAt.getTime()+1e3*r).toISOString():null,durationMs:null,lastError:null,details:{agentId:e.id,agentName:e.name,pendingJobs:o.get(e.id)??0}});let f=e.codebases.map(e=>e.lastCheckedAt).filter(e=>null!==e).sort((e,t)=>t.getTime()-e.getTime())[0]??null,g=e.codebases.map(e=>e.lastFetchAttemptAt??e.lastFetchedAt).filter(e=>null!==e).sort((e,t)=>t.getTime()-e.getTime())[0]??null,y=e.codebases.filter(e=>e.lastFetchError).length;l.push({id:`agent-codebase-scan:${e.id}`,kind:"CODEBASE_SCAN",runtime:"AGENT",status:nT(e.codebases.length>0,!1,i,f,null),enabled:e.codebases.length>0,cadenceSeconds:i,lastStartedAt:null,lastCompletedAt:nR(f),lastSucceededAt:nR(f),nextScheduledAt:f?new Date(f.getTime()+1e3*i).toISOString():null,durationMs:null,lastError:null,details:{agentId:e.id,agentName:e.name,repositories:e.codebases.length}}),l.push({id:`agent-git-fetch:${e.id}`,kind:"GIT_FETCH",runtime:"AGENT",status:y>0?"ERROR":nT(e.codebases.length>0,!1,c,g,null),enabled:e.codebases.length>0,cadenceSeconds:c,lastStartedAt:null,lastCompletedAt:nR(g),lastSucceededAt:y>0?null:nR(g),nextScheduledAt:g?new Date(g.getTime()+1e3*c).toISOString():null,durationMs:null,lastError:y>0?`${y} repositories have fetch errors`:null,details:{agentId:e.id,agentName:e.name,repositories:e.codebases.length,fetchErrors:y}})}return[...this.serverViews(),...l]}}let nN="default",nO="https://raw.githubusercontent.com/BerriAI/litellm/refs/heads/main/model_prices_and_context_window.json",nP=new Set(["sample_spec"]);function nL(e){return"number"==typeof e&&Number.isFinite(e)?e:null}function nB(e){let t=nL(e);return null===t?null:Math.trunc(t)}function nU(e){return"string"==typeof e&&e.trim()?e.trim():null}function nj(e){let t=e.lastIndexOf("/");return t<0?e:e.slice(t+1)}let nM={MODEL:"model",PROVIDER:"provider",INPUT_COST:"inputCostPerToken",OUTPUT_COST:"outputCostPerToken",CACHE_READ_COST:"cacheReadCostPerToken",CACHE_WRITE_COST:"cacheWriteCostPerToken",CONTEXT_WINDOW:"maxInputTokens"};function nq(e){return{model:e.model,provider:e.provider,mode:e.mode,inputCostPerToken:e.inputCostPerToken,outputCostPerToken:e.outputCostPerToken,cacheReadCostPerToken:e.cacheReadCostPerToken,cacheWriteCostPerToken:e.cacheWriteCostPerToken,maxInputTokens:e.maxInputTokens,maxOutputTokens:e.maxOutputTokens,updatedAt:e.updatedAt.toISOString()}}class n${refreshing=null;checkedAt=0;async getCatalog(){let e=await (0,t1.getPrismaClient)(),t=await e.modelCostSettings.upsert({where:{id:nN},create:{id:nN},update:{}}),r=t.catalogUrl??nO;return{url:r,defaultUrl:nO,customUrl:t.catalogUrl,fetchedAt:t.fetchedAt?.toISOString()??null,entryCount:t.entryCount,error:t.error,stale:this.isStale(t.fetchedAt)||t.sourceUrl!==r}}isStale(e){return!e||Date.now()-e.getTime()>=864e5}async saveSettings(e){let t=e?.trim()??"",r=t&&t!==nO?t:null;if(r){let e;try{e=new URL(r)}catch{throw Error("The model cost URL must be a valid URL")}if("https:"!==e.protocol&&"http:"!==e.protocol)throw Error("The model cost URL must be an http or https URL")}let i=await (0,t1.getPrismaClient)();await i.modelCostSettings.upsert({where:{id:nN},create:{id:nN,catalogUrl:r},update:{catalogUrl:r}}),this.checkedAt=0;let a=await this.getCatalog();return ie.agentEventBus.publish(ie.MODEL_COST_CATALOG_CHANGED_TOPIC,{catalog:a}),a}async refresh(){return this.refreshing||(this.refreshing=this.runRefresh().finally(()=>{this.refreshing=null})),this.refreshing}async runRefresh(){let e=await (0,t1.getPrismaClient)(),t=await this.getCatalog();try{let r=await fetch(t.url,{headers:{accept:"application/json"},signal:AbortSignal.timeout(3e4)});if(!r.ok)throw Error(`The model cost catalog request failed with ${r.status}`);let i=function(e){if(!e||"object"!=typeof e||Array.isArray(e))throw Error("The model cost catalog is not a JSON object");let t=[];for(let[r,i]of Object.entries(e)){if(nP.has(r)||!i||"object"!=typeof i||Array.isArray(i))continue;let e=nL(i.input_cost_per_token),a=nL(i.output_cost_per_token);if((null!==e||null!==a)&&(t.push({model:r,provider:nU(i.litellm_provider),mode:nU(i.mode),inputCostPerToken:e,outputCostPerToken:a,cacheReadCostPerToken:nL(i.cache_read_input_token_cost),cacheWriteCostPerToken:nL(i.cache_creation_input_token_cost),maxInputTokens:nB(i.max_input_tokens),maxOutputTokens:nB(i.max_output_tokens)}),t.length>=2e4))break}if(!t.length)throw Error("The model cost catalog contained no priced models");return t}(await r.json());await e.$transaction(async e=>{await e.modelCostEntry.deleteMany({});for(let t=0;t<i.length;t+=500)await e.modelCostEntry.createMany({data:i.slice(t,t+500)});await e.modelCostSettings.update({where:{id:nN},data:{fetchedAt:new Date,sourceUrl:t.url,entryCount:i.length,error:null}})})}catch(r){let t=r instanceof Error?r.message:String(r);await e.modelCostSettings.update({where:{id:nN},data:{error:t.slice(0,2e3)}})}let r=await this.getCatalog();return ie.agentEventBus.publish(ie.MODEL_COST_CATALOG_CHANGED_TOPIC,{catalog:r}),r}async ensureFresh(){this.refreshing&&await this.refreshing,Date.now()-this.checkedAt<3e5||((await this.getCatalog()).stale&&await this.refresh(),this.checkedAt=Date.now())}async listEntries({search:e,first:t=100,offset:r=0,sortKey:i="MODEL",direction:a="ASC"}){var n;let s,o;await this.ensureFresh();let l=await (0,t1.getPrismaClient)(),c=e?.trim(),u=c?{OR:[{model:{contains:c}},{provider:{contains:c}}]}:{},d=Math.min(Math.max(t??100,1),500),p=Math.max(r??0,0),[h,m]=await Promise.all([l.modelCostEntry.findMany({where:u,orderBy:(n=i??"MODEL",s="DESC"===(a??"ASC")?"desc":"asc","model"===(o=nM[n]??"model")?[{model:s}]:[{[o]:{sort:s,nulls:"last"}},{model:s}]),skip:p,take:d}),l.modelCostEntry.count({where:u})]);return{items:h.map(nq),totalCount:m}}async lookup(e){let t=[...new Set(e.filter(Boolean))],r=new Map;if(!t.length)return r;let i=await (0,t1.getPrismaClient)(),a=[...new Set(t.flatMap(e=>[e,nj(e)]))],n=new Map((await i.modelCostEntry.findMany({where:{model:{in:a}}})).map(e=>[e.model,e])),s=[];for(let e of t){let t=n.get(e)??n.get(nj(e));t?r.set(e,nq(t)):s.push(e)}if(!s.length)return r;let o=await i.modelCostEntry.findMany({where:{OR:s.map(e=>({model:{endsWith:`/${nj(e)}`}}))}});for(let e of s){let t=nj(e).toLowerCase(),i=o.find(e=>nj(e.model).toLowerCase()===t);i&&r.set(e,nq(i))}return r}estimate(e,t){if(!e)return null;let r=e.inputCostPerToken,i=e.outputCostPerToken;if(null===r&&null===i)return null;let a=e.cacheReadCostPerToken??r??0,n=e.cacheWriteCostPerToken??r??0;return t.inputTokens*(r??0)+t.outputTokens*(i??0)+t.cacheReadTokens*a+t.cacheWriteTokens*n}}e.i(648153);var nF=e.i(594875),nG=e.i(937121),nK=e.i(988349);let nH=["ANY_AGENT_HOME","SPECIFIC_AGENT_HOME","ANY_WORKTREE","REPOSITORY_WORKTREE"],nV=["NEVER","ON_FAILURE","ALWAYS"],nW=["EXCLUSIVE","NON_EXCLUSIVE","EXCLUDED"],nJ=["QUEUED","RUNNING","RESTARTING","CANCELLING"],nz=["SUCCEEDED","FAILED","CANCELLED"],nY=["SUCCEEDED","FAILED","CANCELLED","TIMED_OUT"],nZ=e=>!!(e&&!nY.includes(e.status)),nQ="aide.command.export",nX=["QUEUED","RESTARTING"],n0=(e,t)=>e.queuedAt.getTime()-t.queuedAt.getTime()||e.id.localeCompare(t.id);function n1(e,t,r){let i=t.trim().toUpperCase();if(!e.includes(i))throw Error(`${r} is not supported`);return i}function n2(e,t,r){let i=e.trim();if(!i)throw Error(`${t} is required`);if(i.length>r)throw Error(`${t} is too long`);return i}function n3(e,t){if(!e||"object"!=typeof e||Array.isArray(e))throw Error(`${t} must be an object`);return e}let n4=e=>"string"==typeof e&&e.trim()?e.trim():null;function n6(e){ie.agentEventBus.publish(ie.COMMANDS_CHANGED_TOPIC,{commandsChanged:e})}function n8(e){ie.agentEventBus.publish(ie.COMMAND_RUNS_CHANGED_TOPIC,{commandRunsChanged:e}),ie.agentEventBus.publish((0,ie.commandRunChangedTopic)(e.id),{commandRunChanged:e}),ie.agentEventBus.publish(ie.SIDEBAR_STATUS_CHANGED_TOPIC,{sidebarStatusChanged:!0})}class n5{agentControl;notifications;timer;reconciliation;dispatchChain;constructor(e,t){this.agentControl=e,this.notifications=t,this.timer=null,this.reconciliation=null,this.dispatchChain=Promise.resolve(),this.agentControl.registerCompletionHandler(nG.COMMAND_RUN_JOB_KIND,e=>this.handleAttemptCompletion(e)),this.agentControl.registerConnectionHandler(e=>this.reconcileWithReporting({agentId:e}))}startRuntime(){this.timer||(this.reconcileWithReporting(),this.timer=setInterval(()=>void this.reconcileWithReporting(),1e3),this.timer.unref())}async reconcileWithReporting(e={}){if(this.reconciliation)return this.reconciliation;this.reconciliation=this.reconcile(e);try{await this.reconciliation}catch(e){console.error("Command runtime reconciliation failed:",e)}finally{this.reconciliation=null}}async listDefinitions(e=!1){return(await (0,t1.getPrismaClient)()).commandDefinition.findMany({where:e?{}:{archivedAt:null},include:{targetAgent:!0,targetRepository:!0},orderBy:[{archivedAt:"asc"},{name:"asc"}]})}async getDefinition(e){return(await (0,t1.getPrismaClient)()).commandDefinition.findUnique({where:{id:e},include:{targetAgent:!0,targetRepository:!0}})}normalizeDefinition(e){let t=n1(nH,e.targetKind,"Target scope"),r=n1(nV,e.restartPolicy??"NEVER","Restart policy"),i=void 0===e.restartLimit?3:e.restartLimit;if(null!==i&&(!Number.isInteger(i)||i<0||i>100))throw Error("Restart limit must be null or an integer from 0 to 100");let a="SPECIFIC_AGENT_HOME"===t,n="REPOSITORY_WORKTREE"===t;if(!!e.targetAgentId!==a)throw Error(a?"A specific-agent command requires an agent":"This target scope does not accept a specific agent");if(!!e.targetRepositoryId!==n)throw Error(n?"A repository-worktree command requires a repository":"This target scope does not accept a repository");let s=n1(nW,e.concurrency??"NON_EXCLUSIVE","Concurrency");return{name:n2(e.name,"Name",120),description:(e.description??"").trim().slice(0,2e3),script:n2(e.script,"Script",1e6),targetKind:t,targetAgentId:e.targetAgentId??null,targetRepositoryId:e.targetRepositoryId??null,restartPolicy:r,restartLimit:i,concurrency:s,blocksGitOperations:"EXCLUSIVE"===s||(e.blocksGitOperations??!1),quickActionEnabled:e.quickActionEnabled??!1,quickActionIconKey:n2(e.quickActionIconKey??"terminal","Quick action icon",40),quickActionButtonVariant:n2(e.quickActionButtonVariant??"default","Quick action style",40),notificationsEnabled:e.notificationsEnabled??!0}}async createDefinition(e){let t=await (0,t1.getPrismaClient)(),r=await t.commandDefinition.create({data:{id:(0,b.randomUUID)(),...this.normalizeDefinition(e)},include:{targetAgent:!0,targetRepository:!0}});return n6(r),r}async updateDefinition(e,t){let r=await (0,t1.getPrismaClient)(),i=await r.commandDefinition.update({where:{id:e},data:this.normalizeDefinition(t),include:{targetAgent:!0,targetRepository:!0}});return n6(i),i}async deleteDefinition(e){let t=await (0,t1.getPrismaClient)(),r=await t.commandDefinition.findUnique({where:{id:e}});if(!r)return!1;if(await t.commandRun.count({where:{commandId:e}}))throw Error("Archive commands that have run history instead of deleting them");return await t.commandDefinition.delete({where:{id:e}}),n6(r),!0}async exportDefinition(e){let t=await this.getDefinition(e);if(!t)throw Error("Command not found");return{format:nQ,schemaVersion:1,exportedAt:new Date().toISOString(),command:{name:t.name,description:t.description,script:t.script,targetKind:t.targetKind,targetAgentName:t.targetAgent?.name??null,targetRepositoryName:t.targetRepository?.name??null,restartPolicy:t.restartPolicy,restartLimit:t.restartLimit,concurrency:t.concurrency,blocksGitOperations:t.blocksGitOperations,quickActionEnabled:t.quickActionEnabled,quickActionIconKey:t.quickActionIconKey,quickActionButtonVariant:t.quickActionButtonVariant,notificationsEnabled:t.notificationsEnabled}}}async resolveImportTarget(e){let t=n1(nH,n4(e.targetKind)??"ANY_AGENT_HOME","Target scope"),r=await (0,t1.getPrismaClient)();if("SPECIFIC_AGENT_HOME"===t){let i=n4(e.targetAgentName),a=i?await r.agent.findFirst({where:{name:i},orderBy:{id:"asc"}}):null;return a?{targetKind:t,targetAgentId:a.id,targetRepositoryId:null,widened:!1}:{targetKind:"ANY_AGENT_HOME",targetAgentId:null,targetRepositoryId:null,widened:!0}}if("REPOSITORY_WORKTREE"===t){let i=n4(e.targetRepositoryName),a=i?await r.codebaseRepository.findFirst({where:{name:i},orderBy:{id:"asc"}}):null;return a?{targetKind:t,targetAgentId:null,targetRepositoryId:a.id,widened:!1}:{targetKind:"ANY_WORKTREE",targetAgentId:null,targetRepositoryId:null,widened:!0}}return{targetKind:t,targetAgentId:null,targetRepositoryId:null,widened:!1}}async importDefinition(e){let t=e.payload;if("string"==typeof t){if(Buffer.byteLength(t,"utf8")>2097152)throw Error("Command import is too large");t=JSON.parse(t)}let r=n3(t,"Command import"),i=r.format===nQ?n3(r.command,"Exported command"):r,{widened:a,...n}=await this.resolveImportTarget(i),s=e.name?.trim()||n4(i.name);if(!s)throw Error("Name is required");let o=n4(i.script);if(!o)throw Error("Script is required");return this.createDefinition({name:s,description:"string"==typeof i.description?i.description:"",script:o,...n,restartPolicy:n4(i.restartPolicy)??"NEVER",restartLimit:null===i.restartLimit||"number"==typeof i.restartLimit?i.restartLimit:3,concurrency:n4(i.concurrency)??"NON_EXCLUSIVE",blocksGitOperations:!0===i.blocksGitOperations,quickActionEnabled:!a&&!0===i.quickActionEnabled,quickActionIconKey:n4(i.quickActionIconKey)??"terminal",quickActionButtonVariant:n4(i.quickActionButtonVariant)??"default",notificationsEnabled:!1!==i.notificationsEnabled})}async archiveDefinition(e,t){let r=await (0,t1.getPrismaClient)(),i=await r.commandDefinition.update({where:{id:e},data:{archivedAt:t?new Date:null},include:{targetAgent:!0,targetRepository:!0}});return n6(i),i}async eligibleForAgent(e){return(await (0,t1.getPrismaClient)()).commandDefinition.findMany({where:{archivedAt:null,OR:[{targetKind:"ANY_AGENT_HOME"},{targetKind:"SPECIFIC_AGENT_HOME",targetAgentId:e}]},include:{targetAgent:!0,targetRepository:!0},orderBy:{name:"asc"}})}async eligibleForWorktree(e){let t=await (0,t1.getPrismaClient)(),r=await t.worktree.findUnique({where:{id:e},select:{codebase:{select:{repositoryId:!0}}}});if(!r)throw Error("Worktree not found");return t.commandDefinition.findMany({where:{archivedAt:null,OR:[{targetKind:"ANY_WORKTREE"},{targetKind:"REPOSITORY_WORKTREE",targetRepositoryId:r.codebase.repositoryId}]},include:{targetAgent:!0,targetRepository:!0},orderBy:{name:"asc"}})}async listRuns(e){let t=await (0,t1.getPrismaClient)(),r=Math.max(1,Math.min(e.first??50,200)),i=e.search?.trim(),a={...e.includeArchived?{}:{archivedAt:null},...e.agentId?{agentId:e.agentId}:{},...e.worktreeId?{worktreeId:e.worktreeId}:{},...e.statuses?.length?{status:{in:e.statuses}}:{},...i?{OR:[{snapshotName:{contains:i}},{agentName:{contains:i}},{worktreePath:{contains:i}}]}:{}},[n,s]=await Promise.all([t.commandRun.findMany({where:a,include:{command:!0,agent:!0,worktree:{include:{codebase:{include:{repository:!0}}}},attempts:{orderBy:{attempt:"asc"}}},orderBy:[{createdAt:"desc"},{id:"desc"}],take:r+1,...e.after?{cursor:{id:e.after},skip:1}:{}}),t.commandRun.count({where:a})]),o=n.length>r,l=n.slice(0,r);return{nodes:l,totalCount:s,pageInfo:{hasNextPage:o,endCursor:l.at(-1)?.id??null}}}async getRun(e){return(await (0,t1.getPrismaClient)()).commandRun.findUnique({where:{id:e},include:{command:!0,agent:!0,worktree:{include:{codebase:{include:{repository:!0}}}},attempts:{include:{agentJob:!0},orderBy:{attempt:"asc"}},predecessor:!0,successor:!0}})}async runQueue(e){let t=await (0,t1.getPrismaClient)(),r=await t.commandRun.findUnique({where:{id:e},include:{agent:{select:{lastSeenAt:!0,disconnectedAt:!0,heartbeatIntervalSeconds:!0}},predecessor:{select:{status:!0}},attempts:{select:{agentJobId:!0,completionProcessedAt:!0},orderBy:{attempt:"desc"},take:1}}});if(!r)return{reason:"NOT_QUEUED",position:0,waitingCount:0,entries:[]};let i=r.attempts[0],n=!!(r.agent?.lastSeenAt&&!r.agent.disconnectedAt&&Date.now()-r.agent.lastSeenAt.getTime()<=(0,a.agentOnlineWindowMs)(r.agent));return function(e){let{candidate:t}=e,r="EXCLUDED"!==t.concurrency,i=e.peers.filter(e=>e.holdingTarget),a=[...i,...t.holdingTarget?[t]:[]].sort(n0),n=[...e.peers.filter(e=>!e.holdingTarget),...t.holdingTarget?[]:[t]].sort(n0),s=n.findIndex(e=>e.id===t.id),o=s<0?[]:n.slice(0,s),l=e=>r&&"EXCLUDED"!==e.concurrency&&("EXCLUSIVE"===t.concurrency||"EXCLUSIVE"===e.concurrency),c=i.filter(l),u=o.filter(l),d=t.stopRequested||!nX.includes(t.status)?"NOT_QUEUED":t.holdingTarget?e.agentOnline?"WAITING_FOR_AGENT":"AGENT_OFFLINE":e.predecessorPending?"WAITING_FOR_PREDECESSOR":e.restartPending?"RESTART_DELAY":c.length?"TARGET_BUSY":u.length?"QUEUED_BEHIND":e.agentOnline?"READY":"AGENT_OFFLINE",p=new Set("TARGET_BUSY"===d||"QUEUED_BEHIND"===d?[...c,...u].map(e=>e.id):[]);return{reason:d,position:s<0?0:s+1,waitingCount:n.length,entries:[...a,...n].map(e=>({...e,blocking:p.has(e.id),currentRun:e.id===t.id}))}}({candidate:{id:r.id,displayNumber:r.displayNumber,name:r.snapshotName,status:r.status,concurrency:r.snapshotConcurrency,queuedAt:r.queuedAt,stopRequested:r.stopRequested,holdingTarget:!!(i?.agentJobId&&!i.completionProcessedAt)},peers:"EXCLUDED"===r.snapshotConcurrency?[]:await this.targetPeers(r),agentOnline:n,predecessorPending:!!(r.predecessor&&!nz.includes(r.predecessor.status)),restartPending:!!("RESTARTING"===r.status&&r.nextRestartAt&&r.nextRestartAt.getTime()>Date.now())})}async listOutput(e,t=0,r=-1,i=1e3){let a=await (0,t1.getPrismaClient)();return i<1?[]:a.commandRunOutputChunk.findMany({where:{OR:[{attempt:{runId:e,attempt:{gt:t}}},{attempt:{runId:e,attempt:t},sequence:{gt:r}}]},include:{attempt:{select:{attempt:!0,runId:!0}}},orderBy:[{attempt:{attempt:"asc"}},{sequence:"asc"}],take:Math.max(1,Math.min(i,5e3))})}async resolveTarget(e,t){let r=await (0,t1.getPrismaClient)();if("ANY_AGENT_HOME"===e.targetKind||"SPECIFIC_AGENT_HOME"===e.targetKind){if(!t.agentId||t.worktreeId)throw Error("This command requires an agent-home target");if("SPECIFIC_AGENT_HOME"===e.targetKind&&e.targetAgentId!==t.agentId)throw Error("This command is not eligible for the selected agent");let i=await r.agent.findUnique({where:{id:t.agentId}});if(!i)throw Error("Agent not found");return this.requireCapability(i.capabilitiesJson),{agent:i,worktree:null}}if(!t.worktreeId||t.agentId)throw Error("This command requires a worktree target");let i=await r.worktree.findUnique({where:{id:t.worktreeId},include:{codebase:{include:{agent:!0,repository:!0}}}});if(!i||i.missingAt)throw Error("Worktree is unavailable");if("REPOSITORY_WORKTREE"===e.targetKind&&e.targetRepositoryId!==i.codebase.repositoryId)throw Error("This command is not eligible for the selected repository");return this.requireCapability(i.codebase.agent.capabilitiesJson),{agent:i.codebase.agent,worktree:i}}requireCapability(e){if(!(function(e){try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}catch{return[]}})(e).includes(nG.COMMAND_RUN_JOB_KIND))throw Error("The selected agent must be upgraded before it can run commands")}async startRun(e){let t,r=await (0,t1.getPrismaClient)(),i=e.idempotencyKey?.trim()||(0,b.randomUUID)(),a=await r.commandRun.findUnique({where:{idempotencyKey:i}});if(a)return this.getRun(a.id);let n=await r.commandDefinition.findUnique({where:{id:e.commandId}});if(!n||n.archivedAt)throw Error("Command not found");let{agent:s,worktree:o}=await this.resolveTarget(n,e);try{t=await r.$transaction(async t=>{let r=await t.commandRunNumberSequence.upsert({where:{id:"default"},create:{id:"default",nextValue:1},update:{nextValue:{increment:1}}});return t.commandRun.create({data:{id:(0,b.randomUUID)(),displayNumber:r.nextValue,commandId:n.id,idempotencyKey:i,origin:(e.origin??"MANUAL").trim().toUpperCase(),snapshotName:n.name,snapshotDescription:n.description,snapshotScript:n.script,snapshotTargetKind:n.targetKind,snapshotRestartPolicy:n.restartPolicy,snapshotRestartLimit:n.restartLimit,snapshotConcurrency:n.concurrency,snapshotBlocksGitOperations:n.blocksGitOperations||!0===e.blocksGitOperations,snapshotNotificationsEnabled:n.notificationsEnabled,snapshotJson:JSON.stringify(n),agentId:s.id,worktreeId:o?.id??null,agentName:s.name,agentHostname:s.hostname,worktreePath:o?.folder??null,worktreeBranch:o?.branch??null}})})}catch(t){let e=await r.commandRun.findUnique({where:{idempotencyKey:i}});if(!e)throw t;return this.getRun(e.id)}return n8(t),await this.dispatch(t.id),this.getRun(t.id)}async startCustomRun(e){let t,r=await (0,t1.getPrismaClient)(),i=e.idempotencyKey?.trim()||(0,b.randomUUID)(),a=await r.commandRun.findUnique({where:{idempotencyKey:i}});if(a)return this.getRun(a.id);let n=n2(e.script,"Script",1e6),s=e.agentId&&!e.worktreeId?"ANY_AGENT_HOME":e.worktreeId&&!e.agentId?"ANY_WORKTREE":null;if(!s)throw Error("A custom command requires exactly one agent-home or worktree target");let{agent:o,worktree:l}=await this.resolveTarget({targetKind:s,targetAgentId:null,targetRepositoryId:null},e),c={name:"Custom command",description:"",script:n,targetKind:s,restartPolicy:"NEVER",restartLimit:null,concurrency:"NON_EXCLUSIVE",blocksGitOperations:!0===e.blocksGitOperations,notificationsEnabled:!0};try{t=await r.$transaction(async t=>{let r=await t.commandRunNumberSequence.upsert({where:{id:"default"},create:{id:"default",nextValue:1},update:{nextValue:{increment:1}}});return t.commandRun.create({data:{id:(0,b.randomUUID)(),displayNumber:r.nextValue,commandId:null,idempotencyKey:i,origin:(e.origin??"MANUAL").trim().toUpperCase(),status:"QUEUED",snapshotName:c.name,snapshotDescription:c.description,snapshotScript:c.script,snapshotTargetKind:c.targetKind,snapshotRestartPolicy:c.restartPolicy,snapshotRestartLimit:c.restartLimit,snapshotConcurrency:c.concurrency,snapshotBlocksGitOperations:c.blocksGitOperations,snapshotNotificationsEnabled:c.notificationsEnabled,snapshotJson:JSON.stringify(c),agentId:o.id,worktreeId:l?.id??null,agentName:o.name,agentHostname:o.hostname,worktreePath:l?.folder??null,worktreeBranch:l?.branch??null}})})}catch(t){let e=await r.commandRun.findUnique({where:{idempotencyKey:i}});if(!e)throw t;return this.getRun(e.id)}n8(t);try{await this.dispatch(t.id)}catch(e){throw await this.failDispatch(t.id,e instanceof Error?e.message:String(e)),e}return this.getRun(t.id)}async targetPeers(e){let t=await (0,t1.getPrismaClient)();return(await t.commandRun.findMany({where:{id:{not:e.id},status:{in:[...nJ]},snapshotConcurrency:{not:"EXCLUDED"},...e.worktreeId?{worktreeId:e.worktreeId}:{agentId:e.agentId,worktreeId:null}},select:{id:!0,displayNumber:!0,snapshotName:!0,status:!0,snapshotConcurrency:!0,queuedAt:!0,attempts:{select:{agentJobId:!0,completionProcessedAt:!0},orderBy:{attempt:"desc"},take:1}}})).map(e=>{let t=e.attempts[0];return{id:e.id,displayNumber:e.displayNumber,name:e.snapshotName,status:e.status,concurrency:e.snapshotConcurrency,queuedAt:e.queuedAt,holdingTarget:!!(t?.agentJobId&&!t.completionProcessedAt)}})}async admitRun(e){if("EXCLUDED"===e.snapshotConcurrency)return!0;let t=await this.targetPeers(e),r=t.filter(e=>e.holdingTarget),i=t.filter(e=>!e.holdingTarget);var a={candidate:{id:e.id,concurrency:e.snapshotConcurrency,queuedAt:e.queuedAt},holders:r,waiting:i};if("EXCLUDED"===a.candidate.concurrency)return!0;let n=a.holders.filter(e=>"EXCLUDED"!==e.concurrency&&e.id!==a.candidate.id),s=a.waiting.filter(e=>"EXCLUDED"!==e.concurrency&&e.id!==a.candidate.id).filter(e=>{let t=e.queuedAt.getTime()-a.candidate.queuedAt.getTime();return 0!==t?t<0:e.id<a.candidate.id});return"EXCLUSIVE"===a.candidate.concurrency?0===n.length&&0===s.length:!n.some(e=>"EXCLUSIVE"===e.concurrency)&&!s.some(e=>"EXCLUSIVE"===e.concurrency)}dispatch(e){let t=this.dispatchChain.then(()=>this.dispatchRun(e),()=>this.dispatchRun(e));return this.dispatchChain=t.catch(()=>void 0),t}async dispatchRun(e){let t=await (0,t1.getPrismaClient)(),r=await t.commandRun.findUnique({where:{id:e},include:{agent:!0,worktree:{include:{codebase:!0}},attempts:!0}});if(!r||r.stopRequested)return;if(!r.agentId||!r.agent)return void await this.failDispatch(r.id,"The command agent is no longer available");if(r.predecessorRunId){let e=await t.commandRun.findUnique({where:{id:r.predecessorRunId},select:{status:!0}});if(e&&!nz.includes(e.status))return}if(new Set(["ANY_WORKTREE","REPOSITORY_WORKTREE"]).has(r.snapshotTargetKind)&&(!r.worktreeId||!r.worktree||r.worktree.missingAt))return void await this.failDispatch(r.id,"The command worktree is no longer available");if(r.worktree&&r.worktree.codebase.agentId!==r.agentId)return void await this.failDispatch(r.id,"The worktree is no longer assigned to the command agent");try{this.requireCapability(r.agent.capabilitiesJson)}catch(e){await this.failDispatch(r.id,e instanceof Error?e.message:String(e));return}let i=r.attempts.reduce((e,t)=>!e||t.attempt>e.attempt?t:e,null);if(!(i?.agentJobId&&!i.completionProcessedAt)&&!await this.admitRun(r))return;let a=!i||i.agentJobId||i.completionProcessedAt||i.finishedAt?(i?.attempt??0)+1:i.attempt,n=i?.attempt===a?i:await t.commandRunAttempt.findUnique({where:{runId_attempt:{runId:e,attempt:a}}});if(!n)try{n=await t.commandRunAttempt.create({data:{id:(0,b.randomUUID)(),runId:e,attempt:a}})}catch(r){if(!(n=await t.commandRunAttempt.findUnique({where:{runId_attempt:{runId:e,attempt:a}}})))throw r}if(!n.agentJobId){let e;try{e=await this.agentControl.createJob({agentId:r.agentId,kind:nG.COMMAND_RUN_JOB_KIND,payload:{commandRunId:r.id,attemptId:n.id,targetKind:r.worktreeId?"WORKTREE":"AGENT_HOME",cwd:r.worktree?.folder??null,script:r.snapshotScript},idempotencyKey:`command-run:${r.id}:attempt:${a}`,timeoutSeconds:0,worktreeId:r.worktreeId,codebaseId:r.worktree?.codebaseId??null,visibility:"SYSTEM",blocksGitOperations:r.snapshotBlocksGitOperations})}catch(e){if(!(0,nK.isCodebaseBusyError)(e))throw e;return}n=await t.commandRunAttempt.update({where:{id:n.id},data:{agentJobId:e.id,status:e.status}})}n8(await t.commandRun.update({where:{id:r.id},data:{status:"RUNNING"===n.status?"RUNNING":"QUEUED",startedAt:"RUNNING"===n.status?r.startedAt??new Date:null,nextRestartAt:null,error:null}}))}async failDispatch(e,t){let r=await (0,t1.getPrismaClient)(),i=await r.commandRun.update({where:{id:e},data:{status:"FAILED",error:t,finishedAt:new Date,nextRestartAt:null},include:{worktree:{select:{highlightColor:!0}}}});n8(i),await this.notifyFinishedRun(i)}async terminateRun(e){let t=await (0,t1.getPrismaClient)(),r=await t.commandRun.findUnique({where:{id:e},include:{attempts:{orderBy:{attempt:"desc"},take:1}}});if(!r)throw Error("Command run not found");if(nz.includes(r.status))return r;let i=await t.commandRun.update({where:{id:e},data:{stopRequested:!0,status:"CANCELLING",nextRestartAt:null}}),a=r.attempts[0]?.agentJobId;return nZ(a?await this.agentControl.cancelJob(a):null)||await this.finishCancelled(e),n8(i),this.getRun(e)}async rerun(e){let t=await (0,t1.getPrismaClient)(),r=await t.commandRun.findUnique({where:{id:e}});if(!r)throw Error("Command run not found");let i=await t.commandRun.findUnique({where:{predecessorRunId:r.id}});if(i)return this.getRun(i.id);let a=await t.$transaction(async e=>{let t=await e.commandRunNumberSequence.upsert({where:{id:"default"},create:{id:"default",nextValue:1},update:{nextValue:{increment:1}}});return e.commandRun.create({data:{id:(0,b.randomUUID)(),displayNumber:t.nextValue,commandId:r.commandId,idempotencyKey:`rerun:${r.id}:${(0,b.randomUUID)()}`,origin:"RERUN",snapshotName:r.snapshotName,snapshotDescription:r.snapshotDescription,snapshotScript:r.snapshotScript,snapshotTargetKind:r.snapshotTargetKind,snapshotRestartPolicy:r.snapshotRestartPolicy,snapshotRestartLimit:r.snapshotRestartLimit,snapshotConcurrency:r.snapshotConcurrency,snapshotBlocksGitOperations:r.snapshotBlocksGitOperations,snapshotNotificationsEnabled:r.snapshotNotificationsEnabled,snapshotJson:r.snapshotJson,agentId:r.agentId,worktreeId:r.worktreeId,agentName:r.agentName,agentHostname:r.agentHostname,worktreePath:r.worktreePath,worktreeBranch:r.worktreeBranch,predecessorRunId:r.id}})});return n8(a),nz.includes(r.status)?await this.dispatch(a.id):await this.terminateRun(r.id),this.getRun(a.id)}async archiveRuns(e,t){let r=await (0,t1.getPrismaClient)();for(let i of(await r.commandRun.updateMany({where:{id:{in:e},status:{in:[...nz]}},data:{archivedAt:t?new Date:null}}),e)){let e=await r.commandRun.findUnique({where:{id:i}});e&&n8(e)}return!0}async deleteRuns(e){let t=await (0,t1.getPrismaClient)();return(await t.commandRun.deleteMany({where:{id:{in:e},status:{in:[...nz]}}})).count}async appendOutput(e,t,r,i){if(!i.length||i.length>nG.MAX_COMMAND_OUTPUT_BATCH_CHUNKS)throw Error(`Output batches must contain 1 to ${nG.MAX_COMMAND_OUTPUT_BATCH_CHUNKS} chunks`);let a=await (0,t1.getPrismaClient)(),n=await a.commandRunAttempt.findUnique({where:{id:r},include:{run:!0}});if(!n||n.agentJobId!==t||n.run.agentId!==e)throw Error("Command attempt not found for this agent job");let s=i.map(e=>{if(!Number.isInteger(e.sequence)||e.sequence<0)throw Error("Output sequence must be a non-negative integer");if(!["STDOUT","STDERR","SYSTEM"].includes(e.stream))throw Error("Output stream is invalid");let t=Buffer.from(e.dataBase64,"base64");if(t.length!==e.byteLength||t.length>262144)throw Error("Output byte length is invalid");let r=new Date(e.createdAt);if(Number.isNaN(r.valueOf()))throw Error("Output date is invalid");return{...e,createdAt:r}});await Promise.all(s.map(e=>a.commandRunOutputChunk.upsert({where:{attemptId_sequence:{attemptId:r,sequence:e.sequence}},create:{id:(0,b.randomUUID)(),attemptId:r,...e},update:{}})));let o=await a.commandRunOutputChunk.findMany({where:{attemptId:r,sequence:{in:s.map(e=>e.sequence)}},orderBy:{sequence:"asc"}});for(let e of o){let t={...e,runId:n.runId,attemptNumber:n.attempt};ie.agentEventBus.publish((0,ie.commandRunOutputTopic)(n.runId),{commandRunOutputAdded:t}),ie.agentEventBus.publish(ie.COMMAND_RUN_OUTPUT_CHANGED_TOPIC,{commandRunOutputAdded:t})}return o}async finishCancelled(e){let t=await (0,t1.getPrismaClient)();n8(await t.commandRun.update({where:{id:e},data:{status:"CANCELLED",finishedAt:new Date,nextRestartAt:null}}));let r=await t.commandRun.findUnique({where:{predecessorRunId:e}});r&&await this.dispatch(r.id)}async notifyFinishedRun(e){if(!this.notifications||!e.snapshotNotificationsEnabled||"SUCCEEDED"!==e.status&&"FAILED"!==e.status)return;let t=[e.worktreeBranch??e.worktreePath??`${e.agentName} \xb7 ${e.agentHostname}`,"FAILED"===e.status?e.error:null].filter(e=>!!e).join(" · ").slice(0,1e3);try{let r=await (0,t1.getPrismaClient)(),i=await r.$transaction(r=>this.notifications.recordInTransaction(r,{dedupeKey:`command-run:${e.id}:${e.status}`,typeKey:"SUCCEEDED"===e.status?"COMMAND_RUN_SUCCEEDED":"COMMAND_RUN_FAILED",title:`${e.snapshotName} ${e.status.toLowerCase()}`,body:t,href:`/commands/runs/${e.id}`,resourceKind:"COMMAND_RUN",resourceId:e.id,worktreeId:e.worktreeId,highlightColor:e.worktree?.highlightColor??null}));this.notifications.created(i)}catch(e){console.error("Command run notification failed:",e)}}async handleAttemptCompletion(e){let t=await (0,t1.getPrismaClient)(),r=await t.commandRunAttempt.findUnique({where:{agentJobId:e.id},include:{run:!0,agentJob:!0}});if(!r||r.completionProcessedAt)return;let i=new Date,a=function(e){if(!e)return{};try{let t=JSON.parse(e);return t&&"object"==typeof t?t:{}}catch{return{}}}(e.resultJson);if(1!==(await t.commandRunAttempt.updateMany({where:{id:r.id,completionProcessedAt:null},data:{status:e.status,exitCode:a.exitCode??null,signal:a.signal??null,error:e.error,startedAt:r.agentJob?.startedAt??r.startedAt,finishedAt:r.agentJob?.finishedAt??i,completionProcessedAt:i}})).count)return;if(r.run.stopRequested||"CANCELLED"===e.status)return void await this.finishCancelled(r.runId);let n="SUCCEEDED"===e.status&&0===a.exitCode,s=n1(nV,r.run.snapshotRestartPolicy,"Restart policy"),o=r.agentJob?.startedAt??r.createdAt,l=function(e){if(e.manualStop||!("ALWAYS"===e.policy||"ON_FAILURE"===e.policy&&!e.clean))return{restart:!1,restartCount:e.restartCount,exhausted:!1};let t=(e.durationMs>=6e4?0:e.restartCount)+1,r=null!==e.limit&&t>e.limit;return{restart:!r,restartCount:t,exhausted:r}}({policy:s,limit:r.run.snapshotRestartLimit,restartCount:r.run.restartCount,durationMs:i.getTime()-o.getTime(),clean:n,manualStop:r.run.stopRequested});if(l.restart)return void n8(await t.commandRun.update({where:{id:r.runId},data:{status:"RESTARTING",restartCount:l.restartCount,nextRestartAt:new Date(i.getTime()+1e3),exitCode:a.exitCode??null,signal:a.signal??null,error:e.error}}));let c=await t.commandRun.update({where:{id:r.runId},data:{status:n?"SUCCEEDED":"FAILED",exitCode:a.exitCode??null,signal:a.signal??null,error:e.error??(l.exhausted?"Restart limit reached":n?null:"Command failed"),finishedAt:i,nextRestartAt:null},include:{worktree:{select:{highlightColor:!0}}}});n8(c),await this.notifyFinishedRun(c)}async reconcile(e={}){let t=await (0,t1.getPrismaClient)(),r=new Date;for(let i of(await t.commandRun.findMany({where:{status:{in:[...nJ]},...e.agentId?{agentId:e.agentId}:{}},include:{attempts:{include:{agentJob:!0},orderBy:{attempt:"desc"},take:1}}}))){let e=i.attempts[0];if(i.stopRequested){let t=e?.agentJob??null;t&&nZ(t)?await this.agentControl.cancelJob(t.id):await this.finishCancelled(i.id);continue}if("RESTARTING"===i.status&&(!i.nextRestartAt||i.nextRestartAt<=r)){await this.dispatch(i.id);continue}if(e?.agentJob&&["SUCCEEDED","FAILED","CANCELLED","TIMED_OUT"].includes(e.agentJob.status)){await this.handleAttemptCompletion(e.agentJob);continue}if(e?.agentJob&&["QUEUED","RUNNING"].includes(e.agentJob.status)){let a="RUNNING"===e.agentJob.status?"RUNNING":"QUEUED";e.status!==e.agentJob.status&&await t.commandRunAttempt.update({where:{id:e.id},data:{status:e.agentJob.status,startedAt:e.agentJob.startedAt}}),i.status!==a&&n8(await t.commandRun.update({where:{id:i.id},data:{status:a,startedAt:"RUNNING"===a?i.startedAt??e.agentJob.startedAt??r:i.startedAt}}));continue}"QUEUED"!==i.status||e&&(e.agentJobId||e.completionProcessedAt||e.finishedAt)||await this.dispatch(i.id)}}}var n9=e.i(735255);function n7(e=new Date){let t=e.getFullYear(),r=String(e.getMonth()+1).padStart(2,"0"),i=String(e.getDate()).padStart(2,"0");return`${t}-${r}-${i}`}class se{ccusage;diskSpace;polling;usageTimer;usageRunning;constructor(e,t,r){this.ccusage=e,this.diskSpace=t,this.polling=r,this.usageRunning=!1,this.ccusage.registerCompletionObserver(e=>this.recordCompletedUsage(e))}async recordCompletedUsage(e){let t=n7(),r=e.aggregate.days.find(e=>e.period===t);await this.persistUsage(t,r?.totalCost??0,new Date)}startRuntime(){this.polling.register({id:"sidebar-usage",kind:"SIDEBAR_USAGE",runtime:"SERVER",enabled:!0,cadenceSeconds:300,details:{}}),this.pruneInterruptedCollections().catch(e=>{console.error("Sidebar usage cleanup failed:",e instanceof Error?e.message:e)}).finally(()=>void this.runUsagePoll())}stopRuntime(){this.usageTimer&&clearTimeout(this.usageTimer),this.usageTimer=void 0}scheduleUsagePoll(){this.usageTimer&&clearTimeout(this.usageTimer);let e=new Date(Date.now()+3e5);this.polling.schedule("sidebar-usage",e),this.usageTimer=setTimeout(()=>void this.runUsagePoll(),3e5),this.usageTimer.unref()}async runUsagePoll(){if(!this.usageRunning){this.usageRunning=!0,this.polling.schedule("sidebar-usage",null);try{await this.polling.run("sidebar-usage",()=>this.collectUsage(),e=>({period:e.period,successfulAgents:e.successfulAgents}))}catch(e){console.error("Sidebar usage refresh failed:",e instanceof Error?e.message:e)}finally{this.usageRunning=!1,this.scheduleUsagePoll()}}}async collectUsage(){if("true"===process.env.SIDEBAR_USAGE_COLLECTION_DISABLED)return{period:n7(),successfulAgents:0};let e=`sidebar-usage:${(0,b.randomUUID)()}`;try{let t=await this.ccusage.collect(e);return{period:n7(),successfulAgents:t.progress.successfulCount}}finally{await this.removeCollection(e)}}async persistUsage(e,t,r){let i=await (0,t1.getPrismaClient)();await i.sidebarUsageSummary.upsert({where:{id:"default"},create:{id:"default",period:e,totalCost:t,collectedAt:r},update:{period:e,totalCost:t,collectedAt:r}}),this.publish()}async latestSuccessfulUsage(e){let t=await (0,t1.getPrismaClient)(),r=await t.ccusageHistoryState.findUnique({where:{id:"default"},select:{clearedAt:!0}}),i=r?.clearedAt?{OR:[{finishedAt:{gt:r.clearedAt}},{finishedAt:null,createdAt:{gt:r.clearedAt}}]}:{},a=await t.agentJob.findMany({where:{kind:nC.CCUSAGE_REPORT_JOB_KIND,status:"SUCCEEDED",resultJson:{not:null},...i},orderBy:[{finishedAt:"desc"},{createdAt:"desc"}],distinct:["agentId"],select:{resultJson:!0,finishedAt:!0,createdAt:!0,agent:{select:{id:!0,name:!0,hostname:!0}}}}),n=a.flatMap(e=>{try{let t=(0,nC.parseCcusageJobResult)(JSON.parse(e.resultJson));return[{agent:e.agent,report:t.report}]}catch{return[]}});if(!n.length)return null;let s=(0,n9.aggregateUsage)(n).days.find(t=>t.period===e);return s?{totalCost:s.totalCost,collectedAt:a.reduce((e,t)=>{let r=t.finishedAt??t.createdAt;return r>e?r:e},new Date(0))}:null}async removeCollection(e){let t=await (0,t1.getPrismaClient)();await t.agentJob.deleteMany({where:{ccusageCollectionId:e}}),await t.ccusageCollection.deleteMany({where:{id:e}})}async pruneInterruptedCollections(){let e=await (0,t1.getPrismaClient)(),t=await e.ccusageCollection.findMany({where:{id:{startsWith:"sidebar-usage:"}},select:{id:!0}});if(!t.length)return;let r=t.map(({id:e})=>e);await e.agentJob.deleteMany({where:{ccusageCollectionId:{in:r}}}),await e.ccusageCollection.deleteMany({where:{id:{in:r}}})}async status(){let e=await (0,t1.getPrismaClient)(),t=n7(),[r,i,a,n,s,o,l]=await Promise.all([e.sidebarUsageSummary.findUnique({where:{id:"default"}}),e.agentRun.count({where:{kind:"PLAN",archivedAt:null,status:"IN_PROGRESS",attempts:{some:{status:{in:["STARTING","RUNNING"]},supersededAt:null}}}}),e.agentRun.count({where:{kind:"SESSION",archivedAt:null,status:"IN_PROGRESS",attempts:{some:{status:{in:["STARTING","RUNNING"]},supersededAt:null}}}}),e.build.count({where:{status:{in:["PREPARING","RUNNING"]}}}),e.workflowRun.count({where:{archivedAt:null,status:"RUNNING"}}),e.commandRun.count({where:{archivedAt:null,status:"RUNNING"}}),this.diskSpace.overview()]),c=r?.period===t?{totalCost:r.totalCost,collectedAt:r.collectedAt}:null;if(!c){let e=await this.latestSuccessfulUsage(t);e&&(c=e,this.persistUsage(t,e.totalCost,e.collectedAt)),this.runUsagePoll()}return{usageToday:{totalCost:c?.totalCost??null,collectedAt:c?.collectedAt.toISOString()??null},activity:{plans:i,sessions:a,builds:n,workflows:s,commands:o},diskSpace:l}}subscribe(){return ie.agentEventBus.iterate(ie.SIDEBAR_STATUS_CHANGED_TOPIC)}publish(){ie.agentEventBus.publish(ie.SIDEBAR_STATUS_CHANGED_TOPIC,{sidebarStatusChanged:!0})}}var st=e.i(499162);let sr=`
632
+ `)&&-1===e.indexOf("\r")){s.push(e),o+=e.length,m();return}s.push(e);let t=s.join("");s.length=0,o=0;let r=f(t);""!==r&&(s.push(r),o=r.length),m()},reset:function(e={}){if(e.consume&&s.length>0){let e=s.join("");g(e,0,e.length)}l=!0,c=void 0,u="",d=0,p=void 0,s.length=0,o=0,h=!1}}}function ew(e,t,r){return 100===r&&97===e.charCodeAt(t+1)&&116===e.charCodeAt(t+2)&&97===e.charCodeAt(t+3)&&58===e.charCodeAt(t+4)}function eb(e,t,r){return 101===r&&118===e.charCodeAt(t+1)&&101===e.charCodeAt(t+2)&&110===e.charCodeAt(t+3)&&116===e.charCodeAt(t+4)&&58===e.charCodeAt(t+5)}class ev extends Event{constructor(e,t){var r,i;super(e),this.code=null!=(r=null==t?void 0:t.code)?r:void 0,this.message=null!=(i=null==t?void 0:t.message)?i:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,t,r){return r(ek(this),t)}[Symbol.for("Deno.customInspect")](e,t){return e(ek(this),t)}}function ek(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var eE,eS,eI,eA,ex,e_,eC,eR,eT,eD,eN,eO,eP,eL,eB,eU,ej,eM,eq,e$,eF,eG,eK,eH=e=>{throw TypeError(e)},eV=(e,t,r)=>t.has(e)||eH("Cannot "+r),eW=(e,t,r)=>(eV(e,t,"read from private field"),r?r.call(e):t.get(e)),eJ=(e,t,r)=>t.has(e)?eH("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),ez=(e,t,r,i)=>(eV(e,t,"write to private field"),t.set(e,r),r),eY=(e,t,r)=>(eV(e,t,"access private method"),r);class eZ extends EventTarget{constructor(e,t){var r,i;super(),eJ(this,eL),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,eJ(this,eE),eJ(this,eS),eJ(this,eI),eJ(this,eA),eJ(this,ex),eJ(this,e_),eJ(this,eC),eJ(this,eR,null),eJ(this,eT),eJ(this,eD),eJ(this,eN,null),eJ(this,eO,null),eJ(this,eP,null),eJ(this,eU,async e=>{var t;eW(this,eD).reset();let{body:r,redirected:i,status:a,headers:n}=e;if(204===a){eY(this,eL,eF).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(i?ez(this,eI,new URL(e.url)):ez(this,eI,void 0),200!==a)return void eY(this,eL,eF).call(this,`Non-200 status code (${a})`,a);if(!(n.get("content-type")||"").startsWith("text/event-stream"))return void eY(this,eL,eF).call(this,'Invalid content type, expected "text/event-stream"',a);if(eW(this,eE)===this.CLOSED)return;ez(this,eE,this.OPEN);let s=new Event("open");if(null==(t=eW(this,eP))||t.call(this,s),this.dispatchEvent(s),"object"!=typeof r||!r||!("getReader"in r)){eY(this,eL,eF).call(this,"Invalid response body, expected a web ReadableStream",a),this.close();return}let o=new TextDecoder,l=r.getReader(),c=!0;do{let{done:e,value:t}=await l.read();t&&eW(this,eD).feed(o.decode(t,{stream:!e})),e&&(c=!1,eW(this,eD).reset(),eY(this,eL,eG).call(this))}while(c)}),eJ(this,ej,e=>{ez(this,eT,void 0),"AbortError"!==e.name&&"aborted"!==e.type&&eY(this,eL,eG).call(this,function e(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(e).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${e(t.cause)}`:t.message:`${t}`}(e))}),eJ(this,eq,e=>{"string"==typeof e.id&&ez(this,eR,e.id);let t=new MessageEvent(e.event||"message",{data:e.data,origin:eW(this,eI)?eW(this,eI).origin:eW(this,eS).origin,lastEventId:e.id||""});eW(this,eO)&&(!e.event||"message"===e.event)&&eW(this,eO).call(this,t),this.dispatchEvent(t)}),eJ(this,e$,e=>{ez(this,e_,e)}),eJ(this,eK,()=>{ez(this,eC,void 0),eW(this,eE)===this.CONNECTING&&eY(this,eL,eB).call(this)});try{if(e instanceof URL)ez(this,eS,e);else if("string"==typeof e)ez(this,eS,new URL(e,function(){let e="document"in globalThis?globalThis.document:void 0;return e&&"object"==typeof e&&"baseURI"in e&&"string"==typeof e.baseURI?e.baseURI:void 0}()));else throw Error("Invalid URL")}catch{throw function(e){let t=globalThis.DOMException;return"function"==typeof t?new t(e,"SyntaxError"):SyntaxError(e)}("An invalid or illegal string was specified")}ez(this,eD,ey({onEvent:eW(this,eq),onRetry:eW(this,e$)})),ez(this,eE,this.CONNECTING),ez(this,e_,3e3),ez(this,ex,null!=(r=null==t?void 0:t.fetch)?r:globalThis.fetch),ez(this,eA,null!=(i=null==t?void 0:t.withCredentials)&&i),eY(this,eL,eB).call(this)}get readyState(){return eW(this,eE)}get url(){return eW(this,eS).href}get withCredentials(){return eW(this,eA)}get onerror(){return eW(this,eN)}set onerror(e){ez(this,eN,e)}get onmessage(){return eW(this,eO)}set onmessage(e){ez(this,eO,e)}get onopen(){return eW(this,eP)}set onopen(e){ez(this,eP,e)}addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}close(){eW(this,eC)&&clearTimeout(eW(this,eC)),eW(this,eE)!==this.CLOSED&&(eW(this,eT)&&eW(this,eT).abort(),ez(this,eE,this.CLOSED),ez(this,eT,void 0))}}function eQ(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function eX(e=fetch,t){return t?async(r,i)=>e(r,{...t,...i,headers:i?.headers?{...eQ(t.headers),...eQ(i.headers)}:t.headers}):e}async function e0(e){return(await t).getRandomValues(new Uint8Array(e))}async function e1(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=256-256%t.length,i="";for(;i.length<e;)for(let a of(await e0(e-i.length)))a<r&&(i+=t[a%t.length]);return i}async function e2(e){return await e1(e)}async function e3(e){return btoa(String.fromCharCode(...new Uint8Array(await (await t).subtle.digest("SHA-256",new TextEncoder().encode(e))))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function e4(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await e2(e),r=await e3(t);return{code_verifier:t,code_challenge:r}}eE=new WeakMap,eS=new WeakMap,eI=new WeakMap,eA=new WeakMap,ex=new WeakMap,e_=new WeakMap,eC=new WeakMap,eR=new WeakMap,eT=new WeakMap,eD=new WeakMap,eN=new WeakMap,eO=new WeakMap,eP=new WeakMap,eL=new WeakSet,eB=function(){ez(this,eE,this.CONNECTING),ez(this,eT,new AbortController),eW(this,ex)(eW(this,eS),eY(this,eL,eM).call(this)).then(eW(this,eU)).catch(eW(this,ej))},eU=new WeakMap,ej=new WeakMap,eM=function(){var e;let t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...eW(this,eR)?{"Last-Event-ID":eW(this,eR)}:void 0},cache:"no-store",signal:null==(e=eW(this,eT))?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},eq=new WeakMap,e$=new WeakMap,eF=function(e,t){var r;eW(this,eE)!==this.CLOSED&&ez(this,eE,this.CLOSED);let i=new ev("error",{code:t,message:e});null==(r=eW(this,eN))||r.call(this,i),this.dispatchEvent(i)},eG=function(e,t){var r;if(eW(this,eE)===this.CLOSED)return;ez(this,eE,this.CONNECTING);let i=new ev("error",{code:t,message:e});null==(r=eW(this,eN))||r.call(this,i),this.dispatchEvent(i),ez(this,eC,setTimeout(eW(this,eK),eW(this,e_)))},eK=new WeakMap,eZ.CONNECTING=0,eZ.OPEN=1,eZ.CLOSED=2,t=globalThis.crypto?.webcrypto??globalThis.crypto??e.A(70729).then(e=>e.webcrypto);var e6=e.i(907855),e8=e.i(733137),e5=e.i(127438),e9=e.i(754257);let e7=e6.url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:e8.ZodIssueCode.custom,message:"URL must be parseable",fatal:!0}),e5.NEVER}).refine(e=>{let t=new URL(e);return"javascript:"!==t.protocol&&"data:"!==t.protocol&&"vbscript:"!==t.protocol},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),te=e6.looseObject({resource:e6.string().url(),authorization_servers:e6.array(e7).optional(),jwks_uri:e6.string().url().optional(),scopes_supported:e6.array(e6.string()).optional(),bearer_methods_supported:e6.array(e6.string()).optional(),resource_signing_alg_values_supported:e6.array(e6.string()).optional(),resource_name:e6.string().optional(),resource_documentation:e6.string().optional(),resource_policy_uri:e6.string().url().optional(),resource_tos_uri:e6.string().url().optional(),tls_client_certificate_bound_access_tokens:e6.boolean().optional(),authorization_details_types_supported:e6.array(e6.string()).optional(),dpop_signing_alg_values_supported:e6.array(e6.string()).optional(),dpop_bound_access_tokens_required:e6.boolean().optional()}),tt=e6.looseObject({issuer:e6.string(),authorization_endpoint:e7,token_endpoint:e7,registration_endpoint:e7.optional(),scopes_supported:e6.array(e6.string()).optional(),response_types_supported:e6.array(e6.string()),response_modes_supported:e6.array(e6.string()).optional(),grant_types_supported:e6.array(e6.string()).optional(),token_endpoint_auth_methods_supported:e6.array(e6.string()).optional(),token_endpoint_auth_signing_alg_values_supported:e6.array(e6.string()).optional(),service_documentation:e7.optional(),revocation_endpoint:e7.optional(),revocation_endpoint_auth_methods_supported:e6.array(e6.string()).optional(),revocation_endpoint_auth_signing_alg_values_supported:e6.array(e6.string()).optional(),introspection_endpoint:e6.string().optional(),introspection_endpoint_auth_methods_supported:e6.array(e6.string()).optional(),introspection_endpoint_auth_signing_alg_values_supported:e6.array(e6.string()).optional(),code_challenge_methods_supported:e6.array(e6.string()).optional(),client_id_metadata_document_supported:e6.boolean().optional()}),tr=e6.looseObject({issuer:e6.string(),authorization_endpoint:e7,token_endpoint:e7,userinfo_endpoint:e7.optional(),jwks_uri:e7,registration_endpoint:e7.optional(),scopes_supported:e6.array(e6.string()).optional(),response_types_supported:e6.array(e6.string()),response_modes_supported:e6.array(e6.string()).optional(),grant_types_supported:e6.array(e6.string()).optional(),acr_values_supported:e6.array(e6.string()).optional(),subject_types_supported:e6.array(e6.string()),id_token_signing_alg_values_supported:e6.array(e6.string()),id_token_encryption_alg_values_supported:e6.array(e6.string()).optional(),id_token_encryption_enc_values_supported:e6.array(e6.string()).optional(),userinfo_signing_alg_values_supported:e6.array(e6.string()).optional(),userinfo_encryption_alg_values_supported:e6.array(e6.string()).optional(),userinfo_encryption_enc_values_supported:e6.array(e6.string()).optional(),request_object_signing_alg_values_supported:e6.array(e6.string()).optional(),request_object_encryption_alg_values_supported:e6.array(e6.string()).optional(),request_object_encryption_enc_values_supported:e6.array(e6.string()).optional(),token_endpoint_auth_methods_supported:e6.array(e6.string()).optional(),token_endpoint_auth_signing_alg_values_supported:e6.array(e6.string()).optional(),display_values_supported:e6.array(e6.string()).optional(),claim_types_supported:e6.array(e6.string()).optional(),claims_supported:e6.array(e6.string()).optional(),service_documentation:e6.string().optional(),claims_locales_supported:e6.array(e6.string()).optional(),ui_locales_supported:e6.array(e6.string()).optional(),claims_parameter_supported:e6.boolean().optional(),request_parameter_supported:e6.boolean().optional(),request_uri_parameter_supported:e6.boolean().optional(),require_request_uri_registration:e6.boolean().optional(),op_policy_uri:e7.optional(),op_tos_uri:e7.optional(),client_id_metadata_document_supported:e6.boolean().optional()}),ti=e6.object({...tr.shape,...tt.pick({code_challenge_methods_supported:!0}).shape}),ta=e6.object({access_token:e6.string(),id_token:e6.string().optional(),token_type:e6.string(),expires_in:e9.coerce.number().optional(),scope:e6.string().optional(),refresh_token:e6.string().optional()}).strip(),tn=e6.object({error:e6.string(),error_description:e6.string().optional(),error_uri:e6.string().optional()}),ts=e7.optional().or(e6.literal("").transform(()=>void 0)),to=e6.object({redirect_uris:e6.array(e7),token_endpoint_auth_method:e6.string().optional(),grant_types:e6.array(e6.string()).optional(),response_types:e6.array(e6.string()).optional(),client_name:e6.string().optional(),client_uri:e7.optional(),logo_uri:ts,scope:e6.string().optional(),contacts:e6.array(e6.string()).optional(),tos_uri:ts,policy_uri:e6.string().optional(),jwks_uri:e7.optional(),jwks:e6.any().optional(),software_id:e6.string().optional(),software_version:e6.string().optional(),software_statement:e6.string().optional()}).strip(),tl=e6.object({client_id:e6.string(),client_secret:e6.string().optional(),client_id_issued_at:e6.number().optional(),client_secret_expires_at:e6.number().optional()}).strip(),tc=to.merge(tl);e6.object({error:e6.string(),error_description:e6.string().optional()}).strip(),e6.object({token:e6.string(),token_type_hint:e6.string().optional()}).strip();class tu extends Error{constructor(e,t){super(e),this.errorUri=t,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}}class td extends tu{}td.errorCode="invalid_request";class tp extends tu{}tp.errorCode="invalid_client";class th extends tu{}th.errorCode="invalid_grant";class tm extends tu{}tm.errorCode="unauthorized_client";class tf extends tu{}tf.errorCode="unsupported_grant_type";class tg extends tu{}tg.errorCode="invalid_scope";class ty extends tu{}ty.errorCode="access_denied";class tw extends tu{}tw.errorCode="server_error";class tb extends tu{}tb.errorCode="temporarily_unavailable";class tv extends tu{}tv.errorCode="unsupported_response_type";class tk extends tu{}tk.errorCode="unsupported_token_type";class tE extends tu{}tE.errorCode="invalid_token";class tS extends tu{}tS.errorCode="method_not_allowed";class tI extends tu{}tI.errorCode="too_many_requests";class tA extends tu{}tA.errorCode="invalid_client_metadata";class tx extends tu{}tx.errorCode="insufficient_scope";class t_ extends tu{}t_.errorCode="invalid_target";let tC={[td.errorCode]:td,[tp.errorCode]:tp,[th.errorCode]:th,[tm.errorCode]:tm,[tf.errorCode]:tf,[tg.errorCode]:tg,[ty.errorCode]:ty,[tw.errorCode]:tw,[tb.errorCode]:tb,[tv.errorCode]:tv,[tk.errorCode]:tk,[tE.errorCode]:tE,[tS.errorCode]:tS,[tI.errorCode]:tI,[tA.errorCode]:tA,[tx.errorCode]:tx,[t_.errorCode]:t_};class tR extends Error{constructor(e){super(e??"Unauthorized")}}let tT="code",tD="S256";async function tN(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let{error:e,error_description:t,error_uri:i}=tn.parse(JSON.parse(r));return new(tC[e]||tw)(t||"",i)}catch(e){return new tw(`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${e}. Raw body: ${r}`)}}async function tO(e,t){try{return await tP(e,t)}catch(r){if(r instanceof tp||r instanceof tm)return await e.invalidateCredentials?.("all"),await tP(e,t);if(r instanceof th)return await e.invalidateCredentials?.("tokens"),await tP(e,t);throw r}}async function tP(e,{serverUrl:t,authorizationCode:r,scope:i,resourceMetadataUrl:a,fetchFn:n}){let s,o,l,c=await e.discoveryState?.(),u=a;if(!u&&c?.resourceMetadataUrl&&(u=new URL(c.resourceMetadataUrl)),c?.authorizationServerUrl){if(o=c.authorizationServerUrl,s=c.resourceMetadata,l=c.authorizationServerMetadata??await tF(o,{fetchFn:n}),!s)try{s=await tj(t,{resourceMetadataUrl:u},n)}catch{}(l!==c.authorizationServerMetadata||s!==c.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(o),resourceMetadataUrl:u?.toString(),resourceMetadata:s,authorizationServerMetadata:l})}else{let r=await tG(t,{resourceMetadataUrl:u,fetchFn:n});o=r.authorizationServerUrl,l=r.authorizationServerMetadata,s=r.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(o),resourceMetadataUrl:u?.toString(),resourceMetadata:s,authorizationServerMetadata:l})}let d=await tL(t,e,s),p=i||s?.scopes_supported?.join(" ")||e.clientMetadata.scope,h=await Promise.resolve(e.clientInformation());if(!h){if(void 0!==r)throw Error("Existing OAuth client information is required when exchanging an authorization code");let t=l?.client_id_metadata_document_supported===!0,i=e.clientMetadataUrl;if(i&&!function(e){if(!e)return!1;try{let t=new URL(e);return"https:"===t.protocol&&"/"!==t.pathname}catch{return!1}}(i))throw new tA(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${i}`);if(t&&i)h={client_id:i},await e.saveClientInformation?.(h);else{if(!e.saveClientInformation)throw Error("OAuth client information must be saveable for dynamic registration");let t=await tJ(o,{metadata:l,clientMetadata:e.clientMetadata,scope:p,fetchFn:n});await e.saveClientInformation(t),h=t}}let m=!e.redirectUrl;if(void 0!==r||m){let t=await tW(e,o,{metadata:l,resource:d,authorizationCode:r,fetchFn:n});return await e.saveTokens(t),"AUTHORIZED"}let f=await e.tokens();if(f?.refresh_token)try{let t=await tV(o,{metadata:l,clientInformation:h,refreshToken:f.refresh_token,resource:d,addClientAuthentication:e.addClientAuthentication,fetchFn:n});return await e.saveTokens(t),"AUTHORIZED"}catch(e){if(!(e instanceof tu)||e instanceof tw);else throw e}let g=e.state?await e.state():void 0,{authorizationUrl:y,codeVerifier:w}=await tK(o,{metadata:l,clientInformation:h,state:g,redirectUrl:e.redirectUrl,scope:p,resource:d});return await e.saveCodeVerifier(w),await e.redirectToAuthorization(y),"REDIRECT"}async function tL(e,t,r){let i,a=((i=new URL("string"==typeof e?e:e.href)).hash="",i);if(t.validateResourceURL)return await t.validateResourceURL(a,r?.resource);if(r){if(!function({requestedResource:e,configuredResource:t}){let r=new URL("string"==typeof e?e:e.href),i=new URL("string"==typeof t?t:t.href);if(r.origin!==i.origin||r.pathname.length<i.pathname.length)return!1;let a=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",n=i.pathname.endsWith("/")?i.pathname:i.pathname+"/";return a.startsWith(n)}({requestedResource:a,configuredResource:r.resource}))throw Error(`Protected resource ${r.resource} does not match expected ${a} (or origin)`);return new URL(r.resource)}}function tB(e){let t,r=e.headers.get("WWW-Authenticate");if(!r)return{};let[i,a]=r.split(" ");if("bearer"!==i.toLowerCase()||!a)return{};let n=tU(e,"resource_metadata")||void 0;if(n)try{t=new URL(n)}catch{}return{resourceMetadataUrl:t,scope:tU(e,"scope")||void 0,error:tU(e,"error")||void 0}}function tU(e,t){let r=e.headers.get("WWW-Authenticate");if(!r)return null;let i=RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),a=r.match(i);return a?a[1]||a[2]:null}async function tj(e,t,r=fetch){let i=await t$(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!i||404===i.status)throw await i?.body?.cancel(),Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!i.ok)throw await i.body?.cancel(),Error(`HTTP ${i.status} trying to load well-known OAuth protected resource metadata.`);return te.parse(await i.json())}async function tM(e,t,r=fetch){try{return await r(e,{headers:t})}catch(i){if(i instanceof TypeError)if(t)return tM(e,void 0,r);else return;throw i}}async function tq(e,t,r=fetch){return await tM(e,{"MCP-Protocol-Version":t},r)}async function t$(e,t,r,i){var a,n;let s,o=new URL(e),l=i?.protocolVersion??E.LATEST_PROTOCOL_VERSION;i?.metadataUrl?s=new URL(i.metadataUrl):(s=new URL(function(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}(t,o.pathname),i?.metadataServerUrl??o)).search=o.search;let c=await tq(s,l,r);if(!i?.metadataUrl&&(a=c,n=o.pathname,!a||a.status>=400&&a.status<500&&"/"!==n)){let e=new URL(`/.well-known/${t}`,o);c=await tq(e,l,r)}return c}async function tF(e,{fetchFn:t=fetch,protocolVersion:r=E.LATEST_PROTOCOL_VERSION}={}){let i={"MCP-Protocol-Version":r,Accept:"application/json"};for(let{url:r,type:a}of function(e){let t="string"==typeof e?new URL(e):e,r="/"!==t.pathname,i=[];if(!r)return i.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),i.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),i;let a=t.pathname;return a.endsWith("/")&&(a=a.slice(0,-1)),i.push({url:new URL(`/.well-known/oauth-authorization-server${a}`,t.origin),type:"oauth"}),i.push({url:new URL(`/.well-known/openid-configuration${a}`,t.origin),type:"oidc"}),i.push({url:new URL(`${a}/.well-known/openid-configuration`,t.origin),type:"oidc"}),i}(e)){let e=await tM(r,i,t);if(e){if(!e.ok){if(await e.body?.cancel(),e.status>=400&&e.status<500)continue;throw Error(`HTTP ${e.status} trying to load ${"oauth"===a?"OAuth":"OpenID provider"} metadata from ${r}`)}if("oauth"===a)return tt.parse(await e.json());return ti.parse(await e.json())}}}async function tG(e,t){let r,i;try{(r=await tj(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn)).authorization_servers&&r.authorization_servers.length>0&&(i=r.authorization_servers[0])}catch{}i||(i=String(new URL("/",e)));let a=await tF(i,{fetchFn:t?.fetchFn});return{authorizationServerUrl:i,authorizationServerMetadata:a,resourceMetadata:r}}async function tK(e,{metadata:t,clientInformation:r,redirectUrl:i,scope:a,state:n,resource:s}){let o;if(t){if(o=new URL(t.authorization_endpoint),!t.response_types_supported.includes(tT))throw Error(`Incompatible auth server: does not support response type ${tT}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(tD))throw Error(`Incompatible auth server: does not support code challenge method ${tD}`)}else o=new URL("/authorize",e);let l=await e4(),c=l.code_verifier,u=l.code_challenge;return o.searchParams.set("response_type",tT),o.searchParams.set("client_id",r.client_id),o.searchParams.set("code_challenge",u),o.searchParams.set("code_challenge_method",tD),o.searchParams.set("redirect_uri",String(i)),n&&o.searchParams.set("state",n),a&&o.searchParams.set("scope",a),a?.includes("offline_access")&&o.searchParams.append("prompt","consent"),s&&o.searchParams.set("resource",s.href),{authorizationUrl:o,codeVerifier:c}}async function tH(e,{metadata:t,tokenRequestParams:r,clientInformation:i,addClientAuthentication:a,resource:n,fetchFn:s}){var o,l;let c,u=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),d=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});n&&r.set("resource",n.href),a?await a(d,r,u,t):i&&function(e,t,r,i){let{client_id:a,client_secret:n}=t;switch(e){case"client_secret_basic":var s,o,l,c,u=a,d=n,p=r;if(!d)throw Error("client_secret_basic authentication requires a client_secret");let h=btoa(`${u}:${d}`);p.set("Authorization",`Basic ${h}`);return;case"client_secret_post":s=a,o=n,(l=i).set("client_id",s),o&&l.set("client_secret",o);return;case"none":c=a,i.set("client_id",c);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}((o=i,l=t?.token_endpoint_auth_methods_supported??[],c=void 0!==o.client_secret,"token_endpoint_auth_method"in o&&o.token_endpoint_auth_method&&["client_secret_basic","client_secret_post","none"].includes(o.token_endpoint_auth_method)&&(0===l.length||l.includes(o.token_endpoint_auth_method))?o.token_endpoint_auth_method:0===l.length?c?"client_secret_basic":"none":c&&l.includes("client_secret_basic")?"client_secret_basic":c&&l.includes("client_secret_post")?"client_secret_post":l.includes("none")?"none":c?"client_secret_post":"none"),i,d,r);let p=await (s??fetch)(u,{method:"POST",headers:d,body:r});if(!p.ok)throw await tN(p);return ta.parse(await p.json())}async function tV(e,{metadata:t,clientInformation:r,refreshToken:i,resource:a,addClientAuthentication:n,fetchFn:s}){let o=new URLSearchParams({grant_type:"refresh_token",refresh_token:i});return{refresh_token:i,...await tH(e,{metadata:t,tokenRequestParams:o,clientInformation:r,addClientAuthentication:n,resource:a,fetchFn:s})}}async function tW(e,t,{metadata:r,resource:i,authorizationCode:a,fetchFn:n}={}){let s,o=e.clientMetadata.scope;if(e.prepareTokenRequest&&(s=await e.prepareTokenRequest(o)),!s){if(!a)throw Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw Error("redirectUrl is required for authorization_code flow");s=new URLSearchParams({grant_type:"authorization_code",code:a,code_verifier:await e.codeVerifier(),redirect_uri:String(e.redirectUrl)})}return tH(t,{metadata:r,tokenRequestParams:s,clientInformation:await e.clientInformation()??void 0,addClientAuthentication:e.addClientAuthentication,resource:i,fetchFn:n})}async function tJ(e,{metadata:t,clientMetadata:r,scope:i,fetchFn:a}){let n;if(t){if(!t.registration_endpoint)throw Error("Incompatible auth server: does not support dynamic client registration");n=new URL(t.registration_endpoint)}else n=new URL("/register",e);let s=await (a??fetch)(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...void 0!==i?{scope:i}:{}})});if(!s.ok)throw await tN(s);return tc.parse(await s.json())}class tz extends Error{constructor(e,t,r){super(`SSE error: ${t}`),this.code=e,this.event=r}}class tY{constructor(e,t){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=t?.eventSourceInit,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=eX(t?.fetch,t?.requestInit)}async _authThenStart(){let e;if(!this._authProvider)throw new tR("No auth provider");try{e=await tO(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(e){throw this.onerror?.(e),e}if("AUTHORIZED"!==e)throw new tR;return await this._startOrAuth()}async _commonHeaders(){let e={};if(this._authProvider){let t=await this._authProvider.tokens();t&&(e.Authorization=`Bearer ${t.access_token}`)}this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let t=eQ(this._requestInit?.headers);return new Headers({...e,...t})}_startOrAuth(){let e=this?._eventSourceInit?.fetch??this._fetch??fetch;return new Promise((t,r)=>{this._eventSource=new eZ(this._url.href,{...this._eventSourceInit,fetch:async(t,r)=>{let i=await this._commonHeaders();i.set("Accept","text/event-stream");let a=await e(t,{...r,headers:i});if(401===a.status&&a.headers.has("www-authenticate")){let{resourceMetadataUrl:e,scope:t}=tB(a);this._resourceMetadataUrl=e,this._scope=t}return a}}),this._abortController=new AbortController,this._eventSource.onerror=e=>{if(401===e.code&&this._authProvider)return void this._authThenStart().then(t,r);let i=new tz(e.code,e.message,e);r(i),this.onerror?.(i)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",e=>{try{if(this._endpoint=new URL(e.data,this._url),this._endpoint.origin!==this._url.origin)throw Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(e){r(e),this.onerror?.(e),this.close();return}t()}),this._eventSource.onmessage=e=>{let t;try{t=E.JSONRPCMessageSchema.parse(JSON.parse(e.data))}catch(e){this.onerror?.(e);return}this.onmessage?.(t)}})}async start(){if(this._eventSource)throw Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new tR("No auth provider");if("AUTHORIZED"!==await tO(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit}))throw new tR("Failed to authorize")}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(e){if(!this._endpoint)throw Error("Not connected");try{let t=await this._commonHeaders();t.set("content-type","application/json");let r={...this._requestInit,method:"POST",headers:t,body:JSON.stringify(e),signal:this._abortController?.signal},i=await (this._fetch??fetch)(this._endpoint,r);if(!i.ok){let t=await i.text().catch(()=>null);if(401===i.status&&this._authProvider){let{resourceMetadataUrl:t,scope:r}=tB(i);this._resourceMetadataUrl=t,this._scope=r;let a=await tO(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit});if("AUTHORIZED"!==a)throw new tR;return this.send(e)}throw Error(`Error POSTing to endpoint (HTTP ${i.status}): ${t}`)}await i.body?.cancel()}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}}class tZ extends TransformStream{constructor({onError:e,onRetry:t,onComment:r,maxBufferSize:i}={}){let a;super({start(n){a=ey({onEvent:e=>{n.enqueue(e)},onError(t){"function"==typeof e&&e(t),("terminate"===e||"max-buffer-size-exceeded"===t.type)&&n.error(t)},onRetry:t,onComment:r,maxBufferSize:i})},transform(e){a.feed(e)}})}}let tQ={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class tX extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}}class t0{constructor(e,t){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=eX(t?.fetch,t?.requestInit),this._sessionId=t?.sessionId,this._reconnectionOptions=t?.reconnectionOptions??tQ}async _authThenStart(){let e;if(!this._authProvider)throw new tR("No auth provider");try{e=await tO(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(e){throw this.onerror?.(e),e}if("AUTHORIZED"!==e)throw new tR;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let t=await this._authProvider.tokens();t&&(e.Authorization=`Bearer ${t.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let t=eQ(this._requestInit?.headers);return new Headers({...e,...t})}async _startOrAuthSse(e){let{resumptionToken:t}=e;try{let r=await this._commonHeaders();r.set("Accept","text/event-stream"),t&&r.set("last-event-id",t);let i=await (this._fetch??fetch)(this._url,{method:"GET",headers:r,signal:this._abortController?.signal});if(!i.ok){if(await i.body?.cancel(),401===i.status&&this._authProvider)return await this._authThenStart();if(405===i.status)return;throw new tX(i.status,`Failed to open SSE stream: ${i.statusText}`)}this._handleSseStream(i.body,e,!0)}catch(e){throw this.onerror?.(e),e}}_getNextReconnectionDelay(e){return void 0!==this._serverRetryMs?this._serverRetryMs:Math.min(this._reconnectionOptions.initialReconnectionDelay*Math.pow(this._reconnectionOptions.reconnectionDelayGrowFactor,e),this._reconnectionOptions.maxReconnectionDelay)}_scheduleReconnection(e,t=0){let r=this._reconnectionOptions.maxRetries;if(t>=r)return void this.onerror?.(Error(`Maximum reconnection attempts (${r}) exceeded.`));let i=this._getNextReconnectionDelay(t);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(r=>{this.onerror?.(Error(`Failed to reconnect SSE stream: ${r instanceof Error?r.message:String(r)}`)),this._scheduleReconnection(e,t+1)})},i)}_handleSseStream(e,t,r){let i;if(!e)return;let{onresumptiontoken:a,replayMessageId:n}=t,s=!1,o=!1;(async()=>{try{let t=e.pipeThrough(new TextDecoderStream).pipeThrough(new tZ({onRetry:e=>{this._serverRetryMs=e}})).getReader();for(;;){let{value:e,done:r}=await t.read();if(r)break;if((e.id&&(i=e.id,s=!0,a?.(e.id)),e.data)&&(!e.event||"message"===e.event))try{let t=E.JSONRPCMessageSchema.parse(JSON.parse(e.data));(0,E.isJSONRPCResultResponse)(t)&&(o=!0,void 0!==n&&(t.id=n)),this.onmessage?.(t)}catch(e){this.onerror?.(e)}}(r||s)&&!o&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:i,onresumptiontoken:a,replayMessageId:n},0)}catch(e){if(this.onerror?.(Error(`SSE stream disconnected: ${e}`)),(r||s)&&!o&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:i,onresumptiontoken:a,replayMessageId:n},0)}catch(e){this.onerror?.(Error(`Failed to reconnect: ${e instanceof Error?e.message:String(e)}`))}}})()}async start(){if(this._abortController)throw Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new tR("No auth provider");if("AUTHORIZED"!==await tO(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit}))throw new tR("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(e,t){try{let{resumptionToken:r,onresumptiontoken:i}=t||{};if(r)return void this._startOrAuthSse({resumptionToken:r,replayMessageId:(0,E.isJSONRPCRequest)(e)?e.id:void 0}).catch(e=>this.onerror?.(e));let a=await this._commonHeaders();a.set("content-type","application/json"),a.set("accept","application/json, text/event-stream");let n={...this._requestInit,method:"POST",headers:a,body:JSON.stringify(e),signal:this._abortController?.signal},s=await (this._fetch??fetch)(this._url,n),o=s.headers.get("mcp-session-id");if(o&&(this._sessionId=o),!s.ok){let t=await s.text().catch(()=>null);if(401===s.status&&this._authProvider){if(this._hasCompletedAuthFlow)throw new tX(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:t,scope:r}=tB(s);this._resourceMetadataUrl=t,this._scope=r;let i=await tO(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit});if("AUTHORIZED"!==i)throw new tR;return this._hasCompletedAuthFlow=!0,this.send(e)}if(403===s.status&&this._authProvider){let{resourceMetadataUrl:t,scope:r,error:i}=tB(s);if("insufficient_scope"===i){let i=s.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===i)throw new tX(403,"Server returned 403 after trying upscoping");r&&(this._scope=r),t&&(this._resourceMetadataUrl=t),this._lastUpscopingHeader=i??void 0;let a=await tO(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch});if("AUTHORIZED"!==a)throw new tR;return this.send(e)}}throw new tX(s.status,`Error POSTing to endpoint: ${t}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,202===s.status){await s.body?.cancel(),(0,E.isInitializedNotification)(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(e=>this.onerror?.(e));return}let l=(Array.isArray(e)?e:[e]).filter(e=>"method"in e&&"id"in e&&void 0!==e.id).length>0,c=s.headers.get("content-type");if(l)if(c?.includes("text/event-stream"))this._handleSseStream(s.body,{onresumptiontoken:i},!1);else if(c?.includes("application/json")){let e=await s.json();for(let t of Array.isArray(e)?e.map(e=>E.JSONRPCMessageSchema.parse(e)):[E.JSONRPCMessageSchema.parse(e)])this.onmessage?.(t)}else throw await s.body?.cancel(),new tX(-1,`Unexpected content type: ${c}`);else await s.body?.cancel()}catch(e){throw this.onerror?.(e),e}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),t={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},r=await (this._fetch??fetch)(this._url,t);if(await r.body?.cancel(),!r.ok&&405!==r.status)throw new tX(r.status,`Failed to terminate session: ${r.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}}var t1=e.i(243783);e.i(582482);var t2=e.i(318905),t3=e.i(91022),t4=e.i(971619);function t6(e){if("string"!=typeof e)return e??null;try{return JSON.parse(e)}catch{return null}}function t8(e){return e instanceof Date?e.toISOString():"string"==typeof e&&Number.isFinite(Date.parse(e))?new Date(e).toISOString():null}function t5(e){let t;return{id:String(e.id),name:String(e.name),hostname:String(e.hostname),version:String(e.version),osVersion:String(e.osVersion),architecture:String(e.architecture),cpuModel:"string"==typeof e.cpuModel?e.cpuModel:null,memoryTotalBytes:"number"==typeof e.memoryTotalBytes?e.memoryTotalBytes:null,memoryFreeBytes:"number"==typeof e.memoryFreeBytes?e.memoryFreeBytes:null,diskTotalBytes:"number"==typeof e.diskTotalBytes?e.diskTotalBytes:null,diskFreeBytes:"number"==typeof e.diskFreeBytes?e.diskFreeBytes:null,capabilities:Array.isArray(e.capabilities)?e.capabilities:t6(e.capabilitiesJson)??[],baseRepoDirectory:"string"==typeof e.baseRepoDirectory?e.baseRepoDirectory:null,derivedDataLocationMode:String(e.derivedDataLocationMode),derivedDataPath:"string"==typeof e.derivedDataPath?e.derivedDataPath:null,buildsDirectory:"string"==typeof e.buildsDirectory?e.buildsDirectory:null,defaultBuildsDirectory:"string"==typeof e.defaultBuildsDirectory?e.defaultBuildsDirectory:null,effectiveBuildsDirectory:(0,t4.effectiveBuildsDirectory)(e),connectionStatus:null!==(t=t8(e.lastSeenAt))&&Date.now()-Date.parse(t)<=(0,a.agentOnlineWindowMs)(e)&&!e.disconnectedAt?"ONLINE":"OFFLINE",ipAddress:"string"==typeof e.ipAddress?e.ipAddress:null,lastSeenAt:t8(e.lastSeenAt),disconnectedAt:t8(e.disconnectedAt),createdAt:t8(e.createdAt),updatedAt:t8(e.updatedAt)}}function t9(e){let t=t5(e);return{agentId:t.id,baseRepoDirectory:t.baseRepoDirectory,buildsDirectory:t.buildsDirectory,defaultBuildsDirectory:t.defaultBuildsDirectory,effectiveBuildsDirectory:t.effectiveBuildsDirectory,derivedDataLocationMode:t.derivedDataLocationMode,derivedDataPath:t.derivedDataPath,updatedAt:t.updatedAt}}function t7(e){return{id:String(e.id),agentId:String(e.agentId),worktreeId:"string"==typeof e.worktreeId?e.worktreeId:null,codebaseId:"string"==typeof e.codebaseId?e.codebaseId:null,kind:String(e.kind),payload:t6(e.payload??e.payloadJson),status:String(e.status),idempotencyKey:String(e.idempotencyKey),result:t6(e.result??e.resultJson),error:"string"==typeof e.error?e.error:null,timeoutSeconds:Number(e.timeoutSeconds),createdAt:t8(e.createdAt),startedAt:t8(e.startedAt),finishedAt:t8(e.finishedAt),updatedAt:t8(e.updatedAt)}}function re(e){return JSON.parse(JSON.stringify(e))}function rt(e){let t=e._count,r=e.versions;return{id:String(e.id),name:String(e.name),description:String(e.description??""),enabled:!0===e.enabled,overlapPolicy:String(e.overlapPolicy),overlapScope:String(e.overlapScope??"WORKTREE"),maxConcurrentRuns:Number(e.maxConcurrentRuns),completionNotificationsEnabled:!1!==e.completionNotificationsEnabled,exclusiveWorktree:!0===e.exclusiveWorktree,worktreeConcurrency:String(e.worktreeConcurrency??(!0===e.exclusiveWorktree?"EXCLUSIVE":"NON_EXCLUSIVE")),blocksGitOperations:!0===e.blocksGitOperations,activeVersionId:"string"==typeof e.activeVersionId?e.activeVersionId:null,draftSchemaVersion:Number(e.draftSchemaVersion),quickActionKind:String(e.quickActionKind??"NONE"),archivedAt:t8(e.archivedAt),versionCount:t?.versions??r?.length??0,runCount:t?.runs??0,createdAt:t8(e.createdAt),updatedAt:t8(e.updatedAt)}}function rr(e){return{id:String(e.id),workflowId:String(e.workflowId),version:Number(e.version),name:String(e.name),description:String(e.description??""),schemaVersion:Number(e.schemaVersion),contentHash:String(e.contentHash),definition:t6(e.definitionJson),publishedAt:t8(e.publishedAt)}}function ri(e){let t=e._count;return{id:String(e.id),displayNumber:Number(e.displayNumber),workflowId:String(e.workflowId),versionId:String(e.versionId),parentRunId:"string"==typeof e.parentRunId?e.parentRunId:null,triggerKind:String(e.triggerKind),triggerSubjectKey:String(e.triggerSubjectKey??""),triggerPayload:t6(e.triggerPayloadJson),status:String(e.status),phase:String(e.phase),generation:Number(e.generation),sessionData:t6(e.sessionDataJson),blockedReason:"string"==typeof e.blockedReason?e.blockedReason:null,error:"string"==typeof e.error?e.error:null,attemptCount:t?.attempts??e.attempts?.length??0,eventCount:t?.events??e.events?.length??0,queuedAt:t8(e.queuedAt),startedAt:t8(e.startedAt),pausedAt:t8(e.pausedAt),finishedAt:t8(e.finishedAt),updatedAt:t8(e.updatedAt)}}let ra=e6.object({}),rn=e6.object({id:e6.string(),name:e6.string(),hostname:e6.string(),version:e6.string(),osVersion:e6.string(),architecture:e6.string(),cpuModel:e6.string().nullable(),memoryTotalBytes:e6.number().nullable(),memoryFreeBytes:e6.number().nullable(),diskTotalBytes:e6.number().nullable(),diskFreeBytes:e6.number().nullable(),capabilities:e6.array(e6.string()),baseRepoDirectory:e6.string().nullable(),derivedDataLocationMode:e6.enum(["DEFAULT","ABSOLUTE","RELATIVE"]),derivedDataPath:e6.string().nullable(),buildsDirectory:e6.string().nullable(),defaultBuildsDirectory:e6.string().nullable(),effectiveBuildsDirectory:e6.string().nullable(),connectionStatus:e6.enum(["ONLINE","OFFLINE"]),ipAddress:e6.string().nullable(),lastSeenAt:e6.string().nullable(),disconnectedAt:e6.string().nullable(),createdAt:e6.string(),updatedAt:e6.string()}),rs=e6.object({agentId:e6.string(),baseRepoDirectory:e6.string().nullable(),buildsDirectory:e6.string().nullable(),defaultBuildsDirectory:e6.string().nullable(),effectiveBuildsDirectory:e6.string().nullable(),derivedDataLocationMode:e6.enum(["DEFAULT","ABSOLUTE","RELATIVE"]),derivedDataPath:e6.string().nullable(),updatedAt:e6.string()}),ro=e6.object({id:e6.string(),agentId:e6.string(),worktreeId:e6.string().nullable(),codebaseId:e6.string().nullable(),kind:e6.string(),payload:e6.unknown(),status:e6.string(),idempotencyKey:e6.string(),result:e6.unknown().nullable(),error:e6.string().nullable(),timeoutSeconds:e6.number().int(),createdAt:e6.string(),startedAt:e6.string().nullable(),finishedAt:e6.string().nullable(),updatedAt:e6.string()}),rl=e6.object({id:e6.string(),jobId:e6.string(),sequence:e6.number().int(),stream:e6.string(),message:e6.string(),createdAt:e6.string()}),rc=e6.object({agentId:e6.string().min(1)});var ru=e.i(190714);async function rd(e,t,r=[]){if(!e||"object"!=typeof e)throw Error(`Service for ${t} is unavailable`);let i=e[t];if("function"!=typeof i)throw Error(`Service operation ${t} is unavailable`);return Reflect.apply(i,e,r)}let rp=/^(?:credentialValue|enrollmentToken|privateKey|privateKeyPem|p12|p12Base64|apnsToken|token|nativeTranscript|nativeSession|nativeSessionFile|rawJson|secretHash|tokenHash)$/i;function rh(e){return e instanceof Date?e.toISOString():Array.isArray(e)?e.map(rh):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).filter(([e])=>!rp.test(e)).map(([e,t])=>[e,rh(t)])):e}function rm(e){let t=e.resultKey??"result";return an({name:e.name,title:e.title,description:e.description,inputSchema:e.inputSchema,outputSchema:e6.object({[t]:e6.unknown()}),annotations:e.annotations??i7,handler:async r=>{let i=await rd(e.service,e.method,e.arguments?.(r)??[r]);return{[t]:e.mapResult?e.mapResult(i):rh(i??null)}}})}let rf=e6.object({});var rg=e.i(184015);let ry=e6.object({}),rw=e6.object({settings:e6.object({refreshIntervalSeconds:e6.number().int(),fetchIntervalSeconds:e6.number().int(),defaultJiraBranchRegex:e6.string(),updatedAt:e6.string()})}),rb=e6.object({agentId:e6.string().min(1),path:e6.string().nullable().default(null),requestId:e6.string().min(1)}),rv=e6.object({listing:e6.unknown()}),rk=e6.object({agentId:e6.string().min(1),folder:e6.string().min(1),requestId:e6.string().min(1)}),rE=e6.object({inspection:e6.unknown()}),rS=e6.object({codebaseIds:e6.array(e6.string().min(1)).min(1).max(500),requestId:e6.string().min(1)}),rI=e6.object({jobs:e6.array(e6.unknown()),skipped:e6.array(e6.object({codebaseId:e6.string(),reason:e6.string()}))}),rA=e6.object({codebaseId:e6.string().min(1),requestId:e6.string().min(1)}),rx=e6.object({state:e6.unknown()}),r_=e6.object({codebaseId:e6.string().min(1),stashOid:e6.string().regex(/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/i),requestId:e6.string().min(1)}),rC=e6.object({diff:e6.unknown()}),rR=e6.object({id:e6.string(),kind:e6.enum(["WRITE","DELETE","ASSUME_UNCHANGED"]),path:e6.string(),contentBase64:e6.string().nullable(),contentSha256:e6.string().nullable(),byteCount:e6.number().int().nonnegative().nullable(),definitionHash:e6.string(),createdAt:e6.string(),updatedAt:e6.string()}),rT=e6.object({repositoryId:e6.string().min(1)}),rD=e=>({id:e.id,kind:e.kind,path:e.path,contentBase64:e.contents?Buffer.from(e.contents).toString("base64"):null,contentSha256:e.contentSha256,byteCount:e.byteCount,definitionHash:e.definitionHash,createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString()});e.i(282790);var rN=e.i(474170);function rO(e){return e instanceof Date?e.toISOString():null}function rP(e){if("string"!=typeof e)return e??null;try{return JSON.parse(e)}catch{return null}}let rL=e6.object({id:e6.string(),clientRegistrationId:e6.string(),tokenMasked:e6.string(),topic:e6.string(),environment:e6.string(),supportedPushTypes:e6.array(e6.string()),displayName:e6.string(),deviceModel:e6.string().nullable(),osVersion:e6.string().nullable(),appVersion:e6.string().nullable(),appBuild:e6.string().nullable(),locale:e6.string().nullable(),pushMagicConfigured:e6.boolean(),status:e6.string(),invalidatedAt:e6.string().nullable(),lastFailureReason:e6.string().nullable(),lastFailureAt:e6.string().nullable(),lastRegisteredAt:e6.string(),lastSentAt:e6.string().nullable(),createdAt:e6.string(),updatedAt:e6.string()}),rB=e6.object({id:e6.string(),name:e6.string(),topic:e6.string(),environment:e6.string(),fingerprint:e6.string(),expiresAt:e6.string().nullable(),lastTestedAt:e6.string().nullable(),lastError:e6.string().nullable(),createdAt:e6.string(),updatedAt:e6.string()}),rU=e6.object({tokenConfigured:e6.boolean(),tokenTeamId:e6.string().nullable(),tokenKeyId:e6.string().nullable(),tokenPrivateKeyFingerprint:e6.string().nullable(),tokenConfiguredAt:e6.string().nullable(),tokenLastUsedAt:e6.string().nullable(),tokenLastError:e6.string().nullable(),certificates:e6.array(rB),updatedAt:e6.string()}),rj=e6.object({id:e6.string(),channelId:e6.string(),bundleId:e6.string(),environment:e6.string(),storagePolicy:e6.string(),createdAt:e6.string(),updatedAt:e6.string()}),rM=e6.object({id:e6.string(),name:e6.string(),editor:e6.unknown(),createdAt:e6.string(),updatedAt:e6.string()}),rq=e6.object({id:e6.string(),registrationId:e6.string().nullable(),topic:e6.string(),environment:e6.string(),status:e6.string(),apnsId:e6.string().nullable(),responseCode:e6.number().int().nullable(),reason:e6.string().nullable(),responseTimestamp:e6.string().nullable(),attempts:e6.number().int(),durationMs:e6.number().int().nullable(),createdAt:e6.string(),startedAt:e6.string().nullable(),finishedAt:e6.string().nullable()}),r$=e6.object({id:e6.string(),requestId:e6.string(),status:e6.string(),editor:e6.unknown(),payload:e6.unknown(),headers:e6.unknown(),targetMode:e6.string(),channelId:e6.string().nullable(),recipientCount:e6.number().int(),successCount:e6.number().int(),failureCount:e6.number().int(),error:e6.string().nullable(),createdAt:e6.string(),startedAt:e6.string().nullable(),finishedAt:e6.string().nullable(),updatedAt:e6.string(),deliveries:e6.array(rq)});function rF(e){return{id:String(e.id),requestId:String(e.requestId),status:String(e.status),editor:rP(e.editor??e.editorJson),payload:rP(e.payload??e.payloadJson),headers:rP(e.headers??e.headersJson),targetMode:String(e.targetMode),channelId:"string"==typeof e.channelId?e.channelId:null,recipientCount:Number(e.recipientCount),successCount:Number(e.successCount),failureCount:Number(e.failureCount),error:"string"==typeof e.error?e.error:null,createdAt:rO(e.createdAt),startedAt:rO(e.startedAt),finishedAt:rO(e.finishedAt),updatedAt:rO(e.updatedAt),deliveries:Array.isArray(e.deliveries)?e.deliveries.map(e=>({id:String(e.id),registrationId:"string"==typeof e.registrationId?e.registrationId:null,topic:String(e.topic),environment:String(e.environment),status:String(e.status),apnsId:"string"==typeof e.apnsId?e.apnsId:null,responseCode:"number"==typeof e.responseCode?e.responseCode:null,reason:"string"==typeof e.reason?e.reason:null,responseTimestamp:rO(e.responseTimestamp),attempts:Number(e.attempts),durationMs:"number"==typeof e.durationMs?e.durationMs:null,createdAt:rO(e.createdAt),startedAt:rO(e.startedAt),finishedAt:rO(e.finishedAt)})):[]}}let rG={requestId:e6.string().min(1),editor:e6.record(e6.string(),e6.unknown())},rK={requestId:e6.string().min(1),presetId:e6.string().min(1)},rH=e6.discriminatedUnion("targetMode",[e6.object({...rG,targetMode:e6.literal("DEVICES"),registrationIds:e6.array(e6.string().min(1)).min(1)}),e6.object({...rG,targetMode:e6.literal("ALL")}),e6.object({...rG,targetMode:e6.literal("BROADCAST"),channelId:e6.string().min(1)}),e6.object({...rG,targetMode:e6.literal("DIRECT"),directToken:e6.string().min(1),directTokenEncoding:e6.enum(["HEX","BASE64"]).default("HEX"),directEnvironment:e6.enum(["SANDBOX","PRODUCTION"]).default("SANDBOX")})]),rV=e6.discriminatedUnion("targetMode",[e6.object({...rK,targetMode:e6.literal("DEVICES"),registrationIds:e6.array(e6.string().min(1)).min(1)}),e6.object({...rK,targetMode:e6.literal("ALL")}),e6.object({...rK,targetMode:e6.literal("BROADCAST"),channelId:e6.string().min(1)}),e6.object({...rK,targetMode:e6.literal("DIRECT"),directToken:e6.string().min(1),directTokenEncoding:e6.enum(["HEX","BASE64"]).default("HEX"),directEnvironment:e6.enum(["SANDBOX","PRODUCTION"]).default("SANDBOX")})]);function rW(e){return{requestId:e.requestId,editor:e.editor,targetMode:e.targetMode,registrationIds:"DEVICES"===e.targetMode?e.registrationIds:void 0,channelId:"BROADCAST"===e.targetMode?e.channelId:void 0,directToken:"DIRECT"===e.targetMode?e.directToken:void 0,directTokenEncoding:"DIRECT"===e.targetMode?e.directTokenEncoding:void 0,directEnvironment:"DIRECT"===e.targetMode?e.directEnvironment:void 0}}let rJ=e6.object({id:e6.string(),entryType:e6.enum(["CONSOLE","ANALYTICS","SEPARATOR"]),clientTime:e6.string(),receivedAt:e6.string(),deviceIp:e6.string().nullable(),message:e6.string().nullable(),level:e6.string().nullable(),category:e6.string().nullable(),eventName:e6.string().nullable(),eventKind:e6.string().nullable(),screenName:e6.string().nullable(),buildId:e6.string().nullable(),sessionId:e6.string().nullable(),attributes:e6.record(e6.string(),e6.unknown()),defaultParameters:e6.record(e6.string(),e6.unknown()),additionalParameters:e6.record(e6.string(),e6.unknown()),highlightColor:e6.string().nullable(),separatorKind:e6.string().nullable(),separatorName:e6.string().nullable()}),rz=e6.object({items:e6.array(rJ),nextCursor:e6.string().nullable(),matchingCount:e6.number().int().nonnegative(),totalCount:e6.number().int().nonnegative()}),rY=rz.extend({separator:rJ.nullable()}),rZ=e6.object({first:e6.number().int().min(1).max(500).default(200),after:e6.string().nullable().default(null)}),rQ=e6.object({field:e6.string().min(1),operator:e6.enum(["CONTAINS","DOES_NOT_CONTAIN","IS","IS_NOT","MATCHES_GLOB","MATCHES_REGEX","NO_REGEX_MATCH","IS_EMPTY","IS_NOT_EMPTY"]),value:e6.string().nullable().optional(),caseSensitive:e6.boolean().default(!1),sources:e6.array(e6.enum(["CONSOLE","ANALYTICS"])).optional()}),rX=e6.object({mode:e6.enum(["ALL","ANY"]),conditions:e6.array(rQ).min(1).max(100)}),r0={search:e6.string().min(1).nullable().optional(),searchMode:e6.enum(["TEXT","GLOB","REGEX"]).default("TEXT"),caseSensitive:e6.boolean().default(!1),quickFilters:e6.record(e6.string(),e6.array(e6.string()).max(500)).nullable().optional(),advancedFilter:rX.nullable().optional()},r1=rZ.extend(r0).refine(r6,{message:"At least one telemetry search filter is required"}),r2=rZ.extend(r0),r3=e6.object({scope:e6.literal("MATCHING"),...r0}).refine(r6,{message:"At least one telemetry search filter is required"}),r4=e6.union([e6.object({scope:e6.literal("IDS"),ids:e6.array(e6.string().min(1)).min(1).max(1e3)}),r3,e6.object({scope:e6.literal("ALL"),includeSeparators:e6.boolean().default(!1)}),e6.object({scope:e6.literal("BEFORE_LATEST_SEPARATOR"),includeSeparators:e6.boolean().default(!1)})]);function r6(e){return!!(e.search||Object.values(e.quickFilters??{}).some(e=>e.length)||e.advancedFilter?.conditions.length)}function r8(e,t){return{view:e,first:t.first,after:t.after,search:t.search,searchMode:t.searchMode??"TEXT",caseSensitive:t.caseSensitive??!1,quickFilters:t.quickFilters,advancedFilter:t.advancedFilter}}function r5(e,t,r){return[an({name:`get_${r.plural}`,title:`Get ${r.label}`,description:`Fetch the newest ${r.label.toLocaleLowerCase()} with cursor pagination.`,inputSchema:rZ,outputSchema:rz,annotations:i7,handler:r=>e.timeline(r8(t,r))}),an({name:`get_${r.singular}`,title:`Get ${r.singular.replaceAll("_"," ")}`,description:`Fetch one ${r.label.toLocaleLowerCase()} item by ID.`,inputSchema:e6.object({id:e6.string().min(1)}),outputSchema:e6.object({entry:rJ.nullable()}),annotations:i7,handler:async({id:r})=>({entry:await e.entry(r,t)})}),an({name:`search_${r.plural}`,title:`Search ${r.label}`,description:"Search with text, glob, regex, quick facets, or advanced filter conditions.",inputSchema:r1,outputSchema:rz,annotations:i7,handler:r=>e.timeline(r8(t,r))}),an({name:`get_${r.plural}_since_latest_separator`,title:`Get ${r.label} since latest separator`,description:"Fetch entries strictly newer than the latest global telemetry separator.",inputSchema:r2,outputSchema:rY,annotations:i7,handler:r=>e.timelineSinceLatestSeparator(r8(t,r))}),an({name:`get_${r.singular}_search_metadata`,title:`Get ${r.label} search metadata`,description:"Get searchable fields and current facet values.",inputSchema:e6.object({}),outputSchema:e6.object({fields:e6.array(e6.string()),facets:e6.record(e6.string(),e6.array(e6.string()))}),annotations:i7,handler:async()=>{let[r,i]=await Promise.all([e.fields(t),e.facets(t)]);return{fields:r,facets:i}}}),an({name:`clear_${r.plural}`,title:`Clear ${r.label}`,description:"Clear explicit IDs, matching entries, all entries, or entries before the latest separator.",inputSchema:r4,outputSchema:e6.object({view:e6.enum(["CONSOLE","ANALYTICS","UNIFIED"]),scope:e6.enum(["IDS","MATCHING","ALL","BEFORE_LATEST_SEPARATOR"]),deletedCount:e6.number().int().nonnegative()}),annotations:at,handler:async r=>{let i="MATCHING"===r.scope?r:null,a=await e.clearScoped({view:t,scope:r.scope,ids:"IDS"===r.scope?r.ids:null,includeSeparators:("ALL"===r.scope||"BEFORE_LATEST_SEPARATOR"===r.scope)&&r.includeSeparators,query:i?{search:i.search,searchMode:i.searchMode,caseSensitive:i.caseSensitive,quickFilters:i.quickFilters,advancedFilter:i.advancedFilter}:null});return{view:t,scope:r.scope,deletedCount:a}}})]}var r9=e.i(885418),r7=e.i(586589),ie=e.i(661983),it=e.i(504173),ir=e.i(518733);function ii(e,t,r=null){let i=[...t.volumes].filter(e=>e.monitored).sort((e,t)=>e.freeBytes-t.freeBytes||e.id.localeCompare(t.id))[0],n=i&&i.totalBytes>0?i.freeBytes/i.totalBytes*100:null,s=null===t.agent.disconnectedAt&&null!==t.agent.lastSeenAt&&Date.now()-t.agent.lastSeenAt.getTime()<=(0,a.agentOnlineWindowMs)(t.agent);return{agent:{id:t.agent.id,name:t.agent.name,hostname:t.agent.hostname,connected:s,diskTotalBytes:t.agent.diskTotalBytes,diskFreeBytes:t.agent.diskFreeBytes},codebase:{agentId:t.agent.id},disk:{enabled:t.enabled,status:t.status,pressureMode:t.pressureMode,manualPressureMode:t.manualPressureMode,automaticPressureMode:t.automaticPressureMode,lastReportedAt:t.lastReportedAt,lastError:t.lastError,warnings:[...t.warnings],monitoredVolumeId:i?.id??null,freeBytes:i?.freeBytes??null,totalBytes:i?.totalBytes??null,freeGiB:i?i.freeBytes/0x40000000:null,freePercent:n,usedPercent:null===n?null:100-n,effectiveThresholdBytes:i?.effectiveThresholdBytes??null,normalThresholdGiB:e.normalThresholdGiB,pressureThresholdGiB:e.pressureThresholdGiB,pollIntervalSeconds:e.pollIntervalSeconds,staleAfterSeconds:e.staleAfterSeconds,changeReason:r,volumes:t.volumes.map(e=>({...e}))}}}function ia(e){return{enabled:e.disk.enabled,status:e.disk.status,pressureMode:e.disk.pressureMode,lastError:e.disk.lastError,warnings:e.disk.warnings,monitoredVolumeId:e.disk.monitoredVolumeId}}function is(e){try{let t=JSON.parse(e??"[]");return Array.isArray(t)?t:[]}catch{return[]}}function io(e,t){if(!Number.isFinite(e)||e<=0||e>1e6)throw Error(`${t} must be a positive finite GiB value`);return e}class il{agentControl;constructor(e){this.agentControl=e,this.agentControl.registerCompletionObserver(e=>this.observeCompletion(e))}async settings(){let e=await (0,t1.getPrismaClient)(),t=await e.diskSpaceSettings.upsert({where:{id:"default"},create:{id:"default",normalThresholdGiB:r7.DEFAULT_DISK_SPACE_THRESHOLD_GIB,pressureThresholdGiB:r7.DEFAULT_DISK_SPACE_PRESSURE_THRESHOLD_GIB},update:{}});return{normalThresholdGiB:t.normalThresholdGiB,pressureThresholdGiB:t.pressureThresholdGiB,pollIntervalSeconds:r7.DISK_SPACE_POLL_INTERVAL_SECONDS,staleAfterSeconds:r7.DISK_SPACE_STALE_AFTER_SECONDS}}async updateSettings(e){let t=io(e.normalThresholdGiB,"Normal disk threshold"),r=io(e.pressureThresholdGiB,"Pressure disk threshold");if(r>=t)throw Error("Pressure disk threshold must be lower than the normal threshold");let i=await (0,t1.getPrismaClient)();for(let{agentId:e}of(await i.diskSpaceSettings.upsert({where:{id:"default"},create:{id:"default",normalThresholdGiB:t,pressureThresholdGiB:r},update:{normalThresholdGiB:t,pressureThresholdGiB:r}}),this.publish("settings","SETTINGS_UPDATED"),await i.agentDiskSpaceState.findMany({where:{enabled:!0},select:{agentId:!0}})))this.reconcileAgent(e);return this.settings()}async configuration(e){let t=await (0,t1.getPrismaClient)(),[r,i,a]=await Promise.all([t.agent.findUnique({where:{id:e}}),t.agentDiskSpaceState.findUnique({where:{agentId:e}}),t.worktree.findMany({where:{missingAt:null,codebase:{agentId:e}},select:{id:!0,folder:!0}})]);if(!r)throw Error("Agent not found");return{enabled:i?.enabled??!0,pollIntervalSeconds:r7.DISK_SPACE_POLL_INTERVAL_SECONDS,baseRepoDirectory:r.baseRepoDirectory,derivedDataLocationMode:r.derivedDataLocationMode,derivedDataPath:r.derivedDataPath,worktrees:a}}async report(e,t){let r=(0,r7.parseAgentDiskSpaceReport)(t),i=await (0,t1.getPrismaClient)(),[a,n]=await Promise.all([i.agent.findUnique({where:{id:e}}),i.worktree.findMany({where:{missingAt:null,codebase:{agentId:e}},include:{codebase:{select:{agentId:!0}}}})]);if(!a)throw Error("Agent not found");let s=new Date(r.observedAt),o=r.entries.map(e=>{let t=e.workspacePath?n.filter(t=>{var r,i;let a;return r=t.folder,i=e.workspacePath,i===(a="/"===r?r:r.replace(/\/+$/,""))||i.startsWith(`${a}/`)}).sort((e,t)=>t.folder.length-e.folder.length)[0]:null;return{...e,worktreeId:t?.id??null,worktreePath:t?(0,it.worktreeDisplayPath)(t.folder,a.baseRepoDirectory):null}});await i.agentDiskSpaceState.upsert({where:{agentId:e},create:{agentId:e,volumesJson:JSON.stringify(r.volumes),entriesJson:JSON.stringify(o),warningsJson:JSON.stringify(r.warnings),lastReportedAt:s,lastError:null},update:{volumesJson:JSON.stringify(r.volumes),entriesJson:JSON.stringify(o),warningsJson:JSON.stringify(r.warnings),lastReportedAt:s,lastError:null}}),this.publish(e,"REPORT_RECEIVED"),this.reconcileAgent(e)}async overview(){let e=await (0,t1.getPrismaClient)();await e.derivedDataCleanupLease.deleteMany({where:{jobId:null,expiresAt:{lte:new Date}}});let[t,r,i]=await Promise.all([this.settings(),e.agent.findMany({orderBy:{name:"asc"},include:{diskSpaceState:!0}}),e.derivedDataCleanupLease.findMany({select:{agentId:!0}})]),a=new Set(i.map(e=>e.agentId));return{settings:t,agents:r.map(e=>{let r=e.diskSpaceState,i=r?.enabled??!0,n=r?.manualPressureMode??!1,s=r?.automaticPressureMode??!1,o=r?.lastReportedAt??null,l=!o||Date.now()-o.getTime()>1e3*t.staleAfterSeconds,c=(n||s?t.pressureThresholdGiB:t.normalThresholdGiB)*0x40000000,u=is(r?.volumesJson),d=(0,r7.monitoredDiskSpaceVolumes)(u),p=d.some(e=>e.freeBytes<=0x40000000*t.pressureThresholdGiB),h=d.some(e=>e.freeBytes<c),m="IDLE";i?l?m="STALE":r?.lastError||0===u.length&&is(r?.warningsJson).length>0?m="ERROR":p?m="CRITICAL":a.has(e.id)?m="DELETING":n||s?m="PRESSURE":h&&(m="CLEANUP_REQUIRED"):m="DISABLED";let f=u.map(r=>{let o=(0,r7.isMonitoredDiskSpaceVolume)(r);return{...r,effectiveThresholdBytes:c,monitored:o,status:i?l?"STALE":o?r.freeBytes<=0x40000000*t.pressureThresholdGiB?"CRITICAL":a.has(e.id)&&r.freeBytes<c?"DELETING":n||s?"PRESSURE":r.freeBytes<c?"CLEANUP_REQUIRED":"IDLE":"IDLE":"DISABLED"}}),g=is(r?.warningsJson);return i&&!l&&u.length>0&&0===d.length&&g.push("No Derived Data volume was reported, so free space is not being monitored for this agent"),{agent:e,enabled:i,status:m,pressureMode:n?"MANUAL":s?"AUTOMATIC":"NORMAL",manualPressureMode:n,automaticPressureMode:s,lastReportedAt:o?.toISOString()??null,lastError:r?.lastError??null,warnings:g,volumes:f}})}}async agentView(e){let t=(await this.overview()).agents.find(t=>t.agent.id===e);if(!t)throw Error("Agent not found");return t}async snapshot(e,t=null){let r=await this.overview(),i=r.agents.find(t=>t.agent.id===e);if(!i)throw Error("Agent not found");return ii(r.settings,i,t)}async requestRefresh(e){let t=await this.agentView(e);if(!t.enabled)throw Error("Disk-space monitoring is disabled for this agent");let r=new Date().toISOString();return this.agentControl.requestDiskSpacePoll(e),{agentId:e,requestedAt:r,previousReportedAt:t.lastReportedAt}}async setMonitoring(e,t){let r=await (0,t1.getPrismaClient)();return await r.agent.findUniqueOrThrow({where:{id:e}}),await r.agentDiskSpaceState.upsert({where:{agentId:e},create:{agentId:e,enabled:t},update:{enabled:t,...!t?{manualPressureMode:!1,automaticPressureMode:!1}:{}}}),t||await r.derivedDataCleanupLease.deleteMany({where:{agentId:e,jobId:null}}),this.publish(e,"MONITORING_CHANGED"),this.agentControl.requestAgentConfigurationRefresh(e),this.agentView(e)}async setManualPressureMode(e,t){let r=await (0,t1.getPrismaClient)();return await r.agent.findUniqueOrThrow({where:{id:e}}),await r.agentDiskSpaceState.upsert({where:{agentId:e},create:{agentId:e,manualPressureMode:t},update:{manualPressureMode:t}}),this.publish(e,"MANUAL_PRESSURE_CHANGED"),this.reconcileAgent(e),this.agentView(e)}async assertWorktreeCanStart(e){let t=await (0,t1.getPrismaClient)();await t.derivedDataCleanupLease.deleteMany({where:{worktreeId:e,jobId:null,expiresAt:{lte:new Date}}});let[r,i]=await Promise.all([t.derivedDataCleanupLease.findUnique({where:{worktreeId:e}}),t.worktree.findUnique({where:{id:e},select:{codebase:{select:{agentId:!0}}}})]);if(r)throw Error("Derived Data cleanup is in progress for this worktree; try again shortly");i&&await this.assertAgentCanStart(i.codebase.agentId)}async assertAgentCanStart(e){let t=await (0,t1.getPrismaClient)(),[r,i]=await Promise.all([this.settings(),t.agentDiskSpaceState.findUnique({where:{agentId:e}})]);if(!(!i?.enabled||!i.lastReportedAt||i.lastError||Date.now()-i.lastReportedAt.getTime()>1e3*r.staleAfterSeconds)&&(0,r7.monitoredDiskSpaceVolumes)(is(i.volumesJson)).some(e=>e.freeBytes<=0x40000000*r.pressureThresholdGiB))throw Error(`New builds, plans, and sessions are paused because this agent has ${r.pressureThresholdGiB} GiB or less free disk space`)}subscribe(){return ie.agentEventBus.iterate(ie.DISK_SPACE_CHANGED_TOPIC)}async reconcileAgent(e){let t=await (0,t1.getPrismaClient)();await t.derivedDataCleanupLease.deleteMany({where:{jobId:null,expiresAt:{lte:new Date}}});let[r,i,n,s,o]=await Promise.all([this.settings(),t.agentDiskSpaceState.findUnique({where:{agentId:e}}),t.derivedDataLock.findMany({where:{agentId:e},select:{path:!0}}),t.derivedDataCleanupLease.findFirst({where:{agentId:e}}),t.agent.findUnique({where:{id:e}})]);if(!i?.enabled||!i.lastReportedAt||i.lastError||s||!o||null!==o.disconnectedAt||null===o.lastSeenAt||Date.now()-o.lastSeenAt.getTime()>(0,a.agentOnlineWindowMs)(o)||!is(o.capabilitiesJson).includes(r9.BUILD_DATA_DELETE_JOB_KIND)||Date.now()-i.lastReportedAt.getTime()>1e3*r.staleAfterSeconds)return;let l=is(i.entriesJson),c=is(i.volumesJson),u=(0,r7.monitoredDiskSpaceVolumes)(c),d=l.map(e=>e.worktreeId).filter(e=>!!e),p=await (0,ir.executingResourcesByWorktree)(d),h=new Set(n.map(e=>e.path));l=l.filter(e=>"PROJECT"===e.kind&&!!e.worktreeId&&!h.has(e.path)&&(p.get(e.worktreeId)?.length??0)===0);let m=0x40000000*r.normalThresholdGiB,f=0x40000000*r.pressureThresholdGiB,g=u.filter(e=>e.freeBytes<m),y=e=>e.capacityId??e.id,w=new Map(c.map(e=>[e.id,y(e)])),v=e=>l.some(t=>w.get(t.volumeId)===y(e)),k=i.automaticPressureMode;if(!i.manualPressureMode){let r=g.length>0&&g.some(e=>!v(e)),a=k&&(0===g.length||g.every(e=>v(e)));r?k=!0:a&&(k=!1),k!==i.automaticPressureMode&&(await t.agentDiskSpaceState.update({where:{agentId:e},data:{automaticPressureMode:k}}),this.publish(e,"AUTOMATIC_PRESSURE_CHANGED"))}let E=i.manualPressureMode||k?f:m,S=new Set(u.filter(e=>e.freeBytes<E).map(y)),I=l.filter(e=>S.has(w.get(e.volumeId)??"")).sort((e,t)=>new Date(e.modifiedAt).getTime()-new Date(t.modifiedAt).getTime()||e.path.localeCompare(t.path))[0];if(!I?.worktreeId)return;try{await t.derivedDataCleanupLease.create({data:{worktreeId:I.worktreeId,agentId:e,path:I.path,source:"AUTOMATIC",expiresAt:new Date(Date.now()+6e5)}})}catch{return}let A=await (0,ir.executingResourcesByWorktree)([I.worktreeId]);if((A.get(I.worktreeId)?.length??0)>0){await t.derivedDataCleanupLease.deleteMany({where:{worktreeId:I.worktreeId,jobId:null}}),this.publish(e,"CLEANUP_SKIPPED");return}try{var x;let r=await this.agentControl.createJob({agentId:e,kind:r9.BUILD_DATA_DELETE_JOB_KIND,payload:{source:"AUTOMATIC",targets:[{path:I.path,rootPath:I.rootPath,name:I.name,kind:I.kind,worktreeId:I.worktreeId,worktreePath:I.worktreePath}]},idempotencyKey:`disk-space:auto:${(x=I.path,(0,b.createHash)("sha256").update(e).update("\0").update(x).digest("base64url"))}:${(0,b.randomUUID)()}`,timeoutSeconds:600,visibility:"SYSTEM"});await t.derivedDataCleanupLease.update({where:{worktreeId:I.worktreeId},data:{jobId:r.id}}),this.publish(e,"CLEANUP_STARTED")}catch(r){await t.derivedDataCleanupLease.deleteMany({where:{worktreeId:I.worktreeId}}),await t.agentDiskSpaceState.update({where:{agentId:e},data:{lastError:r instanceof Error?r.message:String(r)}}),this.publish(e,"CLEANUP_START_FAILED")}}async observeCompletion(e){if(e.kind!==r9.BUILD_DATA_DELETE_JOB_KIND)return;let t="USER",r=[];try{let i=(0,r9.buildDataDeletePayload)(JSON.parse(e.payloadJson));t=i.source,r=i.targets}catch{}let i=await (0,t1.getPrismaClient)(),a=await i.derivedDataCleanupLease.deleteMany({where:{jobId:e.id}});if("AUTOMATIC"===t&&"SUCCEEDED"!==e.status&&await i.agentDiskSpaceState.updateMany({where:{agentId:e.agentId},data:{lastError:e.error||"Automatic Derived Data cleanup failed"}}),a.count||"AUTOMATIC"===t){let i=[];if("AUTOMATIC"===t&&e.resultJson)try{i=(0,r9.parseBuildDataDeleteResult)(JSON.parse(e.resultJson)).deleted}catch{}this.publish(e.agentId,"CLEANUP_COMPLETED","AUTOMATIC"===t?{jobId:e.id,status:e.status,source:t,error:e.error,targets:r,deleted:i}:null),this.agentControl.requestDiskSpacePoll(e.agentId)}}publish(e,t,r=null){ie.agentEventBus.publish(ie.DISK_SPACE_CHANGED_TOPIC,{diskSpaceChanged:e,diskSpaceChange:{id:(0,b.randomUUID)(),reason:t,cleanup:r}}),ie.agentEventBus.publish(ie.SIDEBAR_STATUS_CHANGED_TOPIC,{sidebarStatusChanged:!0}),ie.agentEventBus.publish(ie.POLLING_CHANGED_TOPIC,{pollingOperationChanged:`agent-disk-space:${e}`})}}let ic=e6.object({normalThresholdGiB:e6.number(),pressureThresholdGiB:e6.number(),pollIntervalSeconds:e6.number().int(),staleAfterSeconds:e6.number().int()}),iu=e6.object({id:e6.string(),name:e6.string(),hostname:e6.string(),connected:e6.boolean(),diskTotalBytes:e6.number().nullable(),diskFreeBytes:e6.number().nullable()}),id=e6.enum(["DISABLED","STALE","IDLE","CLEANUP_REQUIRED","DELETING","PRESSURE","CRITICAL","ERROR"]),ip=e6.object({id:e6.string(),capacityId:e6.string(),totalBytes:e6.number(),freeBytes:e6.number(),roles:e6.array(e6.enum(["MAIN","BASE_REPO","DERIVED_DATA"])),paths:e6.array(e6.string()),status:id,effectiveThresholdBytes:e6.number(),monitored:e6.boolean()}),ih=e6.object({enabled:e6.boolean(),status:id,pressureMode:e6.enum(["NORMAL","MANUAL","AUTOMATIC"]),manualPressureMode:e6.boolean(),automaticPressureMode:e6.boolean(),lastReportedAt:e6.string().nullable(),lastError:e6.string().nullable(),warnings:e6.array(e6.string()),monitoredVolumeId:e6.string().nullable(),freeBytes:e6.number().nullable(),totalBytes:e6.number().nullable(),freeGiB:e6.number().nullable(),freePercent:e6.number().nullable(),usedPercent:e6.number().nullable(),effectiveThresholdBytes:e6.number().nullable(),normalThresholdGiB:e6.number(),pressureThresholdGiB:e6.number(),pollIntervalSeconds:e6.number().int(),staleAfterSeconds:e6.number().int(),changeReason:e6.string().nullable(),volumes:e6.array(ip)}),im=e6.object({agent:iu,codebase:e6.object({agentId:e6.string()}),disk:ih}),ig=e6.object({agentId:e6.string().min(1)}),iy=e6.object({name:e6.string().min(1),description:e6.string().default(""),script:e6.string().min(1),targetKind:e6.enum(["ANY_AGENT_HOME","SPECIFIC_AGENT_HOME","ANY_WORKTREE","REPOSITORY_WORKTREE"]),targetAgentId:e6.string().nullable().optional(),targetRepositoryIds:e6.array(e6.string().min(1)).nullable().optional(),targetRepositoryId:e6.string().nullable().optional(),restartPolicy:e6.enum(["NEVER","ON_FAILURE","ALWAYS"]).default("NEVER"),restartLimit:e6.number().int().min(0).max(100).default(3),concurrency:e6.enum(["EXCLUSIVE","NON_EXCLUSIVE","EXCLUDED"]).default("NON_EXCLUSIVE"),blocksGitOperations:e6.boolean().default(!1),quickActionEnabled:e6.boolean().default(!1),quickActionIconKey:e6.string().default("terminal"),quickActionButtonVariant:e6.string().default("default"),notificationsEnabled:e6.boolean().default(!0)}),iw="WORKFLOW_AUTOMATION",ib={actor:"workflow",ipAddress:null},iv=e6.object({owner:e6.string().min(1),name:e6.string().min(1),number:e6.number().int().positive()}),ik=e6.object({projectId:e6.string().min(1),iid:e6.number().int().positive()}),iE=e6.object({issueKey:e6.string().min(1)}),iS=e6.object({format:e6.string().min(1),value:e6.string()}),iI=e6.enum(["JQL","BOARD"]);var iA=e.i(807237);let ix=e6.object({runId:e6.string().min(1)}),i_=e6.object({kind:e6.string().min(1),worktreeId:e6.string().min(1),jiraIssueKey:e6.string().nullable().optional(),provider:e6.string().min(1),model:e6.string().min(1),effort:e6.string().nullable().optional(),webSearchEnabled:e6.boolean().nullable().optional(),prompt:e6.string().min(1),attachmentIds:e6.array(e6.string().min(1)).nullable().optional(),draftId:e6.string().nullable().optional(),sourcePlanId:e6.string().nullable().optional(),parentRunId:e6.string().nullable().optional(),followUpMode:e6.string().nullable().optional(),contextMode:e6.string().nullable().optional()});var iC=e.i(497800),iR=e.i(835544);function iT(e,t){let r=new Set([...e.nodes.map(({id:e})=>e),...e.triggers.map(({id:e})=>e)]);for(let e=1;;e+=1){let i=`${t}-${e}`;if(!r.has(i))return i}}function iD(e,t){return e.nodes.find(e=>e.id===t)??e.triggers.find(e=>e.id===t)}function iN(e){return(0,iR.isChoiceTriggerKind)(e.kind)?(0,iC.workflowTriggerChoices)(e.config).map(({key:e})=>e):(0,iR.workflowStaticSourceHandles)(e.kind)}function iO(e,t){if(t.config)return t.config;if(!t.configPatch)return e;let r={...e};for(let[e,i]of Object.entries(t.configPatch))null===i?delete r[e]:r[e]=i;return r}function iP(e,t){let r=iD(e,t.source);if(!r)throw Error(`${t.source} is not in this workflow`);if(!e.nodes.some(({id:e})=>e===t.target))throw Error(`${t.target} is not a step — triggers cannot have incoming connections`);let i=iN(r),a=t.sourceHandle??i[0];if(!a)throw Error(`${t.source} offers no connectors yet — a choice trigger needs its options set first`);if(!i.includes(a))throw Error(`${t.source} has no ${a} connector; it offers ${i.join(", ")}`);let n=t.targetHandle??"input",s=e.edges.find(e=>e.source===t.source&&e.target===t.target&&e.sourceHandle===a);if(s)return{definition:e,edgeId:s.id};let o=function(e){let t=new Set(e.edges.map(({id:e})=>e));for(let e=1;;e+=1){let r=`edge-${e}`;if(!t.has(r))return r}}(e);return{definition:{...e,edges:[...e.edges,{id:o,source:t.source,target:t.target,sourceHandle:a,targetHandle:n}]},edgeId:o}}let iL={workflow:[{name:"id",description:"Workflow definition id"},{name:"name",description:"Workflow name"},{name:"runId",description:"Current run id"},{name:"startedAt",description:"Run start timestamp"},{name:"trigger",description:"Trigger that started the run"}],repo:[{name:"id",description:"Repository id"},{name:"githubId",description:"GitHub repository id"},{name:"owner",description:"Repository owner / organization"},{name:"name",description:"Repository name"},{name:"url",description:"Repository URL"},{name:"canonicalOrigin",description:"Normalized repository origin"},{name:"displayOrigin",description:"Human-readable repository origin"},{name:"defaultBranch",description:"Repository default branch"}],codebase:[{name:"id",description:"Codebase id"},{name:"agentId",description:"Owning agent id"},{name:"folder",description:"Codebase filesystem path"},{name:"branch",description:"Current branch"},{name:"headSha",description:"HEAD commit SHA"},{name:"dirty",description:"Whether the working tree has changes"},{name:"branches",description:"Local and remote Git branches"},{name:"branchesTruncated",description:"Whether branch results were truncated"},{name:"stashes",description:"Git stashes"},{name:"stashesTruncated",description:"Whether stash results were truncated"},{name:"remoteBranches",description:"Known remote branches"}],agent:[{name:"id",description:"Owning agent id"},{name:"name",description:"Agent display name"},{name:"hostname",description:"Agent hostname"},{name:"connected",description:"Whether the agent is connected"},{name:"diskTotalBytes",description:"Root disk capacity in bytes"},{name:"diskFreeBytes",description:"Available disk space in bytes"},{name:"memoryFreeBytes",description:"Available memory in bytes"}],disk:[{name:"enabled",description:"Whether disk monitoring is enabled"},{name:"status",description:"Current disk monitor status"},{name:"pressureMode",description:"Normal, manual, or automatic pressure mode"},{name:"manualPressureMode",description:"Whether manual pressure mode is enabled"},{name:"automaticPressureMode",description:"Whether automatic pressure mode is active"},{name:"lastReportedAt",description:"Timestamp of the latest accepted disk report"},{name:"lastError",description:"Latest monitor or cleanup error"},{name:"warnings",description:"Current disk report warnings"},{name:"monitoredVolumeId",description:"Least-free monitored Derived Data volume id"},{name:"freeBytes",description:"Monitored Derived Data free bytes"},{name:"totalBytes",description:"Monitored Derived Data total bytes"},{name:"freeGiB",description:"Monitored Derived Data free space in GiB"},{name:"freePercent",description:"Monitored Derived Data free percentage"},{name:"usedPercent",description:"Monitored Derived Data used percentage"},{name:"effectiveThresholdBytes",description:"Current cleanup threshold in bytes"},{name:"normalThresholdGiB",description:"Global normal threshold in GiB"},{name:"pressureThresholdGiB",description:"Global pressure threshold in GiB"},{name:"pollIntervalSeconds",description:"Agent disk report cadence"},{name:"staleAfterSeconds",description:"Age at which a report is stale"},{name:"changeReason",description:"Internal reason for the monitor event"},{name:"volumes",description:"All reported volumes and their monitor status"}],cleanup:[{name:"jobId",description:"Automatic cleanup agent job id"},{name:"status",description:"Automatic cleanup terminal status"},{name:"source",description:"Cleanup source"},{name:"error",description:"Cleanup error, if any"},{name:"targets",description:"Derived Data entries selected for cleanup"},{name:"deleted",description:"Derived Data entries reported deleted"}],command:[{name:"id",description:"Command run id"},{name:"commandId",description:"Saved command definition id"},{name:"name",description:"Command display name"},{name:"status",description:"Command run status"},{name:"exitCode",description:"Command process exit code"},{name:"signal",description:"Command termination signal"},{name:"error",description:"Command failure reason"},{name:"finishedAt",description:"Command completion timestamp"}],skill:[{name:"id",description:"Skill id"},{name:"groupId",description:"Skill group id"}],skillSync:[{name:"id",description:"Skill sync run id"},{name:"kind",description:"Skill sync kind"},{name:"status",description:"Skill sync status"},{name:"error",description:"Skill sync failure reason"},{name:"conflictCount",description:"Unresolved conflict count"},{name:"conflicts",description:"Unresolved skill conflicts"},{name:"updatedAt",description:"Skill sync update timestamp"},{name:"finishedAt",description:"Skill sync completion timestamp"}],buildData:[{name:"id",description:"Build-data collection id"},{name:"status",description:"Collection status"},{name:"finishedAt",description:"Collection completion timestamp"},{name:"totalBytes",description:"Total discovered bytes"},{name:"entryCount",description:"Discovered entry count"},{name:"successfulAgentCount",description:"Agents that completed collection successfully"}],signingProfile:[{name:"id",description:"Signing profile id"},{name:"uuid",description:"Provisioning profile UUID"},{name:"name",description:"Provisioning profile name"},{name:"expiresAt",description:"Provisioning profile expiry"},{name:"expired",description:"Whether the profile is expired"}],device:[{name:"id",description:"iOS device id"},{name:"udid",description:"Device UDID"},{name:"name",description:"Device display name"},{name:"product",description:"Device product identifier"},{name:"osVersion",description:"Device OS version"},{name:"status",description:"Device registration status"},{name:"error",description:"Device registration failure reason"},{name:"updatedAt",description:"Device update timestamp"}],pushBatch:[{name:"id",description:"Push-notification batch id"},{name:"status",description:"Push batch status"},{name:"targetMode",description:"Push batch target mode"},{name:"deliveryCount",description:"Push delivery count"},{name:"updatedAt",description:"Push batch update timestamp"}],ticket:[{name:"key",description:"Jira issue key (e.g. AIDE-42)"},{name:"projectKey",description:"Jira project key"},{name:"title",description:"Issue summary / title"},{name:"type",description:"Issue type (Bug, Story, …)"},{name:"status",description:"Workflow status name"},{name:"statusId",description:"Workflow status id"},{name:"statusCategory",description:"Status category (To Do, Done, …)"},{name:"assignee",description:"Assigned user"},{name:"assigneeAccountId",description:"Assigned Jira account id"},{name:"labels",description:"Issue labels"},{name:"sprintNames",description:"Sprints containing the issue"},{name:"url",description:"Jira issue URL"}],changelog:[{name:"id",description:"Jira webhook changelog id"},{name:"items",description:"Fields changed in the Jira update"}],pr:[{name:"id",description:"Pull request id"},{name:"number",description:"Pull request number"},{name:"state",description:"Open / closed / merged state"},{name:"merged",description:"Whether the pull request was merged"},{name:"title",description:"Pull request title"},{name:"url",description:"Pull request URL"},{name:"labels",description:"Pull request labels"},{name:"isDraft",description:"Whether the pull request is a draft"},{name:"headBranch",description:"Pull request head branch"},{name:"headRefName",description:"Pull request head ref"},{name:"headSha",description:"Pull request head commit SHA"},{name:"baseBranch",description:"Pull request base branch"},{name:"reviewDecision",description:"Latest review decision"},{name:"pipelineStatus",description:"Combined pull request check status"},{name:"unresolvedReviewThreadCount",description:"Number of unresolved pull request review threads"},{name:"pipelines",description:"CI pipelines linked to the pull request"},{name:"reviewThreads",description:"Pull request review threads"},{name:"mergeable",description:"Pull request mergeability"},{name:"repositoryGithubId",description:"GitHub repository id"},{name:"repositoryNameWithOwner",description:"GitHub owner and repository name"},{name:"jiraKey",description:"Jira key linked to the pull request"},{name:"unresolvedThreads",description:"Unresolved review threads"}],worktree:[{name:"id",description:"Worktree id"},{name:"branch",description:"Worktree branch"},{name:"baseBranch",description:"Base branch the work targets"},{name:"path",description:"Filesystem path"},{name:"headSha",description:"Worktree HEAD commit SHA"},{name:"pushStatus",description:"Push readiness status"},{name:"upstream",description:"Tracked upstream branch"},{name:"syncState",description:"Relationship to the tracked branch"},{name:"ahead",description:"Commits ahead of upstream"},{name:"behind",description:"Commits behind upstream"},{name:"baseAhead",description:"Commits ahead of the base branch"},{name:"baseBehind",description:"Commits behind the base branch"},{name:"commits",description:"Commits on the branch"},{name:"changes",description:"Pending file changes"},{name:"branchChanges",description:"Files changed from the base branch"},{name:"commitsTruncated",description:"Whether commit results were truncated"},{name:"changesTruncated",description:"Whether pending changes were truncated"},{name:"branchChangesTruncated",description:"Whether branch change results were truncated"},{name:"dirty",description:"Whether the working tree has changes"},{name:"branches",description:"Local and remote Git branches"},{name:"branchesTruncated",description:"Whether branch results were truncated"},{name:"stashes",description:"Git stashes"},{name:"stashesTruncated",description:"Whether stash results were truncated"},{name:"rebaseInProgress",description:"Whether a rebase is in progress"},{name:"hasConflicts",description:"Whether Git reports conflicts"},{name:"conflicted",description:"Whether an inspection found conflicts"},{name:"conflicts",description:"Conflicting files"},{name:"missingAt",description:"When the worktree was found missing"},{name:"dirtySince",description:"When the worktree became dirty"},{name:"autoSync",description:"Persistent Auto Sync configuration and current state"},{name:"autoMerge",description:"Persistent Auto Merge configuration and current state"}],pipeline:[{name:"id",description:"CI pipeline id"},{name:"runId",description:"CI run id"},{name:"workflowId",description:"CI workflow id"},{name:"name",description:"CI workflow name"},{name:"displayTitle",description:"CI run display title"},{name:"status",description:"Run status"},{name:"conclusion",description:"Run conclusion"},{name:"headBranch",description:"Branch built by the CI run"},{name:"headSha",description:"Commit built by the CI run"},{name:"pullRequests",description:"Pull requests linked to the CI run"},{name:"url",description:"CI run URL"},{name:"failedJobs",description:"Failed jobs"},{name:"jobs",description:"Jobs in the CI run"},{name:"checkSuiteId",description:"GitHub check suite id"},{name:"runNumber",description:"GitHub Actions run number"},{name:"runAttempt",description:"GitHub Actions run attempt"},{name:"jiraKey",description:"Jira key inferred from the run"}],build:[{name:"id",description:"Build id"},{name:"status",description:"Build status"},{name:"action",description:"Build action"},{name:"error",description:"Build error, if any"},{name:"artifactDirectory",description:"Build artifact directory"},{name:"testSummary",description:"Test result summary"},{name:"tests",description:"Individual test results"},{name:"coverageSummary",description:"Coverage summary"},{name:"coverageFiles",description:"Per-file coverage results"},{name:"changedCoverageFiles",description:"Coverage for files changed on the branch"},{name:"artifacts",description:"Exported build artifacts"},{name:"exportId",description:"Build export id"}],run:[{name:"id",description:"Agent run id"},{name:"kind",description:"Run kind (PLAN / SESSION)"},{name:"status",description:"Run status"},{name:"phase",description:"Run phase"},{name:"origin",description:"Run origin"},{name:"provider",description:"AI provider"},{name:"model",description:"AI model"},{name:"branch",description:"Branch used by the run"},{name:"finalOutput",description:"Final output text"},{name:"error",description:"Run error, if any"},{name:"usage",description:"Token usage and cost"},{name:"questions",description:"Questions asked by the run"},{name:"events",description:"Run events"},{name:"links",description:"Resources linked to the run"}],steps:[{name:"status",description:"Step completion status"},{name:"output",description:"Step output payload"},{name:"answer",description:"Human answer for the step"},{name:"snapshotId",description:"Captured snapshot id"},{name:"items",description:"Items produced for iteration"},{name:"commandRunId",description:"Command run id"},{name:"displayNumber",description:"Resource display number"},{name:"matches",description:"Ordered regex matches emitted by a command step"},{name:"latestMatch",description:"Latest regex match emitted by a command step"}],comment:[{name:"id",description:"Comment id"},{name:"body",description:"Comment body"},{name:"author",description:"Comment author"}],push:[{name:"ref",description:"Pushed Git ref"},{name:"before",description:"Commit before the push"},{name:"after",description:"Commit after the push"}],job:[{name:"id",description:"Job id"},{name:"name",description:"Job name"},{name:"status",description:"Job status"},{name:"url",description:"Job URL"},{name:"runAttempt",description:"Workflow run attempt"}]},iB=new Map(Object.entries(iL).flatMap(([e,t])=>t.map(t=>[`${e}.${t.name}`,t.description])));function iU(e){return e.split(".")[0]??e}let ij=e6.object({workflowId:e6.string().min(1).describe("Workflow id.")}),iM=e6.object({x:e6.number(),y:e6.number()}).describe("Canvas position. Presentation only — omit it and a sensible spot is chosen."),iq=e6.record(e6.string(),e6.unknown()).describe("Config object for this kind. Call describe_workflow_kind for its schema. A value may be a constant, a session binding `{source:'SESSION',path:'ticket.key'}`, or a string with `{{ticket.key}}` interpolation."),i$=e6.array(e6.string()).max(100).describe("Extra session paths this step guarantees, on top of what its kind always provides. Required when a step writes to a config-chosen path — e.g. a CONTROL_SET_VARIABLE with `path: 'checks.ready'` must declare ['checks.ready'], or a later step binding it fails validation with REQUIREMENT_UNSATISFIED."),iF=e6.array(e6.string()).max(100).describe("Extra session paths this step demands, on top of its kind's own. Publishing fails unless every trigger that reaches the step guarantees them."),iG=e6.object({severity:e6.enum(["ERROR","WARNING"]),code:e6.string(),message:e6.string(),nodeId:e6.string().nullable(),triggerId:e6.string().nullable(),path:e6.string().nullable()}),iK=e6.object({workflowId:e6.string(),definition:e6.unknown().describe("The saved draft definition."),valid:e6.boolean().describe("Whether the draft would publish. Warnings do not block."),diagnostics:e6.array(iG),nodeId:e6.string().nullable().describe("Id of a step this call created."),triggerId:e6.string().nullable().describe("Id of a trigger this call created."),edgeId:e6.string().nullable().describe("Id of a connection this call created.")}),iH=e6.object({id:e6.string(),name:e6.string(),description:e6.string(),enabled:e6.boolean(),overlapPolicy:e6.string(),overlapScope:e6.string(),maxConcurrentRuns:e6.number(),completionNotificationsEnabled:e6.boolean(),exclusiveWorktree:e6.boolean(),worktreeConcurrency:e6.enum(["EXCLUSIVE","NON_EXCLUSIVE","EXCLUDED"]),blocksGitOperations:e6.boolean(),activeVersionId:e6.string().nullable(),draftSchemaVersion:e6.number(),quickActionKind:e6.enum(["STANDARD","MERGE_CONFLICT","GITHUB_ACTIONS","NONE"]),archivedAt:e6.string().nullable(),versionCount:e6.number(),runCount:e6.number(),createdAt:e6.string().nullable(),updatedAt:e6.string().nullable()}),iV=e6.object({id:e6.string(),displayNumber:e6.number(),workflowId:e6.string(),versionId:e6.string(),parentRunId:e6.string().nullable(),triggerKind:e6.string(),triggerSubjectKey:e6.string(),triggerPayload:e6.unknown(),status:e6.string(),phase:e6.string(),generation:e6.number(),sessionData:e6.unknown(),blockedReason:e6.string().nullable(),error:e6.string().nullable(),attemptCount:e6.number(),eventCount:e6.number(),queuedAt:e6.string().nullable(),startedAt:e6.string().nullable(),pausedAt:e6.string().nullable(),finishedAt:e6.string().nullable(),updatedAt:e6.string().nullable()}),iW=e6.object({id:e6.string(),runId:e6.string(),attemptId:e6.string().nullable(),sequence:e6.number(),type:e6.string(),message:e6.string(),detail:e6.unknown(),createdAt:e6.string().nullable()}),iJ=e6.object({batchId:e6.string(),runId:e6.string().nullable(),status:e6.string(),createdAt:e6.string().nullable(),questions:e6.array(e6.object({id:e6.string(),header:e6.string().nullable(),prompt:e6.string(),multiSelect:e6.boolean(),allowCustom:e6.boolean(),options:e6.array(e6.object({label:e6.string(),description:e6.string().nullable()}))}))}),iz={readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0};function iY(e,t){return!t||e.toLowerCase().includes(t.toLowerCase())}async function iZ(e,t){let r=await e().get(t);if(!r)throw Error(`Workflow ${t} was not found`);return(0,iC.parseWorkflowDefinition)(JSON.parse(r.draftDefinitionJson))}async function iQ(e,t,r,i={}){let a=e();await a.saveDraft({id:t,definition:r});let{valid:n,diagnostics:s}=await a.validateDraft(t);return{workflowId:t,definition:re(r),valid:n,diagnostics:s.map(e=>({severity:e.severity,code:e.code,message:e.message,nodeId:e.nodeId??null,triggerId:e.triggerId??null,path:e.path??null})),nodeId:i.nodeId??null,triggerId:i.triggerId??null,edgeId:i.edgeId??null}}function iX(e){let t=iC.WORKFLOW_TRIGGER_CATALOG.find(t=>t.kind===e);if(!t)throw Error(`Unknown trigger kind ${e}`);return t}var i0=e.i(119909);let i1=e6.object({id:e6.string().min(1)}),i2=e6.object({worktreeId:e6.string().min(1),requestId:e6.string().min(1)}),i3=e6.object({mode:e6.enum(["NEW","EXISTING","TICKET"]),branchName:e6.string().nullable().optional(),ticketKey:e6.string().nullable().optional(),baseBranch:e6.string().min(1)}),i4=e6.object({worktreeIds:e6.array(e6.string().min(1)).max(500),action:e6.enum(i0.WORKTREE_PREPARATION_ACTIONS),requestId:e6.string().min(1)}),i6=e6.object({id:e6.string(),kind:e6.enum(["WRITE","DELETE","ASSUME_UNCHANGED"]),path:e6.string(),contentSha256:e6.string().nullable(),byteCount:e6.number().int().nonnegative().nullable(),definitionHash:e6.string()}),i8=e6.object({repositories:e6.array(e6.object({repository:e6.object({id:e6.string(),name:e6.string(),canonicalOrigin:e6.string(),displayOrigin:e6.string()}),preparations:e6.array(i6),worktrees:e6.array(e6.object({worktree:e6.object({id:e6.string(),codebaseId:e6.string(),folder:e6.string(),relativePath:e6.string(),branch:e6.string().nullable(),baseBranch:e6.string().nullable(),primary:e6.boolean(),availability:e6.string(),missingAt:e6.string().nullable()}),agent:e6.object({id:e6.string(),name:e6.string(),hostname:e6.string(),version:e6.string()}),supported:e6.boolean(),unsupportedReason:e6.string().nullable(),overallState:e6.string(),statuses:e6.array(e6.object({preparationId:e6.string(),kind:e6.enum(["WRITE","DELETE","ASSUME_UNCHANGED"]),path:e6.string(),definitionHash:e6.string(),state:e6.string(),message:e6.string().nullable(),checkedAt:e6.string().nullable()})),activeJob:e6.object({id:e6.string(),status:e6.string()}).nullable()}))}))}),i5=e6.object({worktreeId:e6.string(),state:e6.string(),conflictWorkflowId:e6.string().nullable(),conflictWorkflowChoice:e6.string().nullable(),lastError:e6.string().nullable(),pauseReason:e6.string().nullable(),lastSyncedAt:e6.string().nullable(),updatedAt:e6.string()}),i9=e6.object({worktreeId:e6.string(),state:e6.string(),repositoryNameWithOwner:e6.string(),pullRequestNumber:e6.number().int(),mergeMethod:e6.enum(["MERGE","REBASE","SQUASH"]),commitHeadline:e6.string(),commitBody:e6.string(),authorEmail:e6.string().nullable(),deleteWorktree:e6.boolean(),moveTicketToDone:e6.boolean(),ticketKey:e6.string().nullable(),lastError:e6.string().nullable(),updatedAt:e6.string()}),i7={readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},ae={readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},at={readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},ar={...i7,openWorldHint:!0},ai={...ae,openWorldHint:!0},aa={...at,openWorldHint:!0};function an(e){return{name:e.name,title:e.title,description:e.description,inputSchema:e.inputSchema,outputSchema:e.outputSchema,annotations:e.annotations??i7,invoke:async t=>{let r=e.inputSchema.parse(t);return e.outputSchema.parse(await e.handler(r))}}}function as(e){return{id:e.id,name:e.name,source:"BUILTIN",transport:null,url:null,error:null,tools:e.tools.map(e=>({name:e.name,title:e.title,description:e.description,inputSchema:I.toJSONSchema(e.inputSchema),outputSchema:I.toJSONSchema(e.outputSchema),annotations:e.annotations})),children:e.children.map(as)}}function ao(e){if(!e||"object"!=typeof e||Array.isArray(e))throw Error("Built-in tool output must be a JSON object");return{content:[{type:"text",text:JSON.stringify(e,null,2)}],structuredContent:e}}class al{groups;indexed;byName;groupIds;constructor(e){this.groups=e,this.indexed=function e(t){return t.flatMap(t=>[...t.tools.map(e=>({groupId:t.id,definition:e})),...e(t.children)])}(e),this.byName=new Map,this.groupIds=new Set;const t=e=>{if(this.groupIds.has(e.id))throw Error(`Duplicate built-in tool group id: ${e.id}`);this.groupIds.add(e.id),e.children.forEach(t)};for(const r of(e.forEach(t),this.indexed)){if(this.byName.has(r.definition.name))throw Error(`Duplicate built-in MCP tool name: ${r.definition.name}`);this.byName.set(r.definition.name,r)}}definitions(){return this.indexed.map(({definition:e})=>e)}catalog(){return this.groups.map(as)}hasGroup(e){return this.groupIds.has(e)}groupIdForName(e){return this.byName.get(e)?.groupId??null}async call(e,t,r){let i=this.byName.get(t);if(!i||i.groupId!==e)throw Error(`Unknown built-in tool: ${t}`);return ao(await i.definition.invoke(r))}async callByName(e,t){let r=this.byName.get(e);if(!r)throw Error(`Unknown built-in tool: ${e}`);return ao(await r.definition.invoke(t))}}function ac(e){return{...e,startedAt:e.startedAt.toISOString(),finishedAt:e.finishedAt?.toISOString()??null}}class au{async clear(){return(await (0,t1.getPrismaClient)()).toolCallAudit.deleteMany({where:{resultStatus:{not:"RUNNING"}}})}async execute(e,t){var r;let i,a,n=await (0,t1.getPrismaClient)(),s=(0,b.randomUUID)(),o=new Date;await n.toolCallAudit.create({data:{id:s,correlationId:e.correlationId,caller:e.caller,source:e.source,groupId:e.groupId,toolName:e.toolName,argumentsSha256:(r=e.arguments,(0,b.createHash)("sha256").update(JSON.stringify((a=e=>null===e||"string"==typeof e||"boolean"==typeof e?e:"number"==typeof e?Number.isFinite(e)?e:String(e):"bigint"==typeof e?e.toString():Array.isArray(e)?e.map(a):e instanceof Date?e.toISOString():e&&"object"==typeof e?Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,a(t)])):String(e))(r))).digest("hex")),resultStatus:"RUNNING",startedAt:o}});try{i=await t()}catch(t){let e=new Date;throw await n.toolCallAudit.update({where:{id:s},data:{resultStatus:"FAILED",durationMs:Math.max(0,e.getTime()-o.getTime()),finishedAt:e}}).catch(()=>void 0),ie.agentEventBus.publish(ie.TOOL_CALL_AUDIT_CHANGED_TOPIC,{toolCallAuditChanged:{id:s}}),t}let l=new Date,c=!1;try{await n.toolCallAudit.update({where:{id:s},data:{resultStatus:"SUCCEEDED",durationMs:Math.max(0,l.getTime()-o.getTime()),finishedAt:l}}),c=!0}catch(e){console.error("Could not persist successful tool-call audit completion:",e instanceof Error?e.message:e)}return c&&ie.agentEventBus.publish(ie.TOOL_CALL_AUDIT_CHANGED_TOPIC,{toolCallAuditChanged:{id:s}}),i}async list(e={}){let t=await (0,t1.getPrismaClient)();return(await t.toolCallAudit.findMany({where:{...e.toolName?{toolName:e.toolName}:{},...e.resultStatus?{resultStatus:e.resultStatus}:{}},orderBy:{startedAt:"desc"},take:Math.min(Math.max(e.first??100,1),500)})).map(ac)}async get(e){let t=await (0,t1.getPrismaClient)(),r=await t.toolCallAudit.findUnique({where:{id:e}});return r?ac(r):null}}let ad="external:",ap=new Set(["accept","connection","content-length","content-type","host","last-event-id","mcp-protocol-version","mcp-session-id","transfer-encoding"]),ah=new Set(v.BUILD_CONFIGURATION_ICON_KEYS),am=new Set(["get_codebase_repository_preparations","save_codebase_repository_preparations"]);function af(e){if("STREAMABLE_HTTP"===e||"SSE"===e)return e;throw Error(`Unsupported MCP transport: ${e}`)}function ag(e,t){return{id:e.id,name:e.name,url:e.url,transport:af(e.transport),toolNamePrefix:e.toolNamePrefix,headers:[...e.headers].sort((e,t)=>e.name.localeCompare(t.name)).map(e=>({id:e.id,name:e.name,valueConfigured:t})),createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString()}}function ay(e){return{id:e.id,name:e.name,description:e.description,iconKey:e.iconKey,enabledForPlans:e.enabledForPlans,enabledForSessions:e.enabledForSessions,toolNames:e.tools.map(({toolName:e})=>e).sort(),createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString()}}class aw{credentials;audit;builtInTools;constructor(e,t,r={},i=new t3.CredentialService,a=new au){this.credentials=i,this.audit=a,this.builtInTools=function(e){var t,r,i,a,n,s,o,l,u,d,p,h,m,f,g,y,w,b,v,k,E,S,I,A,x,_,C,R,T,D,N,O;let P,L,B,U,j=[(t=e.codebaseTools,r=e.codebases,P=[an({name:"get_codebases",title:"Get codebases",description:"List every registered codebase checkout.",inputSchema:c.GetCodebasesInputSchema,outputSchema:c.GetCodebasesOutputSchema,annotations:i7,handler:async()=>({codebases:await t.list()})}),an({name:"get_codebase",title:"Get codebase",description:"Get one registered codebase by ID or exact folder path.",inputSchema:c.GetCodebaseInputSchema,outputSchema:c.GetCodebaseOutputSchema,annotations:i7,handler:async e=>({codebase:"id"in e?await t.getById(e.id):e.agentId?await t.getByPath(e.path,e.agentId):await t.getByPath(e.path)})})],r&&(P.splice(1,0,an({name:"search_codebases",title:"Search codebases",description:"Search registered codebases by text, agent, repository, branch, availability, or sync state.",inputSchema:c.SearchCodebasesInputSchema,outputSchema:c.SearchCodebasesOutputSchema,annotations:i7,handler:e=>t.search(e)}),rm({name:"register_codebase",title:"Register codebase",description:"Register a previously inspected agent repository folder.",inputSchema:e6.object({inspectionJobId:e6.string().min(1),name:e6.string().nullable().optional(),description:e6.string().nullable().optional()}),service:r,method:"confirm",resultKey:"codebase",annotations:{...ae,idempotentHint:!1}}),rm({name:"update_codebase_repository",title:"Update codebase repository",description:"Update canonical repository metadata and linked skill groups.",inputSchema:e6.object({id:e6.string().min(1),name:e6.string().min(1),description:e6.string(),jiraBranchRegex:e6.string().nullable().optional(),keepBaseBranchUpToDate:e6.boolean(),skillGroupIds:e6.array(e6.string()).nullable().optional()}),service:r,method:"updateRepository",arguments:e=>[e.id,e.name,e.description,e.jiraBranchRegex,e.keepBaseBranchUpToDate,e.skillGroupIds],resultKey:"repository",annotations:ae}),rm({name:"update_codebase_settings",title:"Update codebase settings",description:"Update global refresh, fetch, and Jira branch parsing settings.",inputSchema:e6.object({refreshIntervalSeconds:e6.number().int().positive(),fetchIntervalSeconds:e6.number().int().positive(),defaultJiraBranchRegex:e6.string()}),service:r,method:"updateSettings",resultKey:"settings",annotations:ae}),rm({name:"remove_codebase",title:"Remove codebase",description:"Remove a registered codebase from the control plane without deleting its repository folder.",inputSchema:e6.object({id:e6.string().min(1)}),service:r,method:"removeCodebase",arguments:({id:e})=>[e],resultKey:"removed",annotations:at}),rm({name:"run_codebase_git_operation",title:"Run codebase Git operation",description:"Run a supported Git operation against a registered codebase.",inputSchema:e6.object({codebaseId:e6.string().min(1),operation:e6.string().min(1),branch:e6.string().nullable().optional(),stashOid:e6.string().nullable().optional(),stashChanges:e6.boolean().nullable().optional(),requestId:e6.string().min(1)}),service:r,method:"runGitOperation",resultKey:"job",annotations:ae})),P.push(an({name:"get_codebase_repositories",title:"Get codebase repositories",description:"List canonical repositories and their checkout counts.",inputSchema:ry,outputSchema:c.GetCodebaseRepositoriesOutputSchema,annotations:i7,handler:async()=>({repositories:await t.repositories()})}),an({name:"get_codebase_repository",title:"Get codebase repository",description:"Get a canonical repository and all of its registered checkouts.",inputSchema:c.GetCodebaseRepositoryInputSchema,outputSchema:c.GetCodebaseRepositoryOutputSchema,annotations:i7,handler:async({id:e})=>({repository:await t.repository(e)})}),an({name:"get_codebase_repository_preparations",title:"Get repository preparations",description:"Get every write, delete, and assume-unchanged rule configured for a repository, including uploaded write contents.",inputSchema:rT,outputSchema:e6.object({preparations:e6.array(rR)}),annotations:i7,handler:async({repositoryId:e})=>({preparations:(await r.repositoryPreparations(e)).map(rD)})}),an({name:"save_codebase_repository_preparations",title:"Save repository preparations",description:"Atomically replace a repository's preparation rules. Existing write contents are retained when their rule ID is supplied without contentBase64; omitted rules are deleted.",inputSchema:rT.extend({preparations:e6.array(e6.object({id:e6.string().min(1).nullable().optional(),kind:e6.enum(["WRITE","DELETE","ASSUME_UNCHANGED"]),path:e6.string().min(1),contentBase64:e6.string().nullable().optional()})).max(500)}),outputSchema:e6.object({preparations:e6.array(rR)}),annotations:at,handler:async({repositoryId:e,preparations:t})=>(await r.saveRepositoryPreparations(e,t),{preparations:(await r.repositoryPreparations(e)).map(rD)})}),an({name:"get_codebase_settings",title:"Get codebase settings",description:"Get global codebase refresh, fetch, and branch settings.",inputSchema:ry,outputSchema:rw,annotations:i7,handler:async()=>{let e=await r.settings();return{settings:{refreshIntervalSeconds:e.refreshIntervalSeconds,fetchIntervalSeconds:e.fetchIntervalSeconds,defaultJiraBranchRegex:e.defaultJiraBranchRegex,updatedAt:e.updatedAt.toISOString()}}}}),an({name:"browse_agent_directory",title:"Browse agent directory",description:"List candidate repository folders on an enrolled agent.",inputSchema:rb,outputSchema:rv,annotations:i7,handler:async({agentId:e,path:t,requestId:i})=>({listing:await r.browse(e,t,i)})}),an({name:"inspect_agent_codebase",title:"Inspect agent codebase",description:"Inspect a repository folder without registering or changing it.",inputSchema:rk,outputSchema:rE,annotations:i7,handler:async({agentId:e,folder:t,requestId:i})=>({inspection:re(await r.inspect(e,t,i))})}),an({name:"refresh_codebases",title:"Refresh codebases",description:"Queue local metadata refreshes for registered codebases.",inputSchema:rS,outputSchema:rI,annotations:ae,handler:async({codebaseIds:e,requestId:t})=>{let i=await r.runOperation(rg.CODEBASE_REFRESH_JOB_KIND,e,t);return{jobs:i.jobs.map(e=>t7(e)),skipped:i.skipped}}}),an({name:"fetch_codebases",title:"Fetch codebases",description:"Queue remote Git fetches and configured base-branch updates.",inputSchema:rS,outputSchema:rI,annotations:{...ae,openWorldHint:!0},handler:async({codebaseIds:e,requestId:t})=>{let i=await r.runOperation(rg.CODEBASE_FETCH_JOB_KIND,e,t);return{jobs:i.jobs.map(e=>t7(e)),skipped:i.skipped}}}),an({name:"inspect_codebase_git_state",title:"Inspect codebase Git state",description:"Inspect branches, checkout locations, and stashes.",inputSchema:rA,outputSchema:rx,annotations:i7,handler:async({codebaseId:e,requestId:t})=>({state:await r.inspectGitState(e,t)})}),an({name:"inspect_codebase_stash",title:"Inspect codebase stash",description:"Read a bounded textual patch for a Git stash.",inputSchema:r_,outputSchema:rC,annotations:i7,handler:async({codebaseId:e,stashOid:t,requestId:i})=>({diff:await r.inspectStash(e,t,i)})}))),{id:"builtin:codebases",name:"Codebases",tools:P,children:[]})];return e.builds&&j.push((i=e.builds,{id:"builtin:builds",name:"Builds",children:[],tools:[an({name:"get_builds",title:"Get builds",description:"List immutable iOS build records.",inputSchema:ru.GetBuildsInputSchema,outputSchema:ru.GetBuildsOutputSchema,annotations:i7,handler:async e=>{let t=await i.builds(e);return{builds:t.items,nextCursor:t.nextCursor}}}),an({name:"get_build",title:"Get build",description:"Get a build with sanitized logs.",inputSchema:ru.GetBuildInputSchema,outputSchema:ru.GetBuildOutputSchema,annotations:i7,handler:async({buildId:e,afterLogId:t,logLimit:r})=>{let a=await i.getBuild(e);if(!a)throw Error("Build not found");return{build:a,logs:await i.logChunks(e,t,r)}}}),an({name:"get_build_configurations",title:"Get build configurations",description:"List build configurations for a worktree.",inputSchema:ru.GetBuildConfigurationsInputSchema,outputSchema:ru.GetBuildConfigurationsOutputSchema,annotations:i7,handler:async({worktreeId:e})=>({project:await i.projectForWorktree(e)})}),an({name:"get_build_destinations",title:"Get build destinations",description:"Inspect compatible build destinations.",inputSchema:ru.GetBuildDestinationsInputSchema,outputSchema:ru.GetBuildDestinationsOutputSchema,annotations:i7,handler:async e=>({destinations:"buildId"in e?await i.destinationsForBuild(e.buildId,e.requestId):await i.destinations(e)})}),an({name:"start_build",title:"Start build",description:"Queue an iOS build.",inputSchema:ru.StartBuildToolInputSchema,outputSchema:ru.StartBuildToolOutputSchema,annotations:ae,handler:async e=>({build:await i.startBuild(e)})}),an({name:"import_coverage_report",title:"Import coverage report",description:"Record a coverage file from a worktree as a coverage report.",inputSchema:ru.ImportCoverageReportToolInputSchema,outputSchema:ru.ImportCoverageReportToolOutputSchema,annotations:ae,handler:async e=>({build:await i.importCoverageReport(e)})}),an({name:"cancel_build",title:"Cancel build",description:"Cancel an active build.",inputSchema:ru.CancelBuildToolInputSchema,outputSchema:ru.CancelBuildToolOutputSchema,annotations:at,handler:async({buildId:e})=>({build:await i.cancelBuild(e)})}),an({name:"run_build",title:"Run build",description:"Install and launch without rebuilding.",inputSchema:ru.RunBuildToolInputSchema,outputSchema:ru.RunBuildToolOutputSchema,annotations:ae,handler:async e=>({deployments:await i.runBuild(e)})}),an({name:"export_build_archive",title:"Export build archive",description:"Export an archive to a local IPA folder.",inputSchema:ru.ExportBuildToolInputSchema,outputSchema:ru.ExportBuildToolOutputSchema,annotations:ae,handler:async e=>({export:await i.exportArchive(e)})}),rm({name:"get_build_project",title:"Get build project",description:"Get the iOS build project configured for a codebase.",inputSchema:e6.object({codebaseId:e6.string().min(1)}),service:i,method:"project",arguments:({codebaseId:e})=>[e],resultKey:"project"}),rm({name:"create_build_project",title:"Create build project",description:"Create an iOS build project for a codebase.",inputSchema:e6.object({codebaseId:e6.string().min(1)}),service:i,method:"createProject",arguments:({codebaseId:e})=>[e],resultKey:"project",annotations:{...ae,idempotentHint:!1}}),rm({name:"save_build_configuration",title:"Save build configuration",description:"Create or update an iOS build configuration.",inputSchema:e6.object({input:e6.record(e6.string(),e6.unknown())}),service:i,method:"saveConfiguration",arguments:({input:e})=>[e],resultKey:"configuration",annotations:ae}),rm({name:"delete_build_configuration",title:"Delete build configuration",description:"Delete an iOS build configuration.",inputSchema:e6.object({id:e6.string().min(1)}),service:i,method:"deleteConfiguration",arguments:({id:e})=>[e],resultKey:"deleted",annotations:at}),rm({name:"discover_build_sources",title:"Discover build sources",description:"Discover Xcode projects and workspaces in a worktree.",inputSchema:e6.object({worktreeId:e6.string().min(1),requestId:e6.string().min(1)}),service:i,method:"discoverSources",arguments:e=>[e.worktreeId,e.requestId],resultKey:"sources",annotations:ae}),rm({name:"inspect_build_source",title:"Inspect build source",description:"Inspect schemes, configurations, and targets for an Xcode source.",inputSchema:e6.object({input:e6.record(e6.string(),e6.unknown())}),service:i,method:"inspectSource",arguments:({input:e})=>[e],resultKey:"inspection",annotations:ae}),rm({name:"get_build_scripts",title:"Get build scripts",description:"List reusable build scripts.",inputSchema:e6.object({}),service:i,method:"scripts",arguments:()=>[],resultKey:"scripts"}),rm({name:"save_build_script",title:"Save build script",description:"Create or update a reusable build script.",inputSchema:e6.object({input:e6.record(e6.string(),e6.unknown())}),service:i,method:"saveScript",arguments:({input:e})=>[e],resultKey:"script",annotations:ae}),rm({name:"delete_build_script",title:"Delete build script",description:"Delete a reusable build script.",inputSchema:e6.object({id:e6.string().min(1)}),service:i,method:"deleteScript",arguments:({id:e})=>[e],resultKey:"deleted",annotations:at}),rm({name:"rebuild_build",title:"Rebuild build",description:"Queue a new build from an existing build snapshot.",inputSchema:e6.object({buildId:e6.string().min(1),requestId:e6.string().min(1)}),service:i,method:"rebuildBuild",arguments:e=>[e.buildId,e.requestId,null],resultKey:"build",annotations:ae}),rm({name:"delete_builds",title:"Delete builds",description:"Permanently delete build records and their retained data.",inputSchema:e6.object({ids:e6.array(e6.string().min(1)).min(1)}),service:i,method:"deleteBuilds",arguments:({ids:e})=>[e],resultKey:"count",annotations:at}),rm({name:"get_build_reports",title:"Get build reports",description:"Get parsed test and coverage reports for a build.",inputSchema:e6.object({buildId:e6.string().min(1)}),service:i,method:"reportsForBuild",arguments:({buildId:e})=>[e],resultKey:"reports"}),rm({name:"generate_build_report",title:"Generate build report",description:"Generate a parsed test-results or code-coverage report.",inputSchema:e6.object({buildId:e6.string().min(1),kind:e6.enum(["TEST_RESULTS","CODE_COVERAGE"]),requestId:e6.string().min(1)}),service:i,method:"generateReport",arguments:e=>[e.buildId,e.kind,e.requestId],resultKey:"report",annotations:ae}),rm({name:"start_worktree_coverage",title:"Start worktree coverage",description:"Start the configured coverage workflow for a worktree.",inputSchema:e6.object({input:e6.record(e6.string(),e6.unknown())}),service:i,method:"startWorktreeCoverage",arguments:({input:e})=>[e],resultKey:"build",annotations:ae}),rm({name:"get_worktree_coverage",title:"Get worktree coverage",description:"Get coverage history for a worktree.",inputSchema:e6.object({worktreeId:e6.string().min(1)}),service:i,method:"coverageHistory",arguments:({worktreeId:e})=>[e],resultKey:"history"})]})),e.telemetry&&e.pushNotifications&&j.push((a=e.telemetry,n=e.pushNotifications,(L=r5(a,"UNIFIED",{plural:"unified_events",singular:"unified_event",label:"Unified Events"})).push(an({name:"get_telemetry_separators",title:"Get telemetry separators",description:"List global manual and build separators with optional filters.",inputSchema:e6.object({first:e6.number().int().min(1).max(500).default(100),after:e6.string().nullable().default(null),kind:e6.string().min(1).nullable().optional(),name:e6.string().min(1).nullable().optional(),buildId:e6.string().min(1).nullable().optional()}),outputSchema:e6.object({items:e6.array(rJ),nextCursor:e6.string().nullable()}),annotations:i7,handler:e=>a.separators(e)}),an({name:"add_telemetry_separator",title:"Add telemetry separator",description:"Add a global manual separator to all telemetry views.",inputSchema:e6.object({name:e6.string().max(100).nullable().default(null)}),outputSchema:e6.object({separator:rJ}),annotations:{...ae,idempotentHint:!1},handler:async({name:e})=>({separator:await a.addSeparator(e)})}),an({name:"get_telemetry_settings",title:"Get telemetry settings",description:"Get telemetry collection state and effective ingestion URLs.",inputSchema:e6.object({}),outputSchema:e6.object({settings:e6.object({localBaseUrlOverride:e6.string().nullable(),remoteBaseUrlOverride:e6.string().nullable(),consoleCollectionEnabled:e6.boolean(),analyticsCollectionEnabled:e6.boolean(),detectedLocalBaseUrl:e6.string(),detectedRemoteBaseUrl:e6.string(),effectiveLocalBaseUrl:e6.string(),effectiveRemoteBaseUrl:e6.string(),updatedAt:e6.string()})}),annotations:i7,handler:async()=>({settings:await a.settings()})}),rm({name:"update_telemetry_settings",title:"Update telemetry settings",description:"Update telemetry collection and ingestion URL settings.",inputSchema:e6.object({localBaseUrlOverride:e6.string().nullable().optional(),remoteBaseUrlOverride:e6.string().nullable().optional(),consoleCollectionEnabled:e6.boolean().nullable().optional(),analyticsCollectionEnabled:e6.boolean().nullable().optional()}),service:a,method:"saveSettings",resultKey:"settings",annotations:ae}),rm({name:"get_telemetry_view_settings",title:"Get telemetry view settings",description:"Get display settings for a telemetry view.",inputSchema:e6.object({view:e6.enum(["UNIFIED","CONSOLE","ANALYTICS"])}),service:a,method:"viewSettings",arguments:({view:e})=>[e],resultKey:"settings"}),rm({name:"update_telemetry_highlight",title:"Update telemetry highlight",description:"Set or clear the highlight color on a telemetry entry.",inputSchema:e6.object({id:e6.string().min(1),color:e6.string().nullable().optional()}),service:a,method:"highlight",arguments:({id:e,color:t})=>[e,t??null],resultKey:"entry",annotations:ae}),rm({name:"get_telemetry_presets",title:"Get telemetry presets",description:"List saved column presets for a telemetry view.",inputSchema:e6.object({view:e6.enum(["UNIFIED","CONSOLE","ANALYTICS"])}),service:a,method:"columnPresets",arguments:({view:e})=>[e],resultKey:"presets"}),rm({name:"save_telemetry_preset",title:"Save telemetry preset",description:"Create or update a telemetry column preset.",inputSchema:e6.object({input:e6.record(e6.string(),e6.unknown())}),service:a,method:"saveColumnPreset",arguments:({input:e})=>[e],resultKey:"preset",annotations:ae}),rm({name:"get_saved_telemetry_filters",title:"Get saved telemetry filters",description:"List saved filters for a telemetry view.",inputSchema:e6.object({view:e6.enum(["UNIFIED","CONSOLE","ANALYTICS"])}),service:a,method:"savedFilters",arguments:({view:e})=>[e],resultKey:"filters"}),rm({name:"save_telemetry_filter",title:"Save telemetry filter",description:"Create or update a saved telemetry filter.",inputSchema:e6.object({input:e6.record(e6.string(),e6.unknown())}),service:a,method:"saveFilter",arguments:({input:e})=>[e],resultKey:"filter",annotations:ae}),rm({name:"export_telemetry",title:"Export telemetry",description:"Export a bounded telemetry query as structured JSON.",inputSchema:e6.object({view:e6.enum(["UNIFIED","CONSOLE","ANALYTICS"]).default("UNIFIED"),search:e6.string().nullable().optional(),first:e6.number().int().min(1).max(5e3).default(1e3)}),service:a,method:"timeline",resultKey:"export"})),{id:"builtin:debugging",name:"Debugging",tools:L,children:[{id:"builtin:debugging:console-logs",name:"Console Logs",tools:r5(a,"CONSOLE",{plural:"console_logs",singular:"console_log",label:"Console Logs"}),children:[]},{id:"builtin:debugging:analytics-events",name:"Analytics Events",tools:r5(a,"ANALYTICS",{plural:"analytics_events",singular:"analytics_event",label:"Analytics Events"}),children:[]},(B={...ae,openWorldHint:!0},{id:"builtin:debugging:push-notifications",name:"Push Notifications",children:[],tools:[an({name:"get_push_notification_registrations",title:"Get push notification registrations",description:"List registered APNs devices with masked tokens.",inputSchema:e6.object({}),outputSchema:e6.object({registrations:e6.array(rL)}),annotations:i7,handler:async()=>({registrations:(await n.registrations()).map(e=>{let t,r;return t=Array.isArray(e.supportedPushTypes)?e.supportedPushTypes:rP(e.pushTypesJson),r="string"==typeof e.token?e.token:"",{id:String(e.id),clientRegistrationId:String(e.clientRegistrationId),tokenMasked:"string"==typeof e.tokenMasked?e.tokenMasked:r?`${r.slice(0,8)}…${r.slice(-8)}`:"—",topic:String(e.topic),environment:String(e.environment),supportedPushTypes:Array.isArray(t)?t:[],displayName:String(e.displayName),deviceModel:"string"==typeof e.deviceModel?e.deviceModel:null,osVersion:"string"==typeof e.osVersion?e.osVersion:null,appVersion:"string"==typeof e.appVersion?e.appVersion:null,appBuild:"string"==typeof e.appBuild?e.appBuild:null,locale:"string"==typeof e.locale?e.locale:null,pushMagicConfigured:!!e.pushMagic,status:String(e.status),invalidatedAt:rO(e.invalidatedAt),lastFailureReason:"string"==typeof e.lastFailureReason?e.lastFailureReason:null,lastFailureAt:rO(e.lastFailureAt),lastRegisteredAt:rO(e.lastRegisteredAt),lastSentAt:rO(e.lastSentAt),createdAt:rO(e.createdAt),updatedAt:rO(e.updatedAt)}})})}),an({name:"get_push_notification_settings",title:"Get push notification settings",description:"Inspect APNs credential status without returning secrets.",inputSchema:e6.object({}),outputSchema:e6.object({settings:rU}),annotations:i7,handler:async()=>{var e;return{settings:{tokenConfigured:!!(e=await n.settings()).tokenConfigured,tokenTeamId:"string"==typeof e.tokenTeamId?e.tokenTeamId:null,tokenKeyId:"string"==typeof e.tokenKeyId?e.tokenKeyId:null,tokenPrivateKeyFingerprint:"string"==typeof e.tokenPrivateKeyFingerprint?e.tokenPrivateKeyFingerprint:null,tokenConfiguredAt:rO(e.tokenConfiguredAt),tokenLastUsedAt:rO(e.tokenLastUsedAt),tokenLastError:"string"==typeof e.tokenLastError?e.tokenLastError:null,certificates:Array.isArray(e.certificates)?e.certificates.map(e=>({id:String(e.id),name:String(e.name),topic:String(e.topic),environment:String(e.environment),fingerprint:String(e.fingerprint),expiresAt:rO(e.expiresAt),lastTestedAt:rO(e.lastTestedAt),lastError:"string"==typeof e.lastError?e.lastError:null,createdAt:rO(e.createdAt),updatedAt:rO(e.updatedAt)})):[],updatedAt:rO(e.updatedAt)}}}}),an({name:"get_push_notification_channels",title:"Get push notification channels",description:"List configured APNs broadcast channels.",inputSchema:e6.object({}),outputSchema:e6.object({channels:e6.array(rj)}),annotations:i7,handler:async()=>({channels:(await n.channels()).map(e=>({id:String(e.id),channelId:String(e.channelId),bundleId:String(e.bundleId),environment:String(e.environment),storagePolicy:String(e.storagePolicy),createdAt:rO(e.createdAt),updatedAt:rO(e.updatedAt)}))})}),an({name:"get_push_notification_presets",title:"Get push notification presets",description:"List saved, validated push editor presets.",inputSchema:e6.object({}),outputSchema:e6.object({presets:e6.array(rM)}),annotations:i7,handler:async()=>({presets:(await n.presets()).map(e=>({id:String(e.id),name:String(e.name),editor:rP(e.editor??e.editorJson),createdAt:rO(e.createdAt),updatedAt:rO(e.updatedAt)}))})}),an({name:"get_push_notification_history",title:"Get push notification history",description:"List recent push batches and per-recipient delivery results.",inputSchema:e6.object({limit:e6.number().int().min(1).max(200).default(100)}),outputSchema:e6.object({batches:e6.array(r$)}),annotations:i7,handler:async({limit:e})=>({batches:(await n.history(e)).map(e=>rF(e))})}),an({name:"get_push_notification_history_item",title:"Get push notification history item",description:"Get one push batch and all delivery results by ID.",inputSchema:e6.object({id:e6.string().min(1)}),outputSchema:e6.object({batch:r$.nullable()}),annotations:i7,handler:async({id:e})=>{let t=await n.historyItem(e);return{batch:t?rF(t):null}}}),an({name:"preview_push_notification",title:"Preview push notification",description:"Validate an editor and return its final payload and APNs headers.",inputSchema:e6.object({editor:e6.record(e6.string(),e6.unknown())}),outputSchema:e6.object({editor:e6.unknown(),payload:e6.unknown(),headers:e6.record(e6.string(),e6.string()),byteLength:e6.number().int().nonnegative()}),annotations:i7,handler:({editor:e})=>(0,rN.validatePushEditor)(e)}),an({name:"send_push_notification",title:"Send push notification",description:"Validate and queue a raw APNs editor payload for delivery.",inputSchema:rH,outputSchema:e6.object({batch:r$}),annotations:B,handler:async e=>({batch:rF(await n.send(rW(e)))})}),an({name:"send_push_notification_preset",title:"Send push notification preset",description:"Load a saved preset by ID and queue it for APNs delivery.",inputSchema:rV,outputSchema:e6.object({batch:r$}),annotations:B,handler:async e=>{let t=await n.preset(e.presetId);if(!t)throw Error("Push notification preset not found");let r={...e,editor:rP(t.editorJson)};return{batch:rF(await n.send(rW(r)))}}}),an({name:"resend_push_notification",title:"Resend push notification",description:"Queue a historical non-draft, non-direct batch again.",inputSchema:e6.object({id:e6.string().min(1),requestId:e6.string().min(1)}),outputSchema:e6.object({batch:r$}),annotations:B,handler:async({id:e,requestId:t})=>({batch:rF(await n.resend(e,t))})}),an({name:"rename_push_registration",title:"Rename push registration",description:"Rename an APNs device registration.",inputSchema:e6.object({id:e6.string().min(1),displayName:e6.string().min(1)}),outputSchema:e6.object({registration:e6.unknown()}),annotations:ae,handler:async({id:e,displayName:t})=>({registration:await n.renameRegistration(e,t)})}),an({name:"set_push_registration_enabled",title:"Set push registration enabled",description:"Enable or disable an APNs device registration.",inputSchema:e6.object({id:e6.string().min(1),enabled:e6.boolean()}),outputSchema:e6.object({registration:e6.unknown()}),annotations:ae,handler:async({id:e,enabled:t})=>({registration:await n.setRegistrationActive(e,t)})}),an({name:"delete_push_registration",title:"Delete push registration",description:"Permanently delete an APNs device registration.",inputSchema:e6.object({id:e6.string().min(1)}),outputSchema:e6.object({deleted:e6.unknown()}),annotations:at,handler:async({id:e})=>({deleted:await n.deleteRegistration(e)})}),an({name:"save_push_preset",title:"Save push preset",description:"Create or update a reusable push-notification preset.",inputSchema:e6.object({id:e6.string().nullable().optional(),name:e6.string().min(1),editor:e6.record(e6.string(),e6.unknown())}),outputSchema:e6.object({preset:e6.unknown()}),annotations:ae,handler:async({id:e,name:t,editor:r})=>({preset:await n.savePreset(t,r,e)})}),an({name:"delete_push_preset",title:"Delete push preset",description:"Delete a saved push-notification preset.",inputSchema:e6.object({id:e6.string().min(1)}),outputSchema:e6.object({deleted:e6.unknown()}),annotations:at,handler:async({id:e})=>({deleted:await n.deletePreset(e)})}),an({name:"delete_push_history",title:"Delete push history",description:"Delete one push-notification history batch.",inputSchema:e6.object({id:e6.string().min(1)}),outputSchema:e6.object({deleted:e6.unknown()}),annotations:at,handler:async({id:e})=>({deleted:await n.deleteHistory(e)})}),an({name:"clear_push_history",title:"Clear push history",description:"Permanently clear all push-notification history.",inputSchema:e6.object({}),outputSchema:e6.object({count:e6.unknown()}),annotations:at,handler:async()=>({count:await n.clearHistory()})}),an({name:"create_push_channel",title:"Create push channel",description:"Create a push-notification broadcast channel.",inputSchema:e6.object({input:e6.record(e6.string(),e6.unknown())}),outputSchema:e6.object({channel:e6.unknown()}),annotations:ae,handler:async({input:e})=>({channel:await n.createChannel(e)})}),an({name:"delete_push_channel",title:"Delete push channel",description:"Delete a push-notification broadcast channel.",inputSchema:e6.object({id:e6.string().min(1)}),outputSchema:e6.object({deleted:e6.unknown()}),annotations:at,handler:async({id:e})=>({deleted:await n.deleteChannel(e)})}),an({name:"retest_push_certificate",title:"Retest push certificate",description:"Retest an existing APNs certificate credential without returning its secret material.",inputSchema:e6.object({id:e6.string().min(1)}),outputSchema:e6.object({credential:e6.unknown()}),annotations:ae,handler:async({id:e})=>({credential:await n.retestCertificateCredential(e)})})]})]})),e.agents&&j.push((s=e.agents,{id:"builtin:agents",name:"Agents",children:[],tools:[an({name:"get_agents",title:"Get agents",description:"List enrolled agents, capabilities, resources, and status.",inputSchema:ra,outputSchema:e6.object({agents:e6.array(rn)}),annotations:i7,handler:async()=>({agents:(await s.listAgents()).map(e=>t5(e))})}),an({name:"get_agent",title:"Get agent",description:"Get one enrolled agent by ID.",inputSchema:rc,outputSchema:e6.object({agent:rn.nullable()}),annotations:i7,handler:async({agentId:e})=>{let t=await s.getAgent(e);return{agent:t?t5(t):null}}}),an({name:"get_agent_settings",title:"Get agent settings",description:"Get repository, build, and Derived Data paths for an agent.",inputSchema:rc,outputSchema:e6.object({settings:rs}),annotations:i7,handler:async({agentId:e})=>{let t=await s.getAgent(e);if(!t)throw Error("Agent not found");return{settings:t9(t)}}}),an({name:"get_agent_jobs",title:"Get agent jobs",description:"List recent user-visible jobs for an agent.",inputSchema:e6.object({agentId:e6.string().min(1),limit:e6.number().int().min(1).max(200).default(50)}),outputSchema:e6.object({jobs:e6.array(ro)}),annotations:i7,handler:async({agentId:e,limit:t})=>({jobs:(await s.listJobs(e,t)).map(e=>t7(e))})}),an({name:"get_agent_job",title:"Get agent job",description:"Get one agent job and its result by ID.",inputSchema:e6.object({jobId:e6.string().min(1)}),outputSchema:e6.object({job:ro.nullable()}),annotations:i7,handler:async({jobId:e})=>{let t=await s.getJob(e);return{job:t?t7(t):null}}}),an({name:"get_agent_job_logs",title:"Get agent job logs",description:"Fetch ordered job logs after an optional sequence number.",inputSchema:e6.object({jobId:e6.string().min(1),afterSequence:e6.number().int().min(-1).default(-1)}),outputSchema:e6.object({logs:e6.array(rl)}),annotations:i7,handler:async({jobId:e,afterSequence:t})=>({logs:(await s.listLogs(e,t)).map(e=>({id:String(e.id),jobId:String(e.jobId),sequence:Number(e.sequence),stream:String(e.stream),message:String(e.message),createdAt:t8(e.createdAt)}))})}),an({name:"update_agent_base_repo_directory",title:"Update agent base repository directory",description:"Set or reset the absolute base repository directory.",inputSchema:e6.object({agentId:e6.string().min(1),baseRepoDirectory:e6.string().min(1).nullable()}),outputSchema:e6.object({settings:rs}),annotations:ae,handler:async({agentId:e,baseRepoDirectory:t})=>({settings:t9(await s.updateBaseRepoDirectory(e,t))})}),an({name:"update_agent_builds_directory",title:"Update agent builds directory",description:"Set or reset the absolute build-output directory.",inputSchema:e6.object({agentId:e6.string().min(1),buildsDirectory:e6.string().min(1).nullable()}),outputSchema:e6.object({settings:rs}),annotations:ae,handler:async({agentId:e,buildsDirectory:t})=>({settings:t9(await s.updateBuildsDirectory(e,t))})}),an({name:"update_agent_derived_data_settings",title:"Update agent Derived Data settings",description:"Set default, absolute, or worktree-relative Derived Data paths.",inputSchema:e6.object({agentId:e6.string().min(1),mode:e6.enum(["DEFAULT","ABSOLUTE","RELATIVE"]),path:e6.string().min(1).nullable().default(null)}),outputSchema:e6.object({settings:rs}),annotations:ae,handler:async({agentId:e,mode:t,path:r})=>({settings:t9(await s.updateDerivedDataSettings(e,t,r))})}),an({name:"request_agent_codebase_reconcile",title:"Request agent codebase reconcile",description:"Ask an online agent to reconcile its registered codebases.",inputSchema:rc,outputSchema:e6.object({requested:e6.boolean()}),annotations:ae,handler:async({agentId:e})=>({requested:await s.requestCodebaseReconcile([e])===1})}),an({name:"cancel_agent_job",title:"Cancel agent job",description:"Cancel a queued or running agent job.",inputSchema:e6.object({jobId:e6.string().min(1)}),outputSchema:e6.object({job:ro}),annotations:at,handler:async({jobId:e})=>({job:t7(await s.cancelJob(e))})}),an({name:"get_agent_cadence_settings",title:"Get agent cadence settings",description:"Get effective scan, reconciliation, fetch, and heartbeat intervals for an agent.",inputSchema:rc,outputSchema:e6.object({settings:e6.unknown()}),handler:async({agentId:e})=>({settings:await s.cadenceSettings(e)})}),an({name:"update_agent_cadence_settings",title:"Update agent cadence settings",description:"Update scan, reconciliation, fetch, and heartbeat intervals for an agent.",inputSchema:rc.extend({settings:e6.object({codebaseScanIntervalSeconds:e6.number().int().positive(),jobReconciliationIntervalSeconds:e6.number().int().positive(),gitFetchIntervalSeconds:e6.number().int().positive(),heartbeatIntervalSeconds:e6.number().int().positive()})}),outputSchema:e6.object({settings:e6.unknown()}),annotations:ae,handler:async({agentId:e,settings:t})=>({settings:await s.updateCadenceSettings(e,t)})}),an({name:"delete_agent",title:"Delete agent",description:"Permanently delete an enrolled agent and its control-plane records.",inputSchema:rc,outputSchema:e6.object({deleted:e6.boolean()}),annotations:at,handler:async({agentId:e})=>({deleted:await s.deleteAgent(e)})})]})),e.diskSpace&&j.push((o=e.diskSpace,{id:"builtin:disk-space",name:"Disk Space",children:[],tools:[an({name:"get_disk_space_overview",title:"Get disk-space overview",description:"Get global thresholds and canonical Derived Data disk snapshots for every agent.",inputSchema:e6.object({}),outputSchema:e6.object({settings:ic,agents:e6.array(im)}),annotations:i7,handler:async()=>{let e=await o.overview();return{settings:e.settings,agents:e.agents.map(t=>ii(e.settings,t))}}}),an({name:"get_disk_space_settings",title:"Get disk-space settings",description:"Get global disk thresholds and report timing settings.",inputSchema:e6.object({}),outputSchema:e6.object({settings:ic}),annotations:i7,handler:async()=>({settings:await o.settings()})}),an({name:"get_agent_disk_space",title:"Get agent disk space",description:"Get one agent's canonical Derived Data disk-space monitor snapshot.",inputSchema:ig,outputSchema:e6.object({snapshot:im}),annotations:i7,handler:async({agentId:e})=>({snapshot:await o.snapshot(e)})}),an({name:"update_disk_space_settings",title:"Update disk-space settings",description:"Update the global normal and pressure free-space thresholds in GiB.",inputSchema:e6.object({normalThresholdGiB:e6.number().positive(),pressureThresholdGiB:e6.number().positive()}),outputSchema:e6.object({settings:ic}),annotations:ae,handler:async e=>({settings:await o.updateSettings(e)})}),an({name:"set_agent_disk_space_monitoring",title:"Set agent disk-space monitoring",description:"Enable or disable Derived Data disk-space monitoring for an agent.",inputSchema:ig.extend({enabled:e6.boolean()}),outputSchema:e6.object({snapshot:im}),annotations:ae,handler:async({agentId:e,enabled:t})=>(await o.setMonitoring(e,t),{snapshot:await o.snapshot(e)})}),an({name:"set_agent_disk_space_pressure_mode",title:"Set agent disk pressure mode",description:"Enable or clear manual disk pressure mode for an agent.",inputSchema:ig.extend({enabled:e6.boolean()}),outputSchema:e6.object({snapshot:im}),annotations:ae,handler:async({agentId:e,enabled:t})=>(await o.setManualPressureMode(e,t),{snapshot:await o.snapshot(e)})}),an({name:"request_agent_disk_space_refresh",title:"Request agent disk-space refresh",description:"Ask an agent to collect and report disk-space telemetry immediately.",inputSchema:ig,outputSchema:e6.object({agentId:e6.string(),requestedAt:e6.string(),previousReportedAt:e6.string().nullable()}),annotations:ae,handler:async({agentId:e})=>o.requestRefresh(e)})]})),e.worktrees&&j.push({id:"builtin:worktrees",name:"Worktrees",children:[],tools:[rm({name:"get_worktrees",title:"Get worktrees",description:"Get the current worktree overview grouped by agent and codebase.",inputSchema:rf,service:l=e.worktrees,method:"overview",arguments:()=>[],resultKey:"overview"}),an({name:"get_worktree_preparation_overview",title:"Get worktree preparation overview",description:"Get persisted per-file preparation status for every repository worktree, including unsupported and offline worktrees.",inputSchema:rf,outputSchema:e6.object({overview:i8}),handler:async()=>({overview:{repositories:(await l.preparationOverview()).repositories.map(({repository:e,worktrees:t})=>({repository:{id:e.id,name:e.name,canonicalOrigin:e.canonicalOrigin,displayOrigin:e.displayOrigin},preparations:e.preparations.map(e=>({id:e.id,kind:e.kind,path:e.path,contentSha256:e.contentSha256,byteCount:e.byteCount,definitionHash:e.definitionHash})),worktrees:t.map(e=>({worktree:{id:e.worktree.id,codebaseId:e.worktree.codebaseId,folder:e.worktree.folder,relativePath:e.worktree.relativePath,branch:e.worktree.branch,baseBranch:e.worktree.baseBranch,primary:e.worktree.primary,availability:e.worktree.availability,missingAt:e.worktree.missingAt?.toISOString()??null},agent:{id:e.agent.id,name:e.agent.name,hostname:e.agent.hostname,version:e.agent.version},supported:e.supported,unsupportedReason:e.unsupportedReason,overallState:e.overallState,statuses:e.statuses.map(e=>({preparationId:e.preparation.id,kind:e.preparation.kind,path:e.preparation.path,definitionHash:e.preparation.definitionHash,state:e.state,message:e.message,checkedAt:e.checkedAt?.toISOString()??null})),activeJob:e.activeJob?{id:e.activeJob.id,status:e.activeJob.status}:null}))}))}})}),an({name:"run_worktree_preparations",title:"Run worktree preparations",description:"Inspect, apply, or undo repository preparations for up to 500 worktrees. Returns dispatched jobs and explicit skip reasons.",inputSchema:i4,outputSchema:e6.object({jobs:e6.array(e6.unknown()),skipped:e6.array(e6.object({worktreeId:e6.string(),reason:e6.string()}))}),handler:e=>l.runPreparations(e.worktreeIds,e.action,e.requestId),annotations:at}),an({name:"get_worktree",title:"Get worktree",description:"Get one current worktree by ID.",inputSchema:i1,outputSchema:e6.object({worktree:e6.unknown().nullable()}),handler:async({id:e})=>({worktree:(await l.overview()).agents.flatMap(e=>e.codebases).flatMap(e=>e.worktrees).find(t=>t.id===e)??null})}),rm({name:"get_hidden_worktrees",title:"Get hidden worktrees",description:"List worktrees no longer present on their agents.",inputSchema:rf,service:l,method:"hidden",arguments:()=>[],resultKey:"worktrees"}),rm({name:"inspect_worktree",title:"Inspect worktree",description:"Request a fresh inspection of a worktree.",inputSchema:i2,service:l,method:"inspect",arguments:e=>[e.worktreeId,e.requestId],resultKey:"job",annotations:ae}),rm({name:"inspect_worktree_diff",title:"Inspect worktree diff",description:"Inspect a worktree diff for a scope, file, or commit.",inputSchema:i2.extend({scope:e6.string().min(1),path:e6.string().nullable().optional(),previousPath:e6.string().nullable().optional(),commitSha:e6.string().nullable().optional()}),service:l,method:"inspectDiff",arguments:e=>[e.worktreeId,{scope:e.scope,path:e.path,previousPath:e.previousPath,commitSha:e.commitSha},e.requestId],resultKey:"inspection",annotations:ae}),rm({name:"refresh_worktrees",title:"Refresh worktrees",description:"Ask connected agents to refresh their worktree reports.",inputSchema:rf,service:l,method:"requestRefresh",arguments:()=>[],resultKey:"requested",annotations:ae}),rm({name:"refresh_worktree_pull_request",title:"Refresh worktree pull request",description:"Refresh the GitHub pull request attached to a worktree.",inputSchema:i1,service:l,method:"refreshPullRequest",arguments:({id:e})=>[e],resultKey:"worktree",annotations:ae}),rm({name:"create_worktree",title:"Create worktree",description:"Create a worktree from a new, existing, or Jira ticket branch.",inputSchema:e6.object({codebaseId:e6.string().min(1),selection:i3,requestId:e6.string().min(1)}),service:l,method:"createWorktree",resultKey:"worktree",annotations:{...ae,idempotentHint:!1}}),rm({name:"change_worktree_branch",title:"Change worktree branch",description:"Switch a worktree to another branch selection.",inputSchema:e6.object({worktreeId:e6.string().min(1),selection:i3,requestId:e6.string().min(1),stashOnFailure:e6.boolean().nullable().optional()}),service:l,method:"changeWorktreeBranch",resultKey:"job",annotations:ae}),rm({name:"commit_worktree",title:"Commit worktree changes",description:"Stage all or an exact set of changed paths and create a Git commit in a worktree.",inputSchema:i2.extend({message:e6.string().trim().min(1).max(5e4),signed:e6.boolean().nullable().optional(),stageAll:e6.boolean().default(!0),paths:e6.array(e6.string().min(1)).max(500).default([])}),service:l,method:"commitWorktree",resultKey:"job",annotations:ae}),rm({name:"move_worktree",title:"Move worktree",description:"Move work from one worktree into another codebase or worktree.",inputSchema:e6.object({sourceWorktreeId:e6.string().min(1),targetCodebaseId:e6.string().min(1),targetWorktreeId:e6.string().nullable().optional(),deleteSource:e6.boolean().default(!1),requestId:e6.string().min(1)}),service:l,method:"moveWorktree",resultKey:"move",annotations:ae}),rm({name:"retry_worktree_move_with_stash",title:"Retry worktree move with stash",description:"Retry a blocked worktree move after stashing changes.",inputSchema:i1,service:l,method:"retryWorktreeMoveWithStash",arguments:({id:e})=>[e],resultKey:"move",annotations:ae}),rm({name:"cancel_worktree_move",title:"Cancel worktree move",description:"Cancel an active worktree move.",inputSchema:i1,service:l,method:"cancelWorktreeMove",arguments:({id:e})=>[e],resultKey:"move",annotations:ae}),rm({name:"delete_worktree",title:"Delete worktree",description:"Delete a worktree and optionally its remote branch.",inputSchema:e6.object({worktreeId:e6.string().min(1),deleteRemoteBranch:e6.boolean().default(!1),requestId:e6.string().min(1)}),service:l,method:"deleteWorktree",resultKey:"job",annotations:at}),rm({name:"run_worktree_operation",title:"Run worktree operation",description:"Run a supported high-level operation in a worktree.",inputSchema:i2.extend({operation:e6.enum(i0.WORKTREE_OPERATIONS),forcePreparations:e6.boolean().default(!1)}),service:l,method:"runOperation",arguments:e=>[e.worktreeId,e.operation,e.requestId,e.forcePreparations],resultKey:"job",annotations:ae}),rm({name:"run_worktree_git_operation",title:"Run worktree Git operation",description:"Run a supported Git operation in a worktree.",inputSchema:i2.extend({operation:e6.enum(i0.WORKTREE_GIT_OPERATIONS),branch:e6.string().nullable().optional(),stashOid:e6.string().nullable().optional(),stashChanges:e6.boolean().nullable().optional()}),service:l,method:"runGitOperation",resultKey:"job",annotations:ae}),an({name:"update_worktree_metadata",title:"Update worktree metadata",description:"Update a worktree base branch and/or highlight color.",inputSchema:e6.object({id:e6.string().min(1),baseBranch:e6.string().nullable().optional(),highlightColor:e6.string().nullable().optional()}),outputSchema:e6.object({worktree:e6.unknown()}),annotations:ae,handler:async({id:e,baseBranch:t,highlightColor:r})=>{let i=null;if(void 0!==t&&(i=await l.updateBaseBranch(e,t)),void 0!==r&&(i=await l.updateHighlight(e,r)),void 0===t&&void 0===r)throw Error("At least one metadata field is required");return{worktree:i}}}),rm({name:"set_worktree_tags",title:"Set worktree tags",description:"Replace the tags assigned to a worktree.",inputSchema:e6.object({id:e6.string().min(1),tagIds:e6.array(e6.string().min(1))}),service:l,method:"setTags",arguments:e=>[e.id,e.tagIds],resultKey:"worktree",annotations:ae})]}),e.runs&&j.push((u=e.runs,{id:"builtin:agent-runs",name:"Agent Runs",children:[],tools:[rm({name:"get_agent_runs",title:"Get agent runs",description:"List agent runs with kind, archive, provider, origin, search, and pagination filters.",inputSchema:e6.object({kind:e6.enum(["SESSION","PLAN"]).default("SESSION"),search:e6.string().nullable().optional(),archive:e6.string().default("ACTIVE"),provider:e6.string().nullable().optional(),origin:e6.string().nullable().optional(),first:e6.number().int().min(1).max(200).default(100),after:e6.string().nullable().optional()}),service:u,method:"list",resultKey:"page"}),rm({name:"get_agent_run",title:"Get agent run",description:"Get an agent run without exposing its native session transcript.",inputSchema:ix,service:u,method:"get",arguments:({runId:e})=>[e],resultKey:"run"}),rm({name:"get_run_events",title:"Get run events",description:"Get normalized run events; native provider payloads are redacted.",inputSchema:ix.extend({search:e6.string().nullable().optional(),afterSequence:e6.number().int().default(-1),first:e6.number().int().min(1).max(500).default(200),includeSuperseded:e6.boolean().default(!1)}),service:u,method:"events",resultKey:"events"}),rm({name:"get_run_questions",title:"Get run questions",description:"Get question batches for a run.",inputSchema:ix.extend({first:e6.number().int().min(1).max(200).default(100),after:e6.string().nullable().optional()}),service:u,method:"questions",resultKey:"page"}),rm({name:"get_run_usage",title:"Get run usage",description:"Get token and cost usage summarized for a run.",inputSchema:ix,service:u,method:"usage",arguments:({runId:e})=>[e],resultKey:"usage"}),rm({name:"get_run_linked_items",title:"Get linked run items",description:"Get runs linked by follow-up, plan, or parent relationships.",inputSchema:ix,service:u,method:"linkedItems",arguments:({runId:e})=>[e],resultKey:"runs"}),rm({name:"get_run_provider_catalog",title:"Get run provider catalog",description:"Get provider, model, and reasoning-effort choices for a run or worktree.",inputSchema:e6.object({runId:e6.string().nullable().optional(),worktreeId:e6.string().nullable().optional()}),service:u,method:"providerCatalog",resultKey:"providers"}),rm({name:"create_agent_run",title:"Create agent run",description:"Create and queue a new agent run.",inputSchema:i_,service:u,method:"create",resultKey:"run",annotations:{...ae,idempotentHint:!1}}),rm({name:"play_plan",title:"Play plan",description:"Create a run from an existing plan run.",inputSchema:e6.object({planId:e6.string().min(1)}),service:u,method:"playPlan",arguments:({planId:e})=>[e],resultKey:"run",annotations:{...ae,idempotentHint:!1}}),rm({name:"create_run_follow_up",title:"Create run follow-up",description:"Create a follow-up run linked to a source run.",inputSchema:e6.object({sourceId:e6.string().min(1),input:i_}),service:u,method:"followUp",arguments:({sourceId:e,input:t})=>[e,t],resultKey:"run",annotations:{...ae,idempotentHint:!1}}),rm({name:"steer_agent_run",title:"Steer agent run",description:"Send additional guidance to an active run.",inputSchema:ix.extend({prompt:e6.string().min(1),attachmentIds:e6.array(e6.string().min(1)).default([])}),service:u,method:"steer",arguments:e=>[e.runId,e.prompt,e.attachmentIds],resultKey:"run",annotations:ae}),rm({name:"answer_run_question",title:"Answer run question",description:"Answer a pending agent question batch.",inputSchema:e6.object({batchId:e6.string().min(1),answers:e6.unknown()}),service:u,method:"answerQuestion",arguments:({batchId:e,answers:t})=>[e,t],resultKey:"run",annotations:ae}),rm({name:"revise_run_answer",title:"Revise run answer",description:"Revise an answer and optionally stash or roll back worktree changes.",inputSchema:e6.object({batchId:e6.string().min(1),answers:e6.unknown(),stash:e6.boolean().default(!1),rollback:e6.boolean().default(!0)}),service:u,method:"reviseAnswer",arguments:e=>[e.batchId,e.answers,e.stash,e.rollback],resultKey:"run",annotations:ae}),rm({name:"pause_agent_run",title:"Pause agent run",description:"Pause an active agent run.",inputSchema:ix,service:u,method:"lifecycle",arguments:({runId:e})=>[e,"PAUSE"],resultKey:"run",annotations:ae}),rm({name:"continue_agent_run",title:"Continue agent run",description:"Continue a paused agent run.",inputSchema:ix,service:u,method:"lifecycle",arguments:({runId:e})=>[e,"CONTINUE"],resultKey:"run",annotations:ae}),rm({name:"cancel_agent_run",title:"Cancel agent run",description:"Cancel an active agent run.",inputSchema:ix,service:u,method:"lifecycle",arguments:({runId:e})=>[e,"CANCEL"],resultKey:"run",annotations:ae}),rm({name:"archive_agent_runs",title:"Archive agent runs",description:"Archive or restore agent runs.",inputSchema:e6.object({ids:e6.array(e6.string().min(1)).min(1),archived:e6.boolean().default(!0)}),service:u,method:"archive",arguments:({ids:e,archived:t})=>[e,t],resultKey:"count",annotations:ae}),rm({name:"delete_agent_runs",title:"Delete agent runs",description:"Permanently delete agent runs and their stored normalized history.",inputSchema:e6.object({ids:e6.array(e6.string().min(1)).min(1)}),service:u,method:"deleteRuns",arguments:({ids:e})=>[e],resultKey:"count",annotations:at})]})),e.commands&&j.push((d=e.commands,{id:"builtin:commands",name:"Commands",children:[],tools:[rm({name:"get_commands",title:"Get commands",description:"List saved command definitions.",inputSchema:e6.object({includeArchived:e6.boolean().default(!1)}),service:d,method:"listDefinitions",arguments:({includeArchived:e})=>[e],resultKey:"commands"}),rm({name:"get_command",title:"Get command",description:"Get one command definition.",inputSchema:e6.object({id:e6.string().min(1)}),service:d,method:"getDefinition",arguments:({id:e})=>[e],resultKey:"command"}),an({name:"get_eligible_commands",title:"Get eligible commands",description:"List commands eligible for an agent or worktree target.",inputSchema:e6.discriminatedUnion("targetType",[e6.object({targetType:e6.literal("AGENT"),agentId:e6.string().min(1)}),e6.object({targetType:e6.literal("WORKTREE"),worktreeId:e6.string().min(1)})]),outputSchema:e6.object({commands:e6.unknown()}),handler:async e=>({commands:rh(await rd(d,"AGENT"===e.targetType?"eligibleForAgent":"eligibleForWorktree",["AGENT"===e.targetType?e.agentId:e.worktreeId]))})}),rm({name:"get_command_runs",title:"Get command runs",description:"List command runs with target, archive, search, and cursor filters.",inputSchema:e6.object({includeArchived:e6.boolean().default(!1),search:e6.string().nullable().optional(),agentId:e6.string().nullable().optional(),worktreeId:e6.string().nullable().optional(),first:e6.number().int().min(1).max(200).default(50),after:e6.string().nullable().optional()}),service:d,method:"listRuns",resultKey:"page"}),rm({name:"get_command_run",title:"Get command run",description:"Get one command run and its attempts.",inputSchema:e6.object({id:e6.string().min(1)}),service:d,method:"getRun",arguments:({id:e})=>[e],resultKey:"run"}),rm({name:"get_command_run_output",title:"Get command run output",description:"Read paginated terminal output chunks for a command run.",inputSchema:e6.object({runId:e6.string().min(1),afterAttempt:e6.number().int().min(0).default(0),afterSequence:e6.number().int().default(-1),first:e6.number().int().min(1).max(5e3).default(1e3)}),service:d,method:"listOutput",arguments:e=>[e.runId,e.afterAttempt,e.afterSequence,e.first],resultKey:"chunks"}),rm({name:"start_command",title:"Start command",description:"Start a saved command on an eligible agent or worktree.",inputSchema:e6.object({commandId:e6.string().min(1),agentId:e6.string().nullable().optional(),worktreeId:e6.string().nullable().optional(),origin:e6.string().default("MANUAL"),idempotencyKey:e6.string().nullable().optional()}),service:d,method:"startRun",resultKey:"run",annotations:ae}),rm({name:"start_custom_command",title:"Start custom command",description:"Start an ad hoc shell command on an agent or worktree.",inputSchema:e6.object({script:e6.string().min(1),agentId:e6.string().nullable().optional(),worktreeId:e6.string().nullable().optional(),origin:e6.string().default("MANUAL"),idempotencyKey:e6.string().nullable().optional()}),service:d,method:"startCustomRun",resultKey:"run",annotations:ae}),rm({name:"terminate_command_run",title:"Terminate command run",description:"Request termination of an active command run.",inputSchema:e6.object({id:e6.string().min(1)}),service:d,method:"terminateRun",arguments:({id:e})=>[e],resultKey:"run",annotations:ae}),rm({name:"rerun_command",title:"Rerun command",description:"Create a new run from a previous command snapshot.",inputSchema:e6.object({id:e6.string().min(1)}),service:d,method:"rerun",arguments:({id:e})=>[e],resultKey:"run",annotations:{...ae,idempotentHint:!1}}),rm({name:"create_command",title:"Create command",description:"Create a saved command definition.",inputSchema:iy,service:d,method:"createDefinition",resultKey:"command",annotations:{...ae,idempotentHint:!1}}),rm({name:"update_command",title:"Update command",description:"Replace a saved command definition.",inputSchema:e6.object({id:e6.string().min(1),input:iy}),service:d,method:"updateDefinition",arguments:({id:e,input:t})=>[e,t],resultKey:"command",annotations:ae}),rm({name:"archive_command",title:"Archive command",description:"Archive or restore a command definition.",inputSchema:e6.object({id:e6.string().min(1),archived:e6.boolean().default(!0)}),service:d,method:"archiveDefinition",arguments:({id:e,archived:t})=>[e,t],resultKey:"command",annotations:ae}),rm({name:"archive_command_runs",title:"Archive command runs",description:"Archive or restore command runs.",inputSchema:e6.object({ids:e6.array(e6.string().min(1)).min(1),archived:e6.boolean().default(!0)}),service:d,method:"archiveRuns",arguments:({ids:e,archived:t})=>[e,t],resultKey:"updated",annotations:ae}),rm({name:"delete_command_runs",title:"Delete command runs",description:"Permanently delete command runs and stored output.",inputSchema:e6.object({ids:e6.array(e6.string().min(1)).min(1)}),service:d,method:"deleteRuns",arguments:({ids:e})=>[e],resultKey:"count",annotations:at})]})),e.jira&&e.jiraWebhooks&&j.push((p=e.jira,{id:"builtin:jira",name:"Jira",children:[(h=e.jiraWebhooks,{id:"builtin:jira:administration",name:"Jira Administration",children:[],tools:[rm({name:"get_jira_webhook_settings",title:"Get Jira webhook settings",description:"Get the Jira webhook configuration and the outcome of the most recent delivery.",inputSchema:e6.object({}),service:h,method:"getWebhookSettings",arguments:()=>[],resultKey:"settings",annotations:i7}),rm({name:"get_jira_webhook_deliveries",title:"Get Jira webhook deliveries",description:"List Jira webhook deliveries with their event, issue, and outcome.",inputSchema:e6.object({limit:e6.number().int().min(1).max(100).default(50),offset:e6.number().int().min(0).default(0)}),service:h,method:"deliveries",arguments:({limit:e,offset:t})=>[e,t],resultKey:"page",annotations:i7}),rm({name:"clear_jira_webhook_deliveries",title:"Clear Jira webhook deliveries",description:"Delete the Jira webhook delivery history.",inputSchema:e6.object({}),service:h,method:"clearDeliveries",arguments:()=>[],resultKey:"cleared",annotations:at}),an({name:"rotate_jira_webhook_secret",title:"Rotate Jira webhook secret",description:"Replace the Jira webhook signing secret and return it once. For a manually configured webhook, paste the returned secret into Jira before expecting deliveries to succeed.",inputSchema:e6.object({}),outputSchema:e6.object({rotated:e6.boolean(),secret:e6.string().min(1)}),annotations:{...ae,idempotentHint:!1},handler:async()=>({rotated:!0,secret:(await h.rotateSecret()).secret})}),rm({name:"disable_jira_webhook",title:"Disable Jira webhook",description:"Delete the Jira webhook signing secret and stop accepting deliveries.",inputSchema:e6.object({}),service:h,method:"disableWebhook",arguments:()=>[],resultKey:"settings",annotations:at}),rm({name:"get_jira_available_projects",title:"Get Jira available projects",description:"List Jira projects that can be added, including ones not configured yet.",inputSchema:e6.object({}),service:p,method:"availableProjects",arguments:()=>[],resultKey:"projects",annotations:ar}),rm({name:"get_jira_project_statuses",title:"Get Jira project statuses",description:"List the statuses available in a configured Jira project.",inputSchema:e6.object({projectId:e6.string().min(1)}),service:p,method:"projectStatuses",arguments:({projectId:e})=>[e],resultKey:"statuses",annotations:ar}),rm({name:"add_jira_project",title:"Add Jira project",description:"Add a Jira project by its Jira ID.",inputSchema:e6.object({jiraId:e6.string().min(1)}),service:p,method:"addProject",arguments:({jiraId:e})=>[e],resultKey:"projects",annotations:ai}),rm({name:"remove_jira_project",title:"Remove Jira project",description:"Remove a configured Jira project along with its sources and cached tickets.",inputSchema:e6.object({projectId:e6.string().min(1)}),service:p,method:"removeProject",arguments:({projectId:e})=>[e],resultKey:"projects",annotations:at}),rm({name:"update_jira_project_display_settings",title:"Update Jira project display settings",description:"Set the assignment filter, completed statuses, and done status for a Jira project.",inputSchema:e6.object({projectId:e6.string().min(1),ticketAssignmentFilter:e6.enum(["ALL","UNASSIGNED_OR_SELF","SELF_IN_PROGRESS"]),hideCompletedTickets:e6.boolean(),completedStatusIds:e6.array(e6.string()),doneStatusId:e6.string().nullable().optional()}),service:p,method:"updateProjectDisplaySettings",resultKey:"projects",annotations:ae}),rm({name:"update_jira_project_branch_naming",title:"Update Jira project branch naming",description:"Set the branch-naming script used to derive branch names for a Jira project.",inputSchema:e6.object({projectId:e6.string().min(1),branchNamingScript:e6.string()}),service:p,method:"updateProjectBranchNaming",arguments:({projectId:e,branchNamingScript:t})=>[e,t],resultKey:"projects",annotations:ae}),rm({name:"create_jira_source",title:"Create Jira source",description:"Create a ticket-board source for a Jira project from a JQL query or a board URL.",inputSchema:e6.object({projectId:e6.string().min(1),name:e6.string().min(1),kind:iI,value:e6.string().min(1)}),service:p,method:"createSource",resultKey:"projects",annotations:ai}),rm({name:"update_jira_source",title:"Update Jira source",description:"Update a Jira ticket-board source and clear its cache.",inputSchema:e6.object({id:e6.string().min(1),name:e6.string().min(1),kind:iI,value:e6.string().min(1)}),service:p,method:"updateSource",resultKey:"projects",annotations:ai}),rm({name:"delete_jira_source",title:"Delete Jira source",description:"Delete a Jira ticket-board source and the cached tickets only it referenced.",inputSchema:e6.object({id:e6.string().min(1)}),service:p,method:"deleteSource",arguments:({id:e})=>[e],resultKey:"projects",annotations:at}),rm({name:"update_jira_cache_ttl",title:"Update Jira cache TTL",description:"Set how long Jira API responses stay cached, in minutes (1 to 1440).",inputSchema:e6.object({ttlMinutes:e6.number().int().min(1).max(1440)}),service:p,method:"updateCacheTtl",arguments:({ttlMinutes:e})=>[e],resultKey:"settings",annotations:ae}),rm({name:"refresh_jira_cached_ticket",title:"Refresh Jira cached ticket",description:"Discard the cached copy of a Jira ticket and fetch it again from Jira.",inputSchema:iE,service:p,method:"refreshCachedTicket",arguments:({issueKey:e})=>[e],resultKey:"ticket",annotations:ai}),rm({name:"delete_jira_cached_ticket",title:"Delete Jira cached ticket",description:"Remove a Jira ticket from the local cache without touching Jira.",inputSchema:iE,service:p,method:"deleteCachedTicket",arguments:({issueKey:e})=>[e],resultKey:"deleted",annotations:at})]})],tools:[rm({name:"get_jira_status",title:"Get Jira status",description:"Test the configured Jira connection without exposing credentials.",inputSchema:e6.object({}),service:p,method:"testConnection",arguments:()=>[],resultKey:"status",annotations:ar}),rm({name:"get_jira_projects",title:"Get Jira projects",description:"List configured Jira projects and display settings.",inputSchema:e6.object({}),service:p,method:"listProjects",arguments:()=>[],resultKey:"projects",annotations:ar}),an({name:"get_jira_sources",title:"Get Jira sources",description:"List ticket-board sources configured across Jira projects.",inputSchema:e6.object({}),outputSchema:e6.object({sources:e6.unknown()}),annotations:ar,handler:async()=>({sources:rh((await p.listProjects()).flatMap(e=>e.sources))})}),rm({name:"get_jira_board",title:"Get Jira board",description:"Get tickets for a configured Jira source.",inputSchema:e6.object({sourceId:e6.string().min(1),refresh:e6.boolean().default(!1)}),service:p,method:"ticketBoard",arguments:({sourceId:e,refresh:t})=>[e,t],resultKey:"board",annotations:ar}),rm({name:"get_jira_ticket",title:"Get Jira ticket",description:"Get a Jira ticket and its normalized editable metadata.",inputSchema:iE.extend({refresh:e6.boolean().default(!1)}),service:p,method:"ticket",arguments:({issueKey:e,refresh:t})=>[e,t],resultKey:"ticket",annotations:ar}),rm({name:"get_jira_assignable_users",title:"Get Jira assignable users",description:"Search users who can be assigned to a Jira ticket.",inputSchema:iE.extend({query:e6.string().default("")}),service:p,method:"assignableUsers",arguments:({issueKey:e,query:t})=>[e,t],resultKey:"users",annotations:ar}),rm({name:"get_jira_transitions",title:"Get Jira transitions",description:"Get available transitions for a Jira ticket.",inputSchema:iE,service:p,method:"ticketTransitions",arguments:({issueKey:e})=>[e],resultKey:"transitions",annotations:ar}),rm({name:"get_jira_edit_fields",title:"Get Jira edit fields",description:"Get editable fields and allowed values for a Jira ticket.",inputSchema:iE,service:p,method:"ticketEditFields",arguments:({issueKey:e})=>[e],resultKey:"fields",annotations:ar}),rm({name:"get_jira_ticket_changes",title:"Get Jira ticket changes",description:"Get paginated Jira ticket changelog entries.",inputSchema:iE.extend({limit:e6.number().int().min(1).max(200).default(50),offset:e6.number().int().min(0).default(0)}),service:p,method:"ticketChanges",arguments:e=>[e.issueKey,e.limit,e.offset],resultKey:"page",annotations:ar}),rm({name:"get_jira_worklogs",title:"Get Jira worklogs",description:"Get paginated worklogs for a Jira ticket.",inputSchema:iE.extend({limit:e6.number().int().min(1).max(200).default(50),offset:e6.number().int().min(0).default(0)}),service:p,method:"ticketWorklogs",arguments:e=>[e.issueKey,e.limit,e.offset],resultKey:"page",annotations:ar}),rm({name:"add_jira_comment",title:"Add Jira comment",description:"Add a plain-text or Markdown comment to a Jira ticket.",inputSchema:iE.extend({content:iS}),service:p,method:"addComment",arguments:({issueKey:e,content:t})=>[e,t],resultKey:"ticket",annotations:{...ai,idempotentHint:!1}}),rm({name:"assign_jira_ticket",title:"Assign Jira ticket",description:"Assign or unassign a Jira ticket.",inputSchema:iE.extend({accountId:e6.string().nullable().optional()}),service:p,method:"assignTicket",arguments:({issueKey:e,accountId:t})=>[e,t??null],resultKey:"ticket",annotations:ai}),rm({name:"transition_jira_ticket",title:"Transition Jira ticket",description:"Apply an available status transition to a Jira ticket.",inputSchema:iE.extend({transitionId:e6.string().min(1)}),service:p,method:"transitionTicket",arguments:({issueKey:e,transitionId:t})=>[e,t],resultKey:"ticket",annotations:ai}),rm({name:"update_jira_ticket",title:"Update Jira ticket",description:"Update supported editable fields on a Jira ticket.",inputSchema:iE.extend({summary:e6.string().nullable().optional(),description:iS.nullable().optional(),priorityId:e6.string().nullable().optional(),labels:e6.array(e6.string()).nullable().optional(),componentIds:e6.array(e6.string()).nullable().optional(),fixVersionIds:e6.array(e6.string()).nullable().optional(),affectedVersionIds:e6.array(e6.string()).nullable().optional(),dueDate:e6.string().nullable().optional()}),service:p,method:"updateTicket",resultKey:"ticket",annotations:ai}),rm({name:"transition_jira_ticket_to_done",title:"Transition Jira ticket to done",description:"Move a Jira ticket to the done status configured for its project.",inputSchema:iE,service:p,method:"transitionTicketToConfiguredDone",arguments:({issueKey:e})=>[e],resultKey:"ticket",annotations:ai}),rm({name:"resolve_jira_branch",title:"Resolve Jira branch",description:"Resolve the configured branch name for a Jira ticket.",inputSchema:iE,service:p,method:"branchTicket",arguments:({issueKey:e})=>[e],resultKey:"branch",annotations:ar}),rm({name:"create_jira_ticket",title:"Create Jira ticket",description:"Create a Jira ticket with typed core fields and optional additional fields.",inputSchema:e6.object({projectKey:e6.string().min(1),issueTypeId:e6.string().min(1),summary:e6.string().min(1),description:iS.nullable().optional(),fields:e6.record(e6.string(),e6.unknown()).nullable().optional()}),service:p,method:"createTicket",resultKey:"ticket",annotations:{...ai,idempotentHint:!1}}),rm({name:"add_jira_worklog",title:"Add Jira worklog",description:"Add a time-spent worklog to a Jira ticket.",inputSchema:iE.extend({timeSpentSeconds:e6.number().int().positive(),startedAt:e6.string().nullable().optional(),comment:iS.nullable().optional()}),service:p,method:"addWorklog",resultKey:"ticket",annotations:{...ai,idempotentHint:!1}}),rm({name:"link_jira_tickets",title:"Link Jira tickets",description:"Create a typed relationship between two Jira tickets.",inputSchema:e6.object({inwardIssueKey:e6.string().min(1),outwardIssueKey:e6.string().min(1),linkType:e6.string().min(1)}),service:p,method:"linkTickets",resultKey:"ticket",annotations:{...ai,idempotentHint:!1}})]})),e.github&&j.push((m=e.github,{id:"builtin:github",name:"GitHub",children:[],tools:[rm({name:"get_github_status",title:"Get GitHub status",description:"Test the configured GitHub connection without exposing credentials.",inputSchema:e6.object({}),service:m,method:"testConnection",arguments:()=>[],resultKey:"status",annotations:ar}),rm({name:"get_github_repositories",title:"Get GitHub repositories",description:"List configured GitHub repositories.",inputSchema:e6.object({}),service:m,method:"listRepositories",arguments:()=>[],resultKey:"repositories",annotations:ar}),rm({name:"get_pull_requests",title:"Get pull requests",description:"List GitHub pull requests by scope, repository, and state.",inputSchema:e6.object({scope:e6.enum(["MINE","REVIEW_REQUESTED","REPOSITORY"]),repositoryId:e6.string().nullable().optional(),state:e6.enum(["ALL","OPEN","CLOSED","MERGED"]).default("OPEN"),first:e6.number().int().min(1).max(100).default(25),after:e6.string().nullable().optional(),includePipelineJobs:e6.boolean().default(!1)}),service:m,method:"pullRequests",arguments:e=>[e.scope,e.repositoryId,{includePipelineJobs:e.includePipelineJobs,state:e.state,first:e.first,after:e.after,requestSource:iw}],resultKey:"page",annotations:ar}),rm({name:"get_pull_request",title:"Get pull request",description:"Get a GitHub pull request by repository and number.",inputSchema:iv,service:m,method:"pullRequest",arguments:e=>[e.owner,e.name,e.number,iw],resultKey:"pullRequest",annotations:ar}),rm({name:"get_pull_request_merge_options",title:"Get pull request merge options",description:"Get merge eligibility, methods, and commit-email choices for a pull request.",inputSchema:iv,service:m,method:"pullRequestMergeOptions",arguments:e=>[e.owner,e.name,e.number,iw],resultKey:"options",annotations:ar}),rm({name:"get_review_threads",title:"Get review threads",description:"List tracked GitHub review threads.",inputSchema:e6.object({}),service:m,method:"reviewThreads",arguments:()=>[],resultKey:"threads",annotations:ar}),rm({name:"get_actions_runs",title:"Get Actions runs",description:"List GitHub Actions workflow runs with repository and branch filters.",inputSchema:e6.object({codebaseRepositoryId:e6.string().nullable().optional(),branch:e6.string().nullable().optional(),workflowId:e6.string().nullable().optional(),first:e6.number().int().min(1).max(100).default(25),after:e6.string().nullable().optional()}),service:m,method:"actionsWorkflowRuns",arguments:e=>[e.codebaseRepositoryId,e.first,e.after,e.branch,e.workflowId,iw],resultKey:"page",annotations:ar}),rm({name:"get_actions_jobs",title:"Get Actions jobs",description:"Get jobs for a GitHub Actions workflow run.",inputSchema:e6.object({codebaseRepositoryId:e6.string().min(1),workflowRunId:e6.string().min(1)}),service:m,method:"actionsWorkflowJobs",arguments:e=>[e.codebaseRepositoryId,e.workflowRunId,iw],resultKey:"jobs",annotations:ar}),rm({name:"get_actions_run_attempt",title:"Get Actions run attempt",description:"Get one attempt of a GitHub Actions workflow run.",inputSchema:e6.object({repositoryId:e6.string().min(1),workflowRunId:e6.string().min(1),attempt:e6.number().int().positive(),includeJobs:e6.boolean().default(!0)}),service:m,method:"actionsWorkflowRunAttempt",arguments:e=>[e.repositoryId,e.workflowRunId,e.attempt,e.includeJobs,iw],resultKey:"attempt",annotations:ar}),rm({name:"get_repository_workflows",title:"Get repository workflows",description:"List GitHub Actions workflows for a configured repository.",inputSchema:e6.object({codebaseRepositoryId:e6.string().min(1)}),service:m,method:"repositoryWorkflows",arguments:({codebaseRepositoryId:e})=>[e,iw],resultKey:"workflows",annotations:ar}),rm({name:"get_auto_retry_rules",title:"Get auto-retry rules",description:"List GitHub pipeline auto-retry rules.",inputSchema:e6.object({codebaseRepositoryId:e6.string().nullable().optional(),workflowRunId:e6.string().nullable().optional()}),service:m,method:"autoRetryRules",resultKey:"rules",annotations:ar}),rm({name:"get_github_rate_limits",title:"Get GitHub rate limits",description:"Get recently observed GitHub API rate-limit snapshots.",inputSchema:e6.object({}),service:m,method:"rateLimitSnapshots",arguments:()=>[],resultKey:"snapshots",annotations:ar}),rm({name:"create_pull_request",title:"Create pull request",description:"Create a GitHub pull request using configured GitHub App credentials.",inputSchema:e6.object({owner:e6.string().min(1),name:e6.string().min(1),baseRefName:e6.string().min(1),headRefName:e6.string().min(1),title:e6.string().min(1),body:e6.string().nullable().optional(),draft:e6.boolean().nullable().optional()}),service:m,method:"createPullRequest",resultKey:"pullRequest",annotations:{...ai,idempotentHint:!1}}),rm({name:"update_pull_request",title:"Update pull request",description:"Update a pull request title, body, or draft state on GitHub.",inputSchema:iv.extend({title:e6.string().nullable().optional(),body:e6.string().nullable().optional(),draft:e6.boolean().nullable().optional()}),service:m,method:"updatePullRequest",resultKey:"pullRequest",annotations:ai}),rm({name:"submit_pull_request_review",title:"Submit pull request review",description:"Approve, comment on, or request changes to a pull request.",inputSchema:iv.extend({event:e6.enum(["APPROVE","REQUEST_CHANGES","COMMENT"]),body:e6.string().nullable().optional()}),service:m,method:"submitPullRequestReview",resultKey:"pullRequest",annotations:{...ai,idempotentHint:!1}}),rm({name:"request_pull_request_reviewers",title:"Request pull request reviewers",description:"Request GitHub users or organization teams to review a pull request.",inputSchema:iv.extend({reviewers:e6.array(e6.string()).default([]),teamReviewers:e6.array(e6.string()).default([])}),service:m,method:"requestPullRequestReviewers",resultKey:"pullRequest",annotations:ai}),rm({name:"dispatch_github_workflow",title:"Dispatch GitHub workflow",description:"Dispatch a workflow_dispatch-enabled GitHub Actions workflow.",inputSchema:e6.object({repositoryId:e6.string().min(1),workflowId:e6.string().min(1),ref:e6.string().min(1),inputs:e6.record(e6.string(),e6.string()).nullable().optional()}),service:m,method:"dispatchWorkflow",resultKey:"dispatched",annotations:{...ai,idempotentHint:!1}}),rm({name:"merge_pull_request",title:"Merge pull request",description:"Merge a GitHub pull request with an enabled merge method.",inputSchema:iv.extend({method:e6.enum(["MERGE","SQUASH","REBASE"]),commitHeadline:e6.string().min(1),commitBody:e6.string().default(""),authorEmail:e6.string().nullable().optional()}),service:m,method:"mergePullRequest",arguments:e=>[e,iw],resultKey:"pullRequest",annotations:ai}),rm({name:"set_pull_request_labels",title:"Set pull request labels",description:"Replace labels on a GitHub pull request.",inputSchema:iv.extend({labels:e6.array(e6.string())}),service:m,method:"setPullRequestLabels",resultKey:"pullRequest",annotations:ai}),rm({name:"reply_review_thread",title:"Reply to review thread",description:"Post a reply to a GitHub pull-request review thread.",inputSchema:e6.object({threadId:e6.string().min(1),body:e6.string().min(1)}),service:m,method:"replyToReviewThread",arguments:({threadId:e,body:t})=>[e,t],resultKey:"thread",annotations:{...ai,idempotentHint:!1}}),rm({name:"set_review_thread_resolved",title:"Set review thread resolved",description:"Resolve or unresolve a GitHub review thread.",inputSchema:e6.object({threadId:e6.string().min(1),resolved:e6.boolean()}),service:m,method:"setReviewThreadResolved",arguments:({threadId:e,resolved:t})=>[e,t],resultKey:"thread",annotations:ai}),rm({name:"retry_pipeline",title:"Retry pipeline",description:"Retry a failed GitHub check suite.",inputSchema:e6.object({repositoryId:e6.string().min(1),checkSuiteId:e6.string().min(1)}),service:m,method:"retryPipeline",arguments:e=>[e.repositoryId,e.checkSuiteId,iw,ib],resultKey:"pipeline",annotations:ai}),rm({name:"retry_workflow_job",title:"Retry workflow job",description:"Retry one failed job in a GitHub Actions workflow run.",inputSchema:e6.object({repositoryId:e6.string().min(1),checkSuiteId:e6.string().min(1),jobId:e6.string().min(1)}),service:m,method:"retryWorkflowJob",arguments:e=>[e.repositoryId,e.checkSuiteId,e.jobId,iw,ib],resultKey:"job",annotations:ai}),rm({name:"cancel_actions_run",title:"Cancel Actions run",description:"Cancel a GitHub Actions workflow run.",inputSchema:e6.object({codebaseRepositoryId:e6.string().min(1),workflowRunId:e6.string().min(1),force:e6.boolean().default(!1)}),service:m,method:"cancelActionsWorkflowRun",arguments:e=>[e.codebaseRepositoryId,e.workflowRunId,e.force,iw,ib],resultKey:"run",annotations:ai}),rm({name:"save_auto_retry_rule",title:"Save auto-retry rule",description:"Create or update a GitHub pipeline auto-retry rule.",inputSchema:e6.object({id:e6.string().nullable().optional(),scope:e6.string().min(1),codebaseRepositoryId:e6.string().min(1),repositoryGithubId:e6.string().nullable().optional(),worktreeId:e6.string().nullable().optional(),branch:e6.string().nullable().optional(),pullRequestNumber:e6.number().int().positive().nullable().optional(),allWorkflows:e6.boolean(),mode:e6.string().min(1),retryLimit:e6.number().int().min(0).nullable().optional(),failureStrategy:e6.string().min(1),targets:e6.array(e6.object({workflowId:e6.string().nullable().optional(),workflowRunId:e6.string().nullable().optional(),jobName:e6.string().nullable().optional()}))}),service:m,method:"saveAutoRetryRule",resultKey:"rule",annotations:ai})]})),e.gitlab&&j.push((f=e.gitlab,{id:"builtin:gitlab",name:"GitLab",children:[],tools:[rm({name:"gitlab_get_status",title:"Get GitLab status",description:"Test the configured GitLab connection.",inputSchema:e6.object({}),service:f,method:"testConnection",arguments:()=>[],resultKey:"status",annotations:ar}),rm({name:"gitlab_get_projects",title:"Get GitLab projects",description:"List the GitLab projects managed by AIDE.",inputSchema:e6.object({}),service:f,method:"projects",arguments:()=>[],resultKey:"projects",annotations:ar}),rm({name:"gitlab_get_merge_requests",title:"Get GitLab merge requests",description:"List accessible GitLab merge requests.",inputSchema:e6.object({scope:e6.enum(["MINE","REVIEW_REQUESTED","PROJECT","ALL"]),projectId:e6.string().nullable().optional(),state:e6.enum(["OPENED","CLOSED","MERGED","ALL"]).default("OPENED"),page:e6.number().int().positive().default(1),perPage:e6.number().int().min(1).max(100).default(25)}),service:f,method:"mergeRequests",resultKey:"page",annotations:ar}),rm({name:"gitlab_get_merge_request",title:"Get GitLab merge request",description:"Get a merge request with discussions and pipelines.",inputSchema:ik,service:f,method:"mergeRequest",arguments:({projectId:e,iid:t})=>[e,t],resultKey:"mergeRequest",annotations:ar}),rm({name:"gitlab_create_merge_request",title:"Create GitLab merge request",description:"Create a GitLab merge request.",inputSchema:e6.object({projectId:e6.string().min(1),sourceBranch:e6.string().min(1),targetBranch:e6.string().min(1),title:e6.string().min(1),description:e6.string().nullable().optional(),removeSourceBranch:e6.boolean().nullable().optional(),squash:e6.boolean().nullable().optional(),reviewerIds:e6.array(e6.string()).nullable().optional(),labels:e6.array(e6.string()).nullable().optional()}),service:f,method:"createMergeRequest",resultKey:"mergeRequest",annotations:{...ai,idempotentHint:!1}}),rm({name:"gitlab_update_merge_request",title:"Update GitLab merge request",description:"Update title, description, state, labels, or reviewers.",inputSchema:ik.extend({title:e6.string().nullable().optional(),description:e6.string().nullable().optional(),stateEvent:e6.enum(["CLOSE","REOPEN"]).nullable().optional(),reviewerIds:e6.array(e6.string()).nullable().optional(),labels:e6.array(e6.string()).nullable().optional()}),service:f,method:"updateMergeRequest",resultKey:"mergeRequest",annotations:ai}),rm({name:"gitlab_set_merge_request_labels",title:"Set GitLab merge request labels",description:"Replace the labels on a GitLab merge request.",inputSchema:ik.extend({labels:e6.array(e6.string())}),service:f,method:"updateMergeRequest",resultKey:"mergeRequest",annotations:ai}),rm({name:"gitlab_request_merge_request_reviewers",title:"Request GitLab merge request reviewers",description:"Replace the reviewers on a GitLab merge request.",inputSchema:ik.extend({reviewerIds:e6.array(e6.string())}),service:f,method:"updateMergeRequest",resultKey:"mergeRequest",annotations:ai}),rm({name:"gitlab_submit_review",title:"Submit GitLab review",description:"Approve, comment on, or request changes on a merge request.",inputSchema:ik.extend({outcome:e6.enum(["APPROVE","COMMENT","REQUEST_CHANGES"]),body:e6.string().nullable().optional()}),service:f,method:"submitReview",resultKey:"submitted",annotations:{...ai,idempotentHint:!1}}),rm({name:"gitlab_reply_discussion",title:"Reply to GitLab discussion",description:"Reply to a merge-request discussion.",inputSchema:ik.extend({discussionId:e6.string().min(1),body:e6.string().min(1)}),service:f,method:"replyToDiscussion",resultKey:"discussion",annotations:{...ai,idempotentHint:!1}}),rm({name:"gitlab_set_discussion_resolved",title:"Resolve GitLab discussion",description:"Resolve or reopen a merge-request discussion.",inputSchema:ik.extend({discussionId:e6.string().min(1),resolved:e6.boolean()}),service:f,method:"setDiscussionResolved",resultKey:"discussion",annotations:ai}),rm({name:"gitlab_merge_merge_request",title:"Merge GitLab merge request",description:"Merge now or enable auto-merge for a GitLab merge request.",inputSchema:ik.extend({squash:e6.boolean().nullable().optional(),removeSourceBranch:e6.boolean().nullable().optional(),autoMerge:e6.boolean().nullable().optional(),sha:e6.string().nullable().optional()}),service:f,method:"mergeMergeRequest",resultKey:"mergeRequest",annotations:ai}),rm({name:"gitlab_get_pipelines",title:"Get GitLab pipelines",description:"List pipelines for a GitLab project.",inputSchema:e6.object({projectId:e6.string().min(1),page:e6.number().int().positive().default(1),perPage:e6.number().int().min(1).max(100).default(25)}),service:f,method:"pipelines",arguments:({projectId:e,page:t,perPage:r})=>[e,t,r],resultKey:"page",annotations:ar}),rm({name:"gitlab_get_pipeline",title:"Get GitLab pipeline",description:"Get a GitLab pipeline by project and pipeline ID.",inputSchema:e6.object({projectId:e6.string().min(1),pipelineId:e6.string().min(1)}),service:f,method:"pipeline",arguments:({projectId:e,pipelineId:t})=>[e,t],resultKey:"pipeline",annotations:ar}),rm({name:"gitlab_get_pipeline_jobs",title:"Get GitLab pipeline jobs",description:"List jobs for a GitLab pipeline.",inputSchema:e6.object({projectId:e6.string().min(1),pipelineId:e6.string().min(1)}),service:f,method:"pipelineJobs",arguments:({projectId:e,pipelineId:t})=>[e,t],resultKey:"jobs",annotations:ar}),rm({name:"gitlab_create_pipeline",title:"Create GitLab pipeline",description:"Create a pipeline for a ref and optional variables.",inputSchema:e6.object({projectId:e6.string().min(1),ref:e6.string().min(1),variables:e6.array(e6.object({key:e6.string().min(1),value:e6.string()})).default([])}),service:f,method:"createPipeline",arguments:({projectId:e,ref:t,variables:r})=>[e,t,r],resultKey:"pipeline",annotations:{...ai,idempotentHint:!1}}),rm({name:"gitlab_retry_pipeline",title:"Retry GitLab pipeline",description:"Retry failed or canceled jobs in a GitLab pipeline.",inputSchema:e6.object({projectId:e6.string().min(1),pipelineId:e6.string().min(1)}),service:f,method:"retryPipeline",arguments:({projectId:e,pipelineId:t})=>[e,t],resultKey:"pipeline",annotations:ai}),rm({name:"gitlab_cancel_pipeline",title:"Cancel GitLab pipeline",description:"Cancel a running GitLab pipeline.",inputSchema:e6.object({projectId:e6.string().min(1),pipelineId:e6.string().min(1)}),service:f,method:"cancelPipeline",arguments:({projectId:e,pipelineId:t})=>[e,t],resultKey:"pipeline",annotations:ai}),rm({name:"gitlab_retry_job",title:"Retry GitLab job",description:"Retry a failed or canceled GitLab job.",inputSchema:e6.object({projectId:e6.string().min(1),jobId:e6.string().min(1)}),service:f,method:"retryJob",arguments:({projectId:e,jobId:t})=>[e,t],resultKey:"job",annotations:ai}),rm({name:"gitlab_get_auto_retry_rules",title:"Get GitLab auto-retry rules",description:"List GitLab pipeline auto-retry rules.",inputSchema:e6.object({projectId:e6.string().nullable().optional()}),service:f,method:"autoRetryRules",arguments:({projectId:e})=>[e],resultKey:"rules",annotations:ar}),rm({name:"gitlab_save_auto_retry_rule",title:"Save GitLab auto-retry rule",description:"Create or update a GitLab pipeline auto-retry rule.",inputSchema:e6.object({id:e6.string().nullable().optional(),projectId:e6.string().min(1),pipelineId:e6.string().nullable().optional(),enabled:e6.boolean().nullable().optional(),maxAttempts:e6.number().int().min(1).max(100)}),service:f,method:"saveAutoRetryRule",resultKey:"rule",annotations:ai}),rm({name:"gitlab_delete_auto_retry_rule",title:"Delete GitLab auto-retry rule",description:"Permanently delete a GitLab pipeline auto-retry rule.",inputSchema:e6.object({id:e6.string().min(1)}),service:f,method:"deleteAutoRetryRule",arguments:({id:e})=>[e],resultKey:"deleted",annotations:ai}),rm({name:"gitlab_get_rate_limits",title:"Get GitLab rate limits",description:"Get recently observed GitLab API rate-limit snapshots.",inputSchema:e6.object({}),service:f,method:"rateLimitSnapshots",arguments:()=>[],resultKey:"snapshots",annotations:ar})]})),e.skills&&j.push((g=e.skills,{id:"builtin:skills",name:"Skills",children:[],tools:[rm({name:"get_skills_overview",title:"Get skills overview",description:"List skills, groups, installations, and sync status.",inputSchema:e6.object({search:e6.string().default("")}),service:g,method:"overview",arguments:({search:e})=>[e],resultKey:"overview"}),rm({name:"get_skill",title:"Get skill",description:"Get one skill and its deployments.",inputSchema:e6.object({id:e6.string().min(1)}),service:g,method:"getSkill",arguments:({id:e})=>[e],resultKey:"skill"}),an({name:"get_skill_groups",title:"Get skill groups",description:"Get skill groups, optionally for one repository.",inputSchema:e6.object({repositoryId:e6.string().nullable().optional()}),outputSchema:e6.object({groups:e6.unknown()}),handler:async({repositoryId:e})=>({groups:rh(e?await g.groupsForRepository(e):(await g.overview()).groups)})}),rm({name:"get_skill_sync_run",title:"Get skill sync run",description:"Inspect a skill synchronization run and its conflicts.",inputSchema:e6.object({id:e6.string().min(1)}),service:g,method:"getRun",arguments:({id:e})=>[e],resultKey:"run"}),rm({name:"save_skill",title:"Save skill",description:"Create or update a managed skill.",inputSchema:e6.object({input:e6.record(e6.string(),e6.unknown())}),service:g,method:"saveSkill",arguments:({input:e})=>[e],resultKey:"skill",annotations:ae}),rm({name:"delete_skill",title:"Delete skill",description:"Delete a managed skill and its associations.",inputSchema:e6.object({id:e6.string().min(1)}),service:g,method:"deleteSkill",arguments:({id:e})=>[e],resultKey:"deleted",annotations:at}),rm({name:"save_skill_group",title:"Save skill group",description:"Create or update a managed skill group.",inputSchema:e6.object({input:e6.record(e6.string(),e6.unknown())}),service:g,method:"saveGroup",arguments:({input:e})=>[e],resultKey:"group",annotations:ae}),rm({name:"delete_skill_group",title:"Delete skill group",description:"Delete a managed skill group.",inputSchema:e6.object({id:e6.string().min(1)}),service:g,method:"deleteGroup",arguments:({id:e})=>[e],resultKey:"deleted",annotations:at}),rm({name:"update_skill_settings",title:"Update skill settings",description:"Update managed skill locations and reconciliation settings.",inputSchema:e6.object({input:e6.record(e6.string(),e6.unknown())}),service:g,method:"saveSettings",arguments:({input:e})=>[e],resultKey:"settings",annotations:ae}),rm({name:"prepare_skill_sync",title:"Prepare skill sync",description:"Prepare a push or pull skill synchronization run.",inputSchema:e6.object({kind:e6.enum(["ALL","GROUP"]),groupId:e6.string().nullable().optional()}),service:g,method:"prepareSync",arguments:({kind:e,groupId:t})=>[e,t??null],resultKey:"run",annotations:ae}),rm({name:"resolve_skill_sync_conflict",title:"Resolve skill sync conflict",description:"Choose a resolution for one skill synchronization conflict.",inputSchema:e6.object({input:e6.record(e6.string(),e6.unknown())}),service:g,method:"resolveItem",arguments:({input:e})=>[e],resultKey:"run",annotations:ae}),rm({name:"skip_skill_sync",title:"Skip skill sync",description:"Skip remaining pending work in a skill synchronization run.",inputSchema:e6.object({runId:e6.string().min(1)}),service:g,method:"skipPending",arguments:({runId:e})=>[e],resultKey:"run",annotations:ae}),rm({name:"apply_skill_sync",title:"Apply skill sync",description:"Apply all resolved items in a prepared skill synchronization run.",inputSchema:e6.object({runId:e6.string().min(1)}),service:g,method:"applyRun",arguments:({runId:e})=>[e],resultKey:"run",annotations:ae})]})),e.buildData&&j.push((y=e.buildData,{id:"builtin:build-data",name:"Build Data",children:[],tools:[rm({name:"get_build_data_collection",title:"Get build data collection",description:"Get a derived-data collection and its entries.",inputSchema:e6.object({id:e6.string().min(1)}),service:y,method:"getCollection",arguments:({id:e})=>[e],resultKey:"collection"}),rm({name:"get_build_data_deletion_history",title:"Get build data deletion history",description:"Get paginated build-data cleanup history.",inputSchema:e6.object({first:e6.number().int().min(1).max(500).default(100),after:e6.string().nullable().optional()}),service:y,method:"history",arguments:({first:e,after:t})=>[e,t],resultKey:"page"}),rm({name:"refresh_build_data",title:"Refresh build data",description:"Collect current derived-data entries from enrolled agents.",inputSchema:e6.object({requestId:e6.string().nullable().optional()}),service:y,method:"refresh",arguments:({requestId:e})=>[e],resultKey:"collection",annotations:ae}),rm({name:"calculate_build_data_sizes",title:"Calculate build data sizes",description:"Calculate accurate sizes for selected build-data entries.",inputSchema:e6.object({collectionId:e6.string().min(1),entryIds:e6.array(e6.string().min(1)).min(1),requestId:e6.string().min(1)}),service:y,method:"calculateSizes",arguments:e=>[e.collectionId,e.entryIds,e.requestId],resultKey:"collection",annotations:ae}),rm({name:"delete_build_data_entries",title:"Delete build data entries",description:"Delete selected derived-data entries from their agents.",inputSchema:e6.object({collectionId:e6.string().min(1),entryIds:e6.array(e6.string().min(1)).min(1),requestId:e6.string().min(1),overrideProtection:e6.boolean().default(!1)}),service:y,method:"deleteEntries",arguments:e=>[e.collectionId,e.entryIds,e.requestId,e.overrideProtection],resultKey:"collection",annotations:at}),rm({name:"clear_build_data_history",title:"Clear build data history",description:"Permanently clear build-data deletion history.",inputSchema:e6.object({}),service:y,method:"clearHistory",arguments:()=>[],resultKey:"count",annotations:at}),rm({name:"set_build_data_lock",title:"Set build data lock",description:"Lock or unlock a build-data entry to control cleanup eligibility.",inputSchema:e6.object({collectionId:e6.string().min(1),entryId:e6.string().min(1),locked:e6.boolean()}),service:y,method:"setEntryLocked",arguments:e=>[e.collectionId,e.entryId,e.locked],resultKey:"entry",annotations:ae})]})),e.signingAssets&&j.push((w=e.signingAssets,{id:"builtin:signing-assets",name:"Signing Assets",children:[],tools:[rm({name:"get_signing_agents",title:"Get signing agents",description:"List agents and signing-asset availability.",inputSchema:e6.object({}),service:w,method:"agents",arguments:()=>[],resultKey:"agents"}),rm({name:"get_signing_profiles",title:"Get signing profiles",description:"List provisioning-profile metadata without profile contents.",inputSchema:e6.object({}),service:w,method:"profiles",arguments:()=>[],resultKey:"profiles"}),rm({name:"get_signing_profile",title:"Get signing profile",description:"Get one provisioning profile and matched devices.",inputSchema:e6.object({id:e6.string().min(1)}),service:w,method:"profile",arguments:({id:e})=>[e],resultKey:"profile"}),rm({name:"get_signing_certificates",title:"Get signing certificates",description:"List signing-certificate metadata without private keys or P12 files.",inputSchema:e6.object({}),service:w,method:"certificates",arguments:()=>[],resultKey:"certificates"}),rm({name:"get_signing_operations",title:"Get signing operations",description:"List recent signing-asset operation history.",inputSchema:e6.object({limit:e6.number().int().min(1).max(500).default(50)}),service:w,method:"operations",arguments:({limit:e})=>[e],resultKey:"operations"}),rm({name:"get_apple_portal_inventory",title:"Get Apple portal inventory",description:"Get provisioning profiles, certificates, devices, and identifiers visible in the Apple Developer portal.",inputSchema:e6.object({}),service:w,method:"portalInventory",arguments:()=>[],resultKey:"inventory",annotations:ar}),rm({name:"refresh_signing_assets",title:"Refresh signing assets",description:"Refresh signing-asset inventory from selected or all agents.",inputSchema:e6.object({agentIds:e6.array(e6.string().min(1)).optional()}),service:w,method:"refresh",arguments:({agentIds:e})=>[e],resultKey:"operation",annotations:ae}),rm({name:"download_signing_profile",title:"Download signing profile",description:"Download an Apple provisioning profile to an agent; profile contents are not returned.",inputSchema:e6.object({uuid:e6.string().min(1),agentId:e6.string().min(1)}),service:w,method:"downloadProfile",arguments:e=>[e.uuid,e.agentId],resultKey:"operation",mapResult:e=>({uuid:"string"==typeof e.uuid?e.uuid:null,filename:"string"==typeof e.filename?e.filename:null}),annotations:ae}),rm({name:"sync_signing_profile",title:"Sync signing profile",description:"Synchronize a provisioning profile between agents.",inputSchema:e6.object({uuid:e6.string().min(1),sourceAgentId:e6.string().min(1),targetAgentIds:e6.array(e6.string().min(1)).min(1)}),service:w,method:"syncProfile",arguments:e=>[e.uuid,e.sourceAgentId,e.targetAgentIds],resultKey:"operation",annotations:ae}),rm({name:"delete_signing_profile",title:"Delete signing profile",description:"Delete a provisioning profile from selected agents.",inputSchema:e6.object({uuid:e6.string().min(1),agentIds:e6.array(e6.string().min(1)).min(1)}),service:w,method:"deleteProfile",arguments:e=>[e.uuid,e.agentIds],resultKey:"operation",annotations:at}),rm({name:"delete_expired_signing_profiles",title:"Delete expired signing profiles",description:"Delete expired provisioning profiles from selected or all agents.",inputSchema:e6.object({agentIds:e6.array(e6.string().min(1)).optional()}),service:w,method:"deleteExpiredProfiles",arguments:({agentIds:e})=>[e],resultKey:"operation",annotations:at})]})),e.iosDevices&&j.push((b=e.iosDevices,{id:"builtin:ios-devices",name:"iOS Devices",children:[],tools:[rm({name:"get_ios_devices",title:"Get iOS devices",description:"List enrolled and pending iOS devices.",inputSchema:e6.object({status:e6.enum(["PENDING","REGISTERING","REGISTERED","REGISTRATION_FAILED","REJECTED"]).nullable().optional()}),service:b,method:"devices",arguments:({status:e})=>[e],resultKey:"devices"}),rm({name:"get_ios_device",title:"Get iOS device",description:"Get one enrolled or pending iOS device.",inputSchema:e6.object({id:e6.string().min(1)}),service:b,method:"device",arguments:({id:e})=>[e],resultKey:"device"}),rm({name:"get_ios_device_firmware",title:"Get iOS device firmware",description:"Get firmware metadata discovered for an iOS device.",inputSchema:e6.object({id:e6.string().min(1)}),service:b,method:"deviceFirmware",arguments:({id:e})=>[e],resultKey:"firmware"}),rm({name:"get_ios_device_settings",title:"Get iOS device settings",description:"Get redacted enrollment and App Store Connect settings.",inputSchema:e6.object({}),service:b,method:"getSettings",arguments:()=>[],resultKey:"settings"}),rm({name:"rename_ios_device",title:"Rename iOS device",description:"Change the display name of an iOS device.",inputSchema:e6.object({id:e6.string().min(1),displayName:e6.string().min(1)}),service:b,method:"renameDevice",arguments:e=>[e.id,e.displayName],resultKey:"device",annotations:ai}),rm({name:"register_ios_device",title:"Register iOS device",description:"Register a pending iOS device with the Apple Developer portal.",inputSchema:e6.object({id:e6.string().min(1)}),service:b,method:"registerDevice",arguments:({id:e})=>[e],resultKey:"device",annotations:ai}),rm({name:"reject_ios_device",title:"Reject iOS device",description:"Reject a pending iOS device enrollment.",inputSchema:e6.object({id:e6.string().min(1)}),service:b,method:"rejectDevice",arguments:({id:e})=>[e],resultKey:"device",annotations:ai}),rm({name:"delete_ios_device",title:"Delete iOS device",description:"Permanently delete an iOS device record.",inputSchema:e6.object({id:e6.string().min(1)}),service:b,method:"deleteDevice",arguments:({id:e})=>[e],resultKey:"deleted",annotations:aa})]})),e.notifications&&j.push((v=e.notifications,{id:"builtin:notifications",name:"Notifications",children:[],tools:[rm({name:"get_notification_history",title:"Get notification history",description:"Get paginated application notification history.",inputSchema:e6.object({first:e6.number().int().min(1).max(500).default(100),after:e6.string().nullable().optional()}),service:v,method:"history",resultKey:"page"}),rm({name:"get_notification_preferences",title:"Get notification preferences",description:"Get notification-category preferences.",inputSchema:e6.object({}),service:v,method:"preferences",arguments:()=>[],resultKey:"preferences"}),rm({name:"get_notification_sidebar",title:"Get notification sidebar",description:"Get unread and recent notification sidebar state.",inputSchema:e6.object({limit:e6.number().int().min(1).max(200).default(25)}),service:v,method:"sidebar",arguments:({limit:e})=>[e],resultKey:"sidebar"}),rm({name:"get_web_push_status",title:"Get web-push status",description:"Get redacted web-push readiness and subscription status.",inputSchema:e6.object({}),service:v,method:"webPushState",arguments:()=>[],resultKey:"status",annotations:ar}),rm({name:"update_notification_preference",title:"Update notification preference",description:"Update one notification-category preference.",inputSchema:e6.object({input:e6.object({typeKey:e6.string().min(1),sidebarEnabled:e6.boolean(),browserEnabled:e6.boolean(),webPushEnabled:e6.boolean()})}),service:v,method:"savePreference",arguments:({input:e})=>[e],resultKey:"preference",annotations:ae}),rm({name:"dismiss_notification",title:"Dismiss notification",description:"Dismiss one application notification.",inputSchema:e6.object({id:e6.string().min(1)}),service:v,method:"dismiss",arguments:({id:e})=>[e],resultKey:"dismissed",annotations:ae}),rm({name:"dismiss_all_notifications",title:"Dismiss all notifications",description:"Dismiss every current application notification.",inputSchema:e6.object({}),service:v,method:"dismissAll",arguments:()=>[],resultKey:"count",annotations:ae}),rm({name:"delete_notifications",title:"Delete notifications",description:"Permanently delete notifications selected by IDs or filters.",inputSchema:e6.object({selection:e6.object({all:e6.boolean().nullable().optional(),ids:e6.array(e6.string().min(1)).nullable().optional(),excludedIds:e6.array(e6.string().min(1)).nullable().optional(),ranges:e6.array(e6.object({start:iA.iso.datetime(),end:iA.iso.datetime()})).nullable().optional(),excludedRanges:e6.array(e6.object({start:iA.iso.datetime(),end:iA.iso.datetime()})).nullable().optional()})}),service:v,method:"deleteSelection",arguments:({selection:e})=>[e],resultKey:"count",annotations:at}),rm({name:"test_web_push_subscription",title:"Test web-push subscription",description:"Send a test notification to a saved web-push subscription.",inputSchema:e6.object({id:e6.string().min(1)}),service:v,method:"testWebPushSubscription",arguments:({id:e})=>[e],resultKey:"sent",annotations:ai})]})),e.ccusage&&e.modelCosts&&j.push((k=e.ccusage,E=e.modelCosts,{id:"builtin:usage-costs",name:"Usage and Costs",children:[],tools:[rm({name:"collect_ccusage",title:"Collect ccusage",description:"Collect current local AI-provider usage from enrolled agents.",inputSchema:e6.object({requestId:e6.string().nullable().optional()}),service:k,method:"collect",arguments:({requestId:e})=>[e],resultKey:"collection",annotations:ae}),rm({name:"get_ccusage_collection",title:"Get ccusage collection",description:"Get a usage collection and aggregated model usage.",inputSchema:e6.object({id:e6.string().min(1)}),service:k,method:"getCollection",arguments:({id:e})=>[e],resultKey:"collection"}),rm({name:"get_model_cost_catalog",title:"Get model cost catalog",description:"Get the active model-pricing catalog and refresh metadata.",inputSchema:e6.object({}),service:E,method:"getCatalog",arguments:()=>[],resultKey:"catalog",annotations:ar}),rm({name:"get_model_cost_entries",title:"Get model cost entries",description:"List model-pricing entries with search and pagination.",inputSchema:e6.object({search:e6.string().nullable().optional(),first:e6.number().int().min(1).max(500).default(100),offset:e6.number().int().min(0).default(0),sortKey:e6.enum(["MODEL","PROVIDER","INPUT","OUTPUT","UPDATED_AT"]).default("MODEL"),direction:e6.enum(["ASC","DESC"]).default("ASC")}),service:E,method:"listEntries",resultKey:"page"}),rm({name:"refresh_model_costs",title:"Refresh model costs",description:"Refresh the model-pricing catalog from its configured URL.",inputSchema:e6.object({}),service:E,method:"refresh",arguments:()=>[],resultKey:"catalog",annotations:ai}),rm({name:"estimate_model_cost",title:"Estimate model cost",description:"Estimate cost for token usage using the current model-pricing catalog.",inputSchema:e6.object({model:e6.string().min(1),inputTokens:e6.number().int().min(0).default(0),outputTokens:e6.number().int().min(0).default(0),cacheCreationInputTokens:e6.number().int().min(0).default(0),cacheReadInputTokens:e6.number().int().min(0).default(0)}),service:{estimate:async e=>{await E.ensureFresh();let t=await E.lookup([String(e.model)]);return E.estimate(t.get(String(e.model)),{inputTokens:Number(e.inputTokens),outputTokens:Number(e.outputTokens),cacheWriteTokens:Number(e.cacheCreationInputTokens),cacheReadTokens:Number(e.cacheReadInputTokens)})}},method:"estimate",resultKey:"estimate"})]})),e.systemStatus&&e.polling&&e.credentials&&j.push((S=e.systemStatus,I=e.polling,A=e.credentials,{id:"builtin:system",name:"System",children:[],tools:[rm({name:"get_system_status",title:"Get system status",description:"Get the control plane's aggregated operational health.",inputSchema:e6.object({}),service:S,method:"status",arguments:()=>[],resultKey:"status"}),rm({name:"get_polling_operations",title:"Get polling operations",description:"List registered background polling operations and their current states.",inputSchema:e6.object({}),service:I,method:"list",arguments:()=>[],resultKey:"operations"}),rm({name:"get_credential_store_status",title:"Get credential store status",description:"Get credential-store health without returning credential values.",inputSchema:e6.object({}),service:A,method:"status",arguments:()=>[],resultKey:"status"}),rm({name:"get_credential_metadata",title:"Get credential metadata",description:"List redacted credential metadata; values are never returned.",inputSchema:e6.object({}),service:A,method:"list",arguments:()=>[],resultKey:"credentials"})]})),e.cacheServer&&e.jira&&e.github&&j.push((x=e.cacheServer,_=e.jira,C=e.github,R=e.gitlab,{id:"builtin:cache-administration",name:"Cache Administration",tools:[],children:[{id:"builtin:cache-administration:cache-server",name:"Cache Server",children:[],tools:[rm({name:"get_cache_server_entries",title:"Get cache-server entries",description:"List cache-server entries with filters and pagination.",inputSchema:e6.object({filters:e6.object({key:e6.string().nullable().optional(),version:e6.string().nullable().optional(),scope:e6.string().nullable().optional(),repoId:e6.string().nullable().optional(),itemsPerPage:e6.number().int().min(1).max(500).default(20),page:e6.number().int().min(1).default(1)}).default({itemsPerPage:20,page:1})}),service:x,method:"listCacheEntries",arguments:({filters:e})=>[e],resultKey:"page",annotations:ar}),rm({name:"get_cache_server_entry",title:"Get cache-server entry",description:"Get cache-entry detail without secret connection values.",inputSchema:e6.object({id:e6.string().min(1)}),service:x,method:"getCacheEntryDetail",arguments:({id:e})=>[e],resultKey:"entry",annotations:ar}),rm({name:"match_cache_server_entry",title:"Match cache-server entry",description:"Find a cache entry matching build cache keys.",inputSchema:e6.object({input:e6.object({primaryKey:e6.string().min(1),restoreKeys:e6.array(e6.string()).nullable().optional(),scopes:e6.array(e6.string()).min(1),repoId:e6.string().min(1),version:e6.string().min(1)})}),service:x,method:"matchCacheEntry",arguments:({input:e})=>[e],resultKey:"match",annotations:ar}),rm({name:"get_cache_storage_location",title:"Get cache storage location",description:"Get one cache storage-location summary.",inputSchema:e6.object({id:e6.string().min(1)}),service:x,method:"getStorageLocation",arguments:({id:e})=>[e],resultKey:"location",annotations:ar}),rm({name:"delete_cache_server_entries",title:"Delete cache-server entries",description:"Permanently delete selected cache-server entries.",inputSchema:e6.object({ids:e6.array(e6.string().min(1)).min(1)}),service:x,method:"deleteCacheEntriesByIds",arguments:({ids:e})=>[e],resultKey:"deleted",annotations:aa})]},{id:"builtin:cache-administration:jira",name:"Jira Cache",children:[],tools:[rm({name:"get_jira_cache_metrics",title:"Get Jira cache metrics",description:"Get Jira cache hit, live-call, error, and latency metrics.",inputSchema:e6.object({}),service:_,method:"cacheMetrics",arguments:()=>[],resultKey:"metrics"}),rm({name:"get_jira_api_calls",title:"Get Jira API calls",description:"List redacted Jira API-call history.",inputSchema:e6.object({limit:e6.number().int().min(1).max(500).default(100),offset:e6.number().int().min(0).default(0)}),service:_,method:"listApiCalls",arguments:e=>[e.limit,e.offset],resultKey:"page"}),rm({name:"get_jira_cached_entries",title:"Get Jira cached entries",description:"List cached Jira ticket entries.",inputSchema:e6.object({limit:e6.number().int().min(1).max(500).default(100),offset:e6.number().int().min(0).default(0)}),service:_,method:"listCachedTickets",arguments:e=>[e.limit,e.offset],resultKey:"page"}),rm({name:"clear_jira_cache",title:"Clear Jira cache",description:"Permanently clear all cached Jira tickets.",inputSchema:e6.object({}),service:_,method:"clearCache",arguments:()=>[],resultKey:"cleared",annotations:aa})]},{id:"builtin:cache-administration:github",name:"GitHub Cache",children:[],tools:[rm({name:"get_github_cache_metrics",title:"Get GitHub cache metrics",description:"Get GitHub cache and API-call metrics.",inputSchema:e6.object({}),service:C,method:"cacheMetrics",arguments:()=>[],resultKey:"metrics"}),rm({name:"get_github_api_calls",title:"Get GitHub API calls",description:"List redacted GitHub API-call history.",inputSchema:e6.object({limit:e6.number().int().min(1).max(500).default(100),offset:e6.number().int().min(0).default(0)}),service:C,method:"apiCalls",arguments:e=>[e.limit,e.offset,{}],resultKey:"page"}),rm({name:"get_github_cached_entries",title:"Get GitHub cached entries",description:"List cached GitHub API entries.",inputSchema:e6.object({limit:e6.number().int().min(1).max(500).default(100),offset:e6.number().int().min(0).default(0)}),service:C,method:"cachedEntries",arguments:e=>[e.limit,e.offset],resultKey:"page"}),rm({name:"clear_github_cache",title:"Clear GitHub cache",description:"Permanently clear cached GitHub API entries.",inputSchema:e6.object({}),service:C,method:"clearCache",arguments:()=>[],resultKey:"cleared",annotations:at})]},...R?[{id:"builtin:cache-administration:gitlab",name:"GitLab Cache",children:[],tools:[rm({name:"get_gitlab_cache_metrics",title:"Get GitLab cache metrics",description:"Get GitLab cache and API-call metrics.",inputSchema:e6.object({}),service:R,method:"cacheMetrics",arguments:()=>[],resultKey:"metrics"}),rm({name:"get_gitlab_api_calls",title:"Get GitLab API calls",description:"List redacted GitLab API-call history.",inputSchema:e6.object({limit:e6.number().int().min(1).max(500).default(100),offset:e6.number().int().min(0).default(0)}),service:R,method:"apiCalls",arguments:({limit:e,offset:t})=>[e,t],resultKey:"page"}),rm({name:"get_gitlab_cached_entries",title:"Get GitLab cached entries",description:"List cached GitLab REST API entries.",inputSchema:e6.object({limit:e6.number().int().min(1).max(500).default(100),offset:e6.number().int().min(0).default(0)}),service:R,method:"cachedEntries",arguments:({limit:e,offset:t})=>[e,t],resultKey:"page"}),rm({name:"clear_gitlab_cache",title:"Clear GitLab cache",description:"Permanently clear cached GitLab REST entries.",inputSchema:e6.object({}),service:R,method:"clearCache",arguments:()=>[],resultKey:"cleared",annotations:at})]}]:[]]})),e.toolAudit&&e.testExternalMcpServer&&j.push((T=e.toolAudit,D=e.testExternalMcpServer,{id:"builtin:tool-administration",name:"Tool Administration",children:[],tools:[rm({name:"test_external_mcp_server",title:"Test external MCP server",description:"Connect to a configured external MCP server and report its tool count without returning saved headers.",inputSchema:e6.object({id:e6.string().min(1)}),service:{testExternalServer:D},method:"testExternalServer",arguments:({id:e})=>[e],resultKey:"status",annotations:ar}),rm({name:"get_tool_call_history",title:"Get tool call history",description:"List redacted tool-call audit records. Arguments are represented only by SHA-256 hashes.",inputSchema:e6.object({first:e6.number().int().min(1).max(500).default(100),toolName:e6.string().nullable().optional(),resultStatus:e6.enum(["RUNNING","SUCCEEDED","FAILED"]).nullable().optional()}),service:T,method:"list",resultKey:"calls"}),rm({name:"get_tool_call",title:"Get tool call",description:"Get one redacted tool-call audit record by ID.",inputSchema:e6.object({id:e6.string().min(1)}),service:T,method:"get",arguments:({id:e})=>[e],resultKey:"call"})]})),e.workflows&&j.push((N=e.workflows,U={id:"builtin:workflows:discovery",name:"Discovery",children:[],tools:[an({name:"list_workflow_step_kinds",title:"List workflow step kinds",description:"Browse the step kinds a workflow can be built from, with a short description of each. Start here when authoring; use describe_workflow_kind for the config schema of one kind.",inputSchema:e6.object({category:e6.string().optional().describe("Restrict to one category, e.g. 'Jira' or 'Control flow'."),search:e6.string().optional().describe("Match against kind, label, category, and description.")}),outputSchema:e6.object({steps:e6.array(e6.object({kind:e6.string(),category:e6.string(),label:e6.string(),description:e6.string(),execution:e6.string(),requiredPaths:e6.array(e6.string()),providedPaths:e6.array(e6.string()),sourceHandles:e6.array(e6.string()),mutatesExternal:e6.boolean(),mutatesWorktree:e6.boolean()}))}),annotations:i7,handler:({category:e,search:t})=>({steps:iC.WORKFLOW_STEP_CATALOG.filter(r=>(!e||r.category===e)&&iY(`${r.kind} ${r.label} ${r.category} ${r.description}`,t)).map(e=>({kind:e.kind,category:e.category,label:e.label,description:e.description,execution:e.execution,requiredPaths:e.requiredPaths,providedPaths:e.providedPaths,sourceHandles:e.sourceHandles,mutatesExternal:e.mutatesExternal,mutatesWorktree:e.mutatesWorktree}))})}),an({name:"list_workflow_trigger_kinds",title:"List workflow trigger kinds",description:"Browse the trigger kinds that can start a workflow, with what each one seeds into session data. Every workflow needs at least one trigger.",inputSchema:e6.object({category:e6.string().optional(),search:e6.string().optional()}),outputSchema:e6.object({triggers:e6.array(e6.object({kind:e6.string(),category:e6.string(),label:e6.string(),description:e6.string(),seedPaths:e6.array(e6.string()),sourceHandles:e6.array(e6.string())}))}),annotations:i7,handler:({category:e,search:t})=>({triggers:iC.WORKFLOW_TRIGGER_CATALOG.filter(r=>(!e||r.category===e)&&iY(`${r.kind} ${r.label} ${r.category} ${r.description}`,t)).map(e=>({kind:e.kind,category:e.category,label:e.label,description:e.description,seedPaths:e.seedPaths,sourceHandles:e.sourceHandles}))})}),an({name:"describe_workflow_kind",title:"Describe a workflow step or trigger kind",description:"Full detail for one kind: long-form notes on preconditions and side effects, the JSON Schema for its config, the session paths it requires and provides, and the handles edges may leave it from.",inputSchema:e6.object({kind:e6.string().min(1).describe("A step or trigger kind.")}),outputSchema:e6.object({scope:e6.enum(["step","trigger"]),kind:e6.string(),category:e6.string(),label:e6.string(),description:e6.string(),details:e6.string(),execution:e6.string().nullable(),configSchema:e6.unknown(),requiredPaths:e6.array(e6.string()),providedPaths:e6.array(e6.string()),seedPaths:e6.array(e6.string()),sourceHandles:e6.array(e6.string()),mutatesExternal:e6.boolean(),mutatesWorktree:e6.boolean()}),annotations:i7,handler:({kind:e})=>{let t=iC.WORKFLOW_STEP_CATALOG.find(t=>t.kind===e);if(t)return{scope:"step",...t,configSchema:re(t.configSchema),seedPaths:[]};let r=iX(e);return{scope:"trigger",...r,configSchema:re(r.configSchema),execution:null,requiredPaths:[],providedPaths:[],mutatesExternal:!1,mutatesWorktree:!1}}}),an({name:"list_workflow_session_paths",title:"List workflow session-data paths",description:"The session-data vocabulary a step's config can bind to — concrete paths like `ticket.key` or `pr.number`, with what each holds. Use it to write bindings that resolve at run time.",inputSchema:e6.object({namespace:e6.string().optional().describe("Restrict to one namespace, e.g. 'ticket' or 'pr'.")}),outputSchema:e6.object({paths:e6.array(e6.object({path:e6.string(),description:e6.string().nullable()}))}),annotations:i7,handler:({namespace:e})=>({paths:(function(e){let t=new Map,r=e=>{t.has(e.path)||t.set(e.path,e)};for(let t of e){let e=t.trim();if(e&&"*"!==e){if(e.endsWith(".*")){let t=e.slice(0,-2),i=iL[iU(t)];if(i)for(let e of i)r({path:`${t}.${e.name}`,description:e.description});else r({path:e});continue}r({path:e,description:function(e){let t=e.split(".");if(t.length<2)return;let r=t[t.length-1];return iB.get(`${iU(e)}.${r}`)}(e)})}}return[...t.values()].sort((e,t)=>e.path.localeCompare(t.path))})(e?[`${e}.*`]:[...new Set(iC.WORKFLOW_TRIGGER_CATALOG.flatMap(({seedPaths:e})=>e))]).map(({path:e,description:t})=>({path:e,description:t??null}))})}),an({name:"get_workflow_path_availability",title:"Get workflow path availability",description:"Per step, the session paths guaranteed to exist before it runs and the ones it contributes. This is what decides whether a config binding is legal — check it before binding a step to a path.",inputSchema:ij,outputSchema:e6.object({steps:e6.array(e6.object({nodeId:e6.string(),kind:e6.string(),availableBefore:e6.array(e6.string()),provides:e6.array(e6.string())})),triggerSeeds:e6.array(e6.object({triggerId:e6.string(),kind:e6.string(),seedPaths:e6.array(e6.string())})),violations:e6.array(e6.object({nodeId:e6.string(),triggerId:e6.string(),triggerName:e6.string(),path:e6.string()}))}),annotations:i7,handler:async({workflowId:e})=>{let t=await iZ(N,e),r=(0,iC.computeWorkflowPathAvailability)(t);return{steps:t.nodes.map(e=>({nodeId:e.id,kind:e.kind,availableBefore:r.availableBefore.get(e.id)??[],provides:r.provides.get(e.id)??[]})),triggerSeeds:t.triggers.map(e=>({triggerId:e.id,kind:e.kind,seedPaths:["workflow.*",...iX(e.kind).seedPaths,...(0,iC.resourceManualSeedPaths)(e.kind,e.config)]})),violations:r.requirementViolations}}})]},{id:"builtin:workflows",name:"Workflows",tools:[],children:[U,{id:"builtin:workflows:authoring",name:"Authoring",children:[],tools:[an({name:"list_workflows",title:"List workflows",description:"List workflows with their publish and enablement state.",inputSchema:e6.object({search:e6.string().optional().describe("Match name or description."),archive:e6.enum(["ACTIVE","ARCHIVED","ALL"]).optional().describe("Defaults to ACTIVE."),enabled:e6.boolean().optional(),first:e6.number().int().min(1).max(200).optional(),after:e6.string().optional().describe("Cursor from a previous page.")}),outputSchema:e6.object({workflows:e6.array(iH),nextCursor:e6.string().nullable(),totalCount:e6.number()}),annotations:i7,handler:async e=>{let t=await N().list(e);return{workflows:t.items.map(e=>rt(e)),nextCursor:t.nextCursor,totalCount:t.totalCount}}}),an({name:"get_workflow",title:"Get workflow",description:"Read one workflow, optionally with its full draft definition — every trigger, step, and connection.",inputSchema:e6.object({workflowId:e6.string().min(1),includeDefinition:e6.boolean().optional().describe("Include the draft graph. Defaults to true.")}),outputSchema:e6.object({workflow:iH,definition:e6.unknown().nullable(),activeVersion:e6.unknown().nullable()}),annotations:i7,handler:async({workflowId:e,includeDefinition:t})=>{let r=await N().get(e);if(!r)throw Error(`Workflow ${e} was not found`);return{workflow:rt(r),definition:!1===t?null:JSON.parse(r.draftDefinitionJson),activeVersion:r.activeVersion?rr(r.activeVersion):null}}}),an({name:"create_workflow",title:"Create workflow",description:"Create a workflow. Without a definition it starts as a draft holding one manual trigger and no steps, ready for add_workflow_step.",inputSchema:e6.object({name:e6.string().min(1).max(200),description:e6.string().max(2e3).optional(),definition:e6.unknown().optional().describe("A complete definition, e.g. from export_workflow."),overlapPolicy:e6.enum(["QUEUE","CONCURRENT","COALESCE_LATEST"]).optional().describe("What happens when a run starts while one is in flight. Defaults to QUEUE."),overlapScope:e6.enum(["WORKTREE","GLOBAL"]).optional().describe("Which runs the overlap policy counts: WORKTREE keeps a queue per worktree so worktrees never wait on each other, GLOBAL counts every run of the workflow. Defaults to WORKTREE."),maxConcurrentRuns:e6.number().int().min(1).optional(),completionNotificationsEnabled:e6.boolean().optional().describe("Whether successful runs create completion notifications. Defaults to true."),exclusiveWorktree:e6.boolean().optional().describe("Reserve a run's worktree and queue other workflows, plans, and sessions until it finishes. Defaults to false."),worktreeConcurrency:e6.enum(["EXCLUSIVE","NON_EXCLUSIVE","EXCLUDED"]).optional().describe("How runs participate in worktree admission. Defaults to NON_EXCLUSIVE."),blocksGitOperations:e6.boolean().optional().describe("Whether command and terminal steps block concurrent Git operations. Exclusive workflows always enable this.")}),outputSchema:e6.object({workflow:iH,definition:e6.unknown()}),annotations:ae,handler:async e=>{let t=await N().create(e);if(!t)throw Error("Workflow could not be created");return{workflow:rt(t),definition:JSON.parse(t.draftDefinitionJson)}}}),an({name:"update_workflow_settings",title:"Update workflow settings",description:"Change a workflow's name, description, concurrency, worktree exclusivity, or successful-run completion notifications. Name and description live inside the definition, so this rewrites the draft.",inputSchema:e6.object({workflowId:e6.string().min(1),name:e6.string().min(1).max(200).optional(),description:e6.string().max(2e3).optional(),overlapPolicy:e6.enum(["QUEUE","CONCURRENT","COALESCE_LATEST"]).optional(),overlapScope:e6.enum(["WORKTREE","GLOBAL"]).optional().describe("Which runs the overlap policy counts: WORKTREE keeps a queue per worktree, GLOBAL counts every run of the workflow."),maxConcurrentRuns:e6.number().int().min(1).optional(),completionNotificationsEnabled:e6.boolean().optional().describe("Set false to suppress successful-run completion notifications for this workflow. Failure and attention notifications remain enabled."),exclusiveWorktree:e6.boolean().optional().describe("Reserve the worktree for each top-level run of this workflow."),worktreeConcurrency:e6.enum(["EXCLUSIVE","NON_EXCLUSIVE","EXCLUDED"]).optional(),blocksGitOperations:e6.boolean().optional()}),outputSchema:iK,annotations:ae,handler:async e=>{let t=await iZ(N,e.workflowId),r={...t,name:e.name??t.name,description:e.description??t.description};return await N().saveDraft({id:e.workflowId,definition:r,overlapPolicy:e.overlapPolicy??null,overlapScope:e.overlapScope??null,maxConcurrentRuns:e.maxConcurrentRuns??null,completionNotificationsEnabled:e.completionNotificationsEnabled??null,exclusiveWorktree:e.exclusiveWorktree??null,worktreeConcurrency:e.worktreeConcurrency??null,blocksGitOperations:e.blocksGitOperations??null}),iQ(N,e.workflowId,r)}}),an({name:"set_workflow_enabled",title:"Enable or pause workflow",description:"Enable a workflow or pause it. A paused workflow ignores its triggers and refuses manual runs.",inputSchema:e6.object({workflowId:e6.string().min(1),enabled:e6.boolean()}),outputSchema:e6.object({workflow:iH}),annotations:ae,handler:async({workflowId:e,enabled:t})=>({workflow:rt(await N().setEnabled(e,t))})}),an({name:"archive_workflow",title:"Archive or restore workflow",description:"Move a workflow out of the active list, or bring it back. Reversible — use delete_workflow to remove it for good.",inputSchema:e6.object({workflowId:e6.string().min(1),archived:e6.boolean()}),outputSchema:e6.object({workflow:iH}),annotations:ae,handler:async({workflowId:e,archived:t})=>({workflow:rt(await N().archive(e,t))})}),an({name:"delete_workflow",title:"Delete workflow",description:"Permanently delete a workflow and its published versions. Refused once the workflow has run history — archive_workflow is the way to retire one that has run. Not reversible.",inputSchema:e6.object({workflowId:e6.string().min(1)}),outputSchema:e6.object({deleted:e6.boolean()}),annotations:at,handler:async({workflowId:e})=>({deleted:await N().delete(e)})}),an({name:"add_workflow_step",title:"Add workflow step",description:"Add a step to the draft and optionally wire it to an existing trigger or step. Returns the new step's id and the validator's view of the result.",inputSchema:e6.object({workflowId:e6.string().min(1),kind:e6.enum(iR.WORKFLOW_STEP_KINDS).describe("Step kind. See list_workflow_step_kinds."),name:e6.string().max(200).optional().describe("Display name. Defaults to the kind's label."),config:iq.optional(),connectFrom:e6.object({from:e6.string().min(1).describe("Trigger or step id this one follows."),sourceHandle:e6.string().optional().describe("Handle to leave from — 'success' by default, 'true'/'false' on an If, 'body'/'empty' on a For each, an option key on a choice trigger.")}).optional(),position:iM.optional(),failurePolicy:e6.enum(["FAIL","CONTINUE"]).optional().describe("CONTINUE lets the run carry on past a failure."),retry:e6.object({maxAttempts:e6.number().int().min(1).max(20),strategy:e6.enum(["FIXED","EXPONENTIAL"]),delaySeconds:e6.number().int().min(1).max(86400)}).optional(),providedPaths:i$.optional(),requiredPaths:iF.optional()}),outputSchema:iK,annotations:ae,handler:async e=>{let t=function(e,t){let r=iT(e,"node"),i={id:r,kind:t.kind,name:t.name??void 0,position:t.position??function(e,t){let r=t?iD(e,t):void 0,i=r?r.position.x+320:320,a=r?r.position.y:120,n=[...e.nodes,...e.triggers].filter(e=>160>Math.abs(e.position.x-i)).map(e=>e.position.y),s=a;for(;n.some(e=>80>Math.abs(e-s));)s+=160;return{x:i,y:s}}(e,t.connectFrom?.from??null),config:t.config??{},requiredPaths:t.requiredPaths??[],providedPaths:t.providedPaths??[],retry:t.retry??{maxAttempts:1,strategy:"EXPONENTIAL",delaySeconds:5},failurePolicy:t.failurePolicy??"FAIL"},a={...e,nodes:[...e.nodes,i]};if(!t.connectFrom)return{definition:a,nodeId:r,edgeId:null};let n=iP(a,{source:t.connectFrom.from,target:r,sourceHandle:t.connectFrom.sourceHandle??null});return{definition:n.definition,nodeId:r,edgeId:n.edgeId}}(await iZ(N,e.workflowId),{...e,name:e.name??function(e){let t=iC.WORKFLOW_STEP_CATALOG.find(t=>t.kind===e);if(!t)throw Error(`Unknown step kind ${e}`);return t}(e.kind).label});return iQ(N,e.workflowId,t.definition,{nodeId:t.nodeId,edgeId:t.edgeId})}}),an({name:"update_workflow_step",title:"Update workflow step",description:"Change a step's name, config, retry, or failure policy. Prefer configPatch, which merges — config replaces the object wholesale.",inputSchema:e6.object({workflowId:e6.string().min(1),nodeId:e6.string().min(1),name:e6.string().max(200).optional(),config:iq.optional().describe("Replaces the entire config. Keys left out are dropped."),configPatch:e6.record(e6.string(),e6.unknown()).optional().describe("Merges into the existing config. A null value removes that key."),position:iM.optional(),failurePolicy:e6.enum(["FAIL","CONTINUE"]).optional(),retry:e6.object({maxAttempts:e6.number().int().min(1).max(20),strategy:e6.enum(["FIXED","EXPONENTIAL"]),delaySeconds:e6.number().int().min(1).max(86400)}).optional(),providedPaths:i$.optional(),requiredPaths:iF.optional()}),outputSchema:iK,annotations:ae,handler:async e=>{let t=await iZ(N,e.workflowId);return iQ(N,e.workflowId,function(e,t){if(!e.nodes.some(({id:e})=>e===t.nodeId))throw Error(`Step ${t.nodeId} is not in this workflow`);if(t.config&&t.configPatch)throw Error("Pass either config or configPatch, not both");return{...e,nodes:e.nodes.map(e=>e.id===t.nodeId?{...e,name:t.name??e.name,config:iO(e.config,t),position:t.position??e.position,retry:t.retry??e.retry,failurePolicy:t.failurePolicy??e.failurePolicy,requiredPaths:t.requiredPaths??e.requiredPaths,providedPaths:t.providedPaths??e.providedPaths}:e)}}(t,e),{nodeId:e.nodeId})}}),an({name:"add_workflow_trigger",title:"Add workflow trigger",description:"Add a trigger to the draft. A workflow needs at least one, and each must reach a step before it can be published.",inputSchema:e6.object({workflowId:e6.string().min(1),kind:e6.enum(iR.WORKFLOW_TRIGGER_KINDS).describe("Trigger kind. See list_workflow_trigger_kinds."),name:e6.string().max(200).optional(),config:iq.optional().describe("Trigger config. Resource triggers need `resourceKind`; choice triggers need keyed `choices`; issue-command triggers need `allowedLogins` and an anchored `commandPattern`."),position:iM.optional()}),outputSchema:iK,annotations:ae,handler:async e=>{var t,r;let i,a,n=(t=await iZ(N,e.workflowId),r={...e,name:e.name??iX(e.kind).label},a={id:i=iT(t,"trigger"),kind:r.kind,name:r.name??void 0,config:r.config??{},position:r.position??{x:0,y:100+140*t.triggers.length}},{definition:{...t,triggers:[...t.triggers,a]},triggerId:i});return iQ(N,e.workflowId,n.definition,{triggerId:n.triggerId})}}),an({name:"update_workflow_trigger",title:"Update workflow trigger",description:"Change a trigger's name or config. Narrowing a choice trigger's options also removes the connections that left the options you dropped.",inputSchema:e6.object({workflowId:e6.string().min(1),triggerId:e6.string().min(1),name:e6.string().max(200).optional(),config:iq.optional(),configPatch:e6.record(e6.string(),e6.unknown()).optional(),position:iM.optional()}),outputSchema:iK,annotations:ae,handler:async e=>{let t=await iZ(N,e.workflowId);return iQ(N,e.workflowId,function(e,t){let r=e.triggers.find(({id:e})=>e===t.triggerId);if(!r)throw Error(`Trigger ${t.triggerId} is not in this workflow`);if(t.config&&t.configPatch)throw Error("Pass either config or configPatch, not both");let i={...r,name:t.name??r.name,config:iO(r.config,t),position:t.position??r.position},a=new Set(iN(i)),n=(0,iR.isChoiceTriggerKind)(i.kind)?e.edges.filter(e=>e.source!==i.id||a.has(e.sourceHandle)):e.edges;return{...e,triggers:e.triggers.map(e=>e.id===i.id?i:e),edges:n}}(t,e),{triggerId:e.triggerId})}}),an({name:"remove_workflow_node",title:"Remove workflow step or trigger",description:"Delete a step or trigger from the draft along with its connections. Set reconnect to stitch its predecessors to its successors so the chain survives.",inputSchema:e6.object({workflowId:e6.string().min(1),id:e6.string().min(1).describe("Step or trigger id."),reconnect:e6.boolean().optional().describe("Join what came before to what came after.")}),outputSchema:iK,annotations:at,handler:async({workflowId:e,id:t,reconnect:r})=>{let i=await iZ(N,e);return iQ(N,e,function(e,t,r={}){if(!iD(e,t))throw Error(`${t} is not in this workflow`);let i=e.edges.filter(e=>e.target===t),a=e.edges.filter(e=>e.source===t),n=e.edges.filter(e=>e.source!==t&&e.target!==t),s={...e,nodes:e.nodes.filter(e=>e.id!==t),triggers:e.triggers.filter(e=>e.id!==t),edges:n};if(!r.reconnect)return s;for(let e of i)for(let t of a)s=iP(s,{source:e.source,sourceHandle:e.sourceHandle,target:t.target,targetHandle:t.targetHandle}).definition;return s}(i,t,{reconnect:r}))}}),an({name:"connect_workflow_nodes",title:"Connect workflow nodes",description:"Draw a connection from a trigger or step to a step. A step with more than one incoming connection must be a CONTROL_JOIN.",inputSchema:e6.object({workflowId:e6.string().min(1),source:e6.string().min(1).describe("Trigger or step id."),target:e6.string().min(1).describe("Step id. Triggers take no input."),sourceHandle:e6.string().optional().describe("Handle to leave from. Defaults to the source's first — 'success' for a step.")}),outputSchema:iK,annotations:ae,handler:async e=>{let t=iP(await iZ(N,e.workflowId),e);return iQ(N,e.workflowId,t.definition,{edgeId:t.edgeId})}}),an({name:"disconnect_workflow_nodes",title:"Disconnect workflow nodes",description:"Remove a connection, either by its edge id or by the pair of nodes it joins.",inputSchema:e6.object({workflowId:e6.string().min(1),edgeId:e6.string().optional(),source:e6.string().optional(),target:e6.string().optional(),sourceHandle:e6.string().optional()}),outputSchema:iK.extend({removedEdgeIds:e6.array(e6.string())}),annotations:ae,handler:async e=>{let t=function(e,t){let r=e.edges.filter(e=>t.edgeId?e.id===t.edgeId:(!!t.source||!!t.target)&&(!t.source||e.source===t.source)&&(!t.target||e.target===t.target)&&(!t.sourceHandle||e.sourceHandle===t.sourceHandle));if(!r.length)throw Error("No matching connection to remove");let i=new Set(r.map(({id:e})=>e));return{definition:{...e,edges:e.edges.filter(e=>!i.has(e.id))},removedEdgeIds:[...i]}}(await iZ(N,e.workflowId),e);return{...await iQ(N,e.workflowId,t.definition),removedEdgeIds:t.removedEdgeIds}}}),an({name:"layout_workflow",title:"Lay out workflow graph",description:"Reposition every trigger and step into readable left-to-right columns. Worth calling once after building a workflow, so it does not open as a pile of overlapping cards.",inputSchema:ij,outputSchema:iK,annotations:ae,handler:async({workflowId:e})=>{let t=await iZ(N,e);return iQ(N,e,function(e){let t=new Map;for(let r of e.edges)t.set(r.source,[...t.get(r.source)??[],r.target]);let r=new Map;for(let t of e.triggers)r.set(t.id,0);let i=e.triggers.map(({id:e})=>e),a=e.nodes.length*e.edges.length+1;for(;i.length&&a-- >0;){let e=i.shift(),a=r.get(e)??0;for(let n of t.get(e)??[])(r.get(n)??-1)>=a+1||(r.set(n,a+1),i.push(n))}let n=Math.max(0,...r.values());for(let t of e.nodes)r.has(t.id)||r.set(t.id,n+1);let s=new Map,o=e=>{let t=r.get(e.id)??0,i=s.get(t)??0;return s.set(t,i+1),{...e,position:{x:320*t,y:160*i}}},l=e.triggers.map(o),c=e.nodes.map(o);return{...e,triggers:l,nodes:c}}(t))}}),an({name:"set_workflow_definition",title:"Replace workflow definition",description:"Overwrite the entire draft graph. The bulk escape hatch — prefer the granular tools for single edits, which cannot clobber work they did not read.",inputSchema:e6.object({workflowId:e6.string().min(1),definition:e6.unknown().describe("A complete definition object, as returned by get_workflow.")}),outputSchema:iK,annotations:ae,handler:async({workflowId:e,definition:t})=>iQ(N,e,(0,iC.parseWorkflowDefinition)(t))}),an({name:"validate_workflow",title:"Validate workflow draft",description:"Check the draft without saving anything. Errors block publishing; the codes name the problem — REQUIREMENT_UNSATISFIED means a step binds a path its trigger cannot seed.",inputSchema:ij,outputSchema:e6.object({valid:e6.boolean(),diagnostics:e6.array(iG)}),annotations:i7,handler:async({workflowId:e})=>{let t=await N().validateDraft(e);return{valid:t.valid,diagnostics:t.diagnostics.map(e=>({severity:e.severity,code:e.code,message:e.message,nodeId:e.nodeId??null,triggerId:e.triggerId??null,path:e.path??null}))}}}),an({name:"publish_workflow",title:"Publish workflow",description:"Publish the draft as a new immutable version. Only a published version can run, and publishing fails if the draft has errors.",inputSchema:ij,outputSchema:e6.object({version:e6.unknown()}),annotations:ae,handler:async({workflowId:e})=>({version:rr(await N().publish(e))})}),an({name:"export_workflow",title:"Export workflow",description:"Export a workflow as a portable document, with secrets and machine-specific paths stripped. Pass a version id to export a published version instead of the draft.",inputSchema:e6.object({workflowId:e6.string().min(1),versionId:e6.string().optional()}),outputSchema:e6.object({export:e6.unknown()}),annotations:i7,handler:async({workflowId:e,versionId:t})=>({export:re(await N().export(e,t))})}),an({name:"import_workflow",title:"Import workflow",description:"Create a workflow from an exported document. References that cannot be resolved on this machine come in marked unresolved and must be fixed before publishing.",inputSchema:e6.object({payload:e6.unknown().describe("A document from export_workflow."),name:e6.string().max(200).optional()}),outputSchema:e6.object({workflow:iH,definition:e6.unknown()}),annotations:ae,handler:async e=>{let t=await N().import(e);if(!t)throw Error("Workflow could not be imported");return{workflow:rt(t),definition:JSON.parse(t.draftDefinitionJson)}}})]},{id:"builtin:workflows:runs",name:"Runs",children:[],tools:[an({name:"trigger_workflow",title:"Trigger workflow run",description:"Start a run of a published, enabled workflow. Runs whatever the workflow's steps do, including external side effects.",inputSchema:e6.object({workflowId:e6.string().min(1),sessionData:e6.record(e6.string(),e6.unknown()).optional().describe("Initial session data, merged with the trigger's seeds."),resourceKind:e6.enum(iR.WORKFLOW_RESOURCE_KINDS).optional().describe("Launch through a resource trigger of this kind."),resourceId:e6.string().optional().describe("The resource to launch against."),choice:e6.string().optional().describe("Option key when the workflow's trigger offers choices. Omitting it on a choice-only workflow returns the valid keys."),subjectKey:e6.string().optional().describe("Dedupe key. Defaults to the resource or a fresh id.")}),outputSchema:e6.object({run:iV}),annotations:iz,handler:async e=>{let t=await N().trigger(e);if(!t)throw Error("Workflow run could not be started");return{run:ri(t)}}}),an({name:"list_workflow_runs",title:"List workflow runs",description:"List runs, newest first, optionally filtered.",inputSchema:e6.object({workflowId:e6.string().optional(),status:e6.enum(["QUEUED","RUNNING","PAUSING","PAUSED","WAITING","BLOCKED","SUCCEEDED","FAILED","CANCELLED"]).optional(),search:e6.string().optional().describe("A run number, or part of a workflow name."),first:e6.number().int().min(1).max(200).optional(),after:e6.string().optional()}),outputSchema:e6.object({runs:e6.array(iV),nextCursor:e6.string().nullable(),totalCount:e6.number()}),annotations:i7,handler:async e=>{let t=await N().runs(e);return{runs:t.items.map(e=>ri(e)),nextCursor:t.nextCursor,totalCount:t.totalCount}}}),an({name:"get_workflow_run",title:"Get workflow run",description:"Read a run's status and session data, with its per-step attempts and any questions it is blocked on. Poll this after trigger_workflow.",inputSchema:e6.object({runId:e6.string().min(1),includeAttempts:e6.boolean().optional().describe("Include per-step attempts. Defaults to true.")}),outputSchema:e6.object({run:iV,attempts:e6.array(e6.unknown()),pendingQuestions:e6.array(iJ)}),annotations:i7,handler:async({runId:e,includeAttempts:t})=>{let r=await N().run(e);if(!r)throw Error(`Workflow run ${e} was not found`);let i=r.attempts??[];return{run:ri(r),attempts:!1===t?[]:i.map(e=>({id:String(e.id),nodeId:String(e.nodeId),kind:String(e.kind),generation:Number(e.generation),iterationKey:String(e.iterationKey??""),attempt:Number(e.attempt),status:String(e.status),phase:String(e.phase),input:t6(e.inputJson),output:t6(e.outputJson),error:"string"==typeof e.error?e.error:null,startedAt:t8(e.startedAt),finishedAt:t8(e.finishedAt)})),pendingQuestions:i.flatMap(e=>e.questionBatches??[]).filter(e=>"PENDING"===e.status).map(e=>{let t;return t=Array.isArray(e.questions)?e.questions:[],{batchId:String(e.id),runId:"string"==typeof e.runId?e.runId:null,status:String(e.status),createdAt:t8(e.createdAt),questions:t.map(e=>{let t=Array.isArray(e.options)?e.options:[];return{id:String(e.id),header:"string"==typeof e.header?e.header:null,prompt:String(e.prompt??""),multiSelect:!0===e.multiSelect,allowCustom:!0===e.allowCustom,options:t.map(e=>({label:String(e.label??""),description:"string"==typeof e.description?e.description:null}))}})}})}}}),an({name:"get_workflow_run_events",title:"Get workflow run events",description:"Read a run's event log in order. Pass the last sequence you saw to tail only what is new.",inputSchema:e6.object({runId:e6.string().min(1),afterSequence:e6.number().int().optional(),first:e6.number().int().min(1).max(500).optional()}),outputSchema:e6.object({events:e6.array(iW)}),annotations:i7,handler:async({runId:e,afterSequence:t,first:r})=>({events:(await N().runEvents(e,t,r)).map(e=>({id:String(e.id),runId:String(e.runId),attemptId:"string"==typeof e.attemptId?e.attemptId:null,sequence:Number(e.sequence),type:String(e.type),message:String(e.message??""),detail:t6(e.detailJson),createdAt:t8(e.createdAt)}))})}),an({name:"control_workflow_run",title:"Pause, resume, or cancel a run",description:"Change an in-flight run's lifecycle. Cancelling is final, and leaves any external effects already applied in place.",inputSchema:e6.object({runId:e6.string().min(1),action:e6.enum(["PAUSE","RESUME","CANCEL"])}),outputSchema:e6.object({run:iV}),annotations:at,handler:async({runId:e,action:t})=>{let r=await N().lifecycle(e,t);if(!r)throw Error("Workflow run lifecycle change failed");return{run:ri(r)}}}),an({name:"answer_workflow_question",title:"Answer a workflow question",description:"Answer the question a run is parked on so it can continue. Find the batch id and the questions through get_workflow_run.",inputSchema:e6.object({batchId:e6.string().min(1).describe("From get_workflow_run."),answers:e6.record(e6.string(),e6.unknown()).describe("Answers keyed by question id. A value is the chosen option label, a list of labels for a multi-select, or free text where a custom answer is allowed.")}),outputSchema:e6.object({run:iV}),annotations:ae,handler:async({batchId:e,answers:t})=>{let r=await N().answerQuestion(e,t);if(!r)throw Error("Workflow question could not be answered");return{run:ri(r)}}}),an({name:"prepare_workflow_replay",title:"Preview a workflow replay",description:"See what replaying a run from a given step would affect: the downstream steps, the external effects that would happen again, and whether a Git checkpoint is available. Read-only — call it before replay_workflow_run.",inputSchema:e6.object({runId:e6.string().min(1),nodeId:e6.string().min(1).describe("Step to replay from.")}),outputSchema:e6.object({preview:e6.unknown()}),annotations:i7,handler:async({runId:e,nodeId:t})=>({preview:re(await N().prepareReplay(e,t))})}),an({name:"replay_workflow_run",title:"Replay a workflow run from a step",description:"Re-run a workflow from one step onward. Every external effect downstream happens again — merges, comments, deploys — so preview it with prepare_workflow_replay first.",inputSchema:e6.object({runId:e6.string().min(1),nodeId:e6.string().min(1),restore:e6.boolean().optional().describe("Restore the worktree to the Git checkpoint at that step, discarding later changes."),stash:e6.boolean().optional().describe("Stash uncommitted changes before restoring.")}),outputSchema:e6.object({run:iV}),annotations:at,handler:async({runId:e,nodeId:t,restore:r,stash:i})=>{let a=await N().replay(e,t,{restore:r,stash:i});if(!a)throw Error("Workflow run could not be replayed");return{run:ri(a)}}}),an({name:"archive_workflow_runs",title:"Archive workflow runs",description:"Archive or restore workflow runs.",inputSchema:e6.object({ids:e6.array(e6.string().min(1)).min(1),archived:e6.boolean().default(!0)}),outputSchema:e6.object({count:e6.unknown()}),annotations:ae,handler:async({ids:e,archived:t})=>({count:await N().archiveRuns(e,t)})}),an({name:"delete_workflow_runs",title:"Delete workflow runs",description:"Permanently delete workflow runs and their retained execution history.",inputSchema:e6.object({ids:e6.array(e6.string().min(1)).min(1)}),outputSchema:e6.object({count:e6.unknown()}),annotations:at,handler:async({ids:e})=>({count:await N().deleteRuns(e)})}),an({name:"repair_workflow_run_data",title:"Repair workflow run data",description:"Repair session data for a blocked or paused workflow run.",inputSchema:e6.object({runId:e6.string().min(1),patch:e6.unknown()}),outputSchema:e6.object({run:e6.unknown()}),annotations:at,handler:async({runId:e,patch:t})=>({run:await N().repairRunData(e,t)})})]}]})),e.worktreeAutomations&&j.push((O=e.worktreeAutomations,{id:"builtin:worktree-automations",name:"Worktree Automations",children:[],tools:[an({name:"get_worktree_automations",title:"Get worktree automations",description:"Inspect the persisted Auto Sync and Auto Merge configuration and state for a worktree.",inputSchema:e6.object({worktreeId:e6.string().min(1)}),outputSchema:e6.object({autoSync:i5.nullable(),autoMerge:i9.nullable()}),annotations:i7,handler:async({worktreeId:e})=>({autoSync:await O().autoSync(e),autoMerge:await O().autoMerge(e)})}),an({name:"configure_worktree_auto_sync",title:"Configure worktree Auto Sync",description:"Enable or update Auto Sync. Optionally select a merge-conflict quick-action workflow and one of its trigger choices.",inputSchema:e6.object({worktreeId:e6.string().min(1),conflictWorkflowId:e6.string().min(1).nullable().optional(),conflictWorkflowChoice:e6.string().min(1).nullable().optional()}),outputSchema:e6.object({autoSync:i5}),annotations:ae,handler:async e=>({autoSync:await O().configureAutoSync(e)})}),an({name:"retry_worktree_auto_sync",title:"Retry worktree Auto Sync",description:"Resume a paused Auto Sync rule.",inputSchema:e6.object({worktreeId:e6.string().min(1)}),outputSchema:e6.object({autoSync:i5}),annotations:ae,handler:async({worktreeId:e})=>({autoSync:await O().retryAutoSync(e)})}),an({name:"force_worktree_auto_sync",title:"Force worktree Auto Sync",description:"Force an Auto Sync paused specifically by a preparation conflict. Managed paths are reset, the sync runs, and current preparations are reapplied.",inputSchema:e6.object({worktreeId:e6.string().min(1),requestId:e6.string().min(1)}),outputSchema:e6.object({job:e6.unknown()}),annotations:at,handler:async({worktreeId:e,requestId:t})=>({job:await O().forceAutoSync(e,t)})}),an({name:"cancel_worktree_auto_sync",title:"Cancel worktree Auto Sync",description:"Cancel any active job and remove the Auto Sync rule.",inputSchema:e6.object({worktreeId:e6.string().min(1)}),outputSchema:e6.object({cancelled:e6.boolean()}),annotations:at,handler:async({worktreeId:e})=>({cancelled:await O().cancelAutoSync(e)})}),an({name:"configure_worktree_auto_merge",title:"Configure worktree Auto Merge",description:"Enable or update GitHub-native Auto Merge and its optional Jira/worktree post-merge actions.",inputSchema:e6.object({worktreeId:e6.string().min(1),repositoryNameWithOwner:e6.string().min(3),pullRequestNumber:e6.number().int().positive(),method:e6.enum(["MERGE","REBASE","SQUASH"]),commitHeadline:e6.string().min(1),commitBody:e6.string(),authorEmail:e6.string().email().nullable().optional(),deleteWorktree:e6.boolean(),moveTicketToDone:e6.boolean()}),outputSchema:e6.object({autoMerge:i9}),annotations:ae,handler:async e=>({autoMerge:await O().configureAutoMerge(e)})}),an({name:"retry_worktree_auto_merge",title:"Retry worktree Auto Merge",description:"Retry an Auto Merge rule that needs attention, including its safe post-merge actions.",inputSchema:e6.object({worktreeId:e6.string().min(1)}),outputSchema:e6.object({autoMerge:i9}),annotations:ae,handler:async({worktreeId:e})=>({autoMerge:await O().retryAutoMerge(e)})}),an({name:"cancel_worktree_auto_merge",title:"Cancel worktree Auto Merge",description:"Disable GitHub-native Auto Merge when still active and remove the persisted rule.",inputSchema:e6.object({worktreeId:e6.string().min(1)}),outputSchema:e6.object({cancelled:e6.boolean()}),annotations:at,handler:async({worktreeId:e})=>({cancelled:await O().cancelAutoMerge(e)})})]})),new al(j)}({codebaseTools:e,builds:t,...r,toolAudit:this.audit,testExternalMcpServer:e=>this.testExternalServer(e)})}async mcpToolPresets(e){let t=e?.trim().toUpperCase()??null;if(t&&!["PLAN","SESSION"].includes(t))throw Error("Run kind is not supported");let r=await (0,t1.getPrismaClient)();return(await r.mcpToolPreset.findMany({where:"PLAN"===t?{enabledForPlans:!0}:"SESSION"===t?{enabledForSessions:!0}:void 0,orderBy:{name:"asc"},include:{tools:!0}})).map(ay)}async toolCallAudits(e={}){return this.audit.list(e)}async clearToolCallAudits(){return this.audit.clear()}async createMcpToolPreset(e){return this.saveMcpToolPreset(null,e)}async updateMcpToolPreset(e,t){return this.saveMcpToolPreset(e,t)}async saveMcpToolPreset(e,t){let r=t.name.trim(),i=t.description?.trim()??"";if(!r)throw Error("Preset name is required");if(r.length>80)throw Error("Preset name must be 80 characters or fewer");if(i.length>1e3)throw Error("Preset description must be 1,000 characters or fewer");if(!ah.has(t.iconKey))throw Error("Preset icon is not supported");if(!t.toolNames.length)throw Error("Select at least one built-in tool");if(new Set(t.toolNames).size!==t.toolNames.length)throw Error("Preset tool membership must not contain duplicates");let a=new Set(this.builtInTools.definitions().map(({name:e})=>e)),n=t.toolNames.map(e=>e.trim()),s=n.find(e=>!e||!a.has(e));if(void 0!==s)throw Error(`Unknown built-in tool: ${s||"(empty)"}`);let o=await (0,t1.getPrismaClient)();if((await o.mcpToolPreset.findMany({select:{id:!0,name:!0}})).some(t=>t.id!==e&&t.name.toLocaleLowerCase()===r.toLocaleLowerCase()))throw Error("An MCP tool preset with this name already exists");if(e&&!await o.mcpToolPreset.findUnique({where:{id:e}}))throw Error("MCP tool preset not found");let l=e??(0,b.randomUUID)();return await o.$transaction(async e=>{await e.mcpToolPreset.upsert({where:{id:l},create:{id:l,name:r,description:i,iconKey:t.iconKey,enabledForPlans:t.enabledForPlans,enabledForSessions:t.enabledForSessions},update:{name:r,description:i,iconKey:t.iconKey,enabledForPlans:t.enabledForPlans,enabledForSessions:t.enabledForSessions}}),await e.mcpToolPresetTool.deleteMany({where:{presetId:l}}),await e.mcpToolPresetTool.createMany({data:n.map(e=>({presetId:l,toolName:e}))})}),ay(await o.mcpToolPreset.findUniqueOrThrow({where:{id:l},include:{tools:!0}}))}async deleteMcpToolPreset(e){let t=await (0,t1.getPrismaClient)();return await t.mcpToolPreset.delete({where:{id:e}}),{id:e}}async resolveRunMcpPresets(e,t){let r=[...new Set(t)];if(!r.length)return{presetIds:[],toolNames:[]};let i=await (0,t1.getPrismaClient)(),a=new Map((await i.mcpToolPreset.findMany({where:{id:{in:r},..."PLAN"===e?{enabledForPlans:!0}:{enabledForSessions:!0}},include:{tools:!0}})).map(e=>[e.id,e])),n=r.filter(e=>a.has(e)),s=new Set(this.builtInTools.definitions().map(({name:e})=>e)),o=new Set;for(let e of n)for(let{toolName:t}of a.get(e).tools)s.has(t)&&o.add(t);return{presetIds:n,toolNames:[...o].sort()}}async mcpPresetToolNames(e){let t=await (0,t1.getPrismaClient)(),r=await t.mcpToolPreset.findUnique({where:{id:e},include:{tools:!0}});if(!r)return null;let i=new Set(this.builtInTools.definitions().map(({name:e})=>e));return r.tools.map(({toolName:e})=>e).filter(e=>i.has(e))}async mcpRunToolNames(e,t){let r=await (0,t1.getPrismaClient)(),i=await r.agentRun.findUnique({where:{id:e},select:{agentId:!0,mcpToolNamesJson:!0,repositoryId:!0}});if(!i)return{status:"NOT_FOUND"};if(i.agentId!==t)return{status:"FORBIDDEN"};let a=JSON.parse(i.mcpToolNamesJson),n=new Set(Array.isArray(a)?a.filter(e=>"string"==typeof e):[]);return{status:"OK",repositoryId:i.repositoryId,toolNames:this.builtInTools.definitions().map(({name:e})=>e).filter(e=>n.has(e))}}async externalServers(){let e=await (0,t1.getPrismaClient)();return Promise.all((await e.externalMcpServer.findMany({orderBy:{name:"asc"},include:{headers:!0}})).map(async e=>ag(e,0===e.headers.length||await this.credentials.isConfigured((0,t2.externalMcpHeadersCredential)(e.id)))))}async createExternalServer(e){return this.saveExternalServer(null,e)}async updateExternalServer(e,t){return this.saveExternalServer(e,t)}async saveExternalServer(e,t){let r=function(e){let t,r=e.name.trim();if(!r)throw Error("Server name is required");if(r.length>80)throw Error("Server name must be 80 characters or fewer");try{t=new URL(e.url.trim())}catch{throw Error("Server URL must be a valid HTTP or HTTPS URL")}if(!["http:","https:"].includes(t.protocol)||t.username||t.password)throw Error("Server URL must be an HTTP or HTTPS URL without embedded credentials");if("STREAMABLE_HTTP"!==e.transport&&"SSE"!==e.transport)throw Error("Transport must be Streamable HTTP or SSE");let i=e.toolNamePrefix?.trim()??"";if(i.length>64||!/^[A-Za-z0-9_.-]*$/.test(i))throw Error("Tool name prefix may contain up to 64 letters, numbers, underscores, periods, or hyphens");let a=new Set,n=e.headers.map(e=>{let t=e.name.trim();if(!t)throw Error("Header name is required");let r=t.toLowerCase();if(ap.has(r))throw Error(`${t} is managed by the MCP transport`);if(a.has(r))throw Error(`Duplicate header name: ${t}`);a.add(r);try{new Headers([[t,e.value??"validation"]])}catch{throw Error(`Invalid HTTP header: ${t}`)}return{id:e.id??null,name:t,value:e.value}});return{name:r,url:t.toString(),transport:e.transport,toolNamePrefix:i,headers:n}}(t),i=await (0,t1.getPrismaClient)();if((await i.externalMcpServer.findMany({select:{id:!0,name:!0}})).some(t=>t.id!==e&&t.name.toLocaleLowerCase()===r.name.toLocaleLowerCase()))throw Error("An MCP server with this name already exists");let a=e?await i.externalMcpServer.findUnique({where:{id:e},include:{headers:!0}}):null;if(e&&!a)throw Error("External MCP server not found");let n=new Map(a?.headers.map(e=>[e.id,e])??[]),s=e??(0,b.randomUUID)(),o=(0,t2.externalMcpHeadersCredential)(s),l=e?await this.credentials.getJson(o)??[]:[],c=new Map(l.map(e=>[e.id,e]));for(let e of r.headers){if(e.id&&!n.has(e.id))throw Error(`Header ${e.name} does not belong to this server`);if(!e.id&&!e.value)throw Error(`A value is required for the new ${e.name} header`)}let u=r.headers.map(e=>{let t=e.id??(0,b.randomUUID)(),r=e.value||c.get(t)?.value;if(!r)throw Error(`A value is required for ${e.name}`);return{id:t,name:e.name,value:r}}),d=async e=>{await e.externalMcpServer.upsert({where:{id:s},create:{id:s,name:r.name,url:r.url,transport:r.transport,toolNamePrefix:r.toolNamePrefix},update:{name:r.name,url:r.url,transport:r.transport,toolNamePrefix:r.toolNamePrefix}}),await e.externalMcpServerHeader.deleteMany({where:{serverId:s}}),u.length&&await e.externalMcpServerHeader.createMany({data:u.map(e=>({id:e.id,serverId:s,name:e.name}))})},p=JSON.stringify(u)!==JSON.stringify(l);return u.length&&p?await this.credentials.setJson(o,u,d):!u.length&&l.length?await this.credentials.delete(o,d):await i.$transaction(d),ag(await i.externalMcpServer.findUniqueOrThrow({where:{id:s},include:{headers:!0}}),!0)}async deleteExternalServer(e){return await this.credentials.delete((0,t2.externalMcpHeadersCredential)(e),async t=>{await t.externalMcpServer.delete({where:{id:e}})}),{id:e}}async testExternalServer(e){let t=await this.externalServerWithSecrets(e),r=await this.listRemoteTools(t);return{id:t.id,name:t.name,toolCount:r.length}}async catalog(){let e=await (0,t1.getPrismaClient)(),t=await e.externalMcpServer.findMany({orderBy:{name:"asc"},include:{headers:!0}}),r=await Promise.all(t.map(async e=>{try{let t=await this.listRemoteTools(await this.externalServerWithSecrets(e.id));return{id:`${ad}${e.id}`,name:e.name,source:"EXTERNAL",transport:af(e.transport),url:e.url,error:null,tools:t.map(t=>({...t,name:`${e.toolNamePrefix}${t.name}`})),children:[]}}catch(t){return{id:`${ad}${e.id}`,name:e.name,source:"EXTERNAL",transport:af(e.transport),url:e.url,error:t instanceof Error?t.message:String(t),tools:[],children:[]}}})),[i,a]=await Promise.all([this.credentials.isConfigured(t2.CREDENTIALS.githubPersonalAccessToken),this.credentials.isConfigured(t2.CREDENTIALS.gitlabAccessToken)]);return{groups:[...this.builtInTools.catalog().filter(e=>"builtin:github"===e.id?i:"builtin:gitlab"!==e.id||a).map(e=>"builtin:cache-administration"===e.id?{...e,children:e.children.filter(e=>"builtin:cache-administration:github"===e.id?i:"builtin:cache-administration:gitlab"!==e.id||a)}:e),...r]}}async callTool(e,t){let r=()=>this.invokeTool(e);return t?this.audit.execute({...t,groupId:e.groupId,toolName:e.name,arguments:e.arguments},r):r()}async callBuiltInTool(e,t,r){let i=this.builtInTools.groupIdForName(e);if(!i)throw Error(`Unknown built-in tool: ${e}`);await this.assertProviderToolConfigured(i);let a=()=>this.builtInTools.callByName(e,t);return r?this.audit.execute({...r,groupId:i,toolName:e,arguments:t},a):a()}async callRunBuiltInTool(e,t,r,i){if(am.has(e)){let e="object"!=typeof t||null===t||Array.isArray(t)?null:t;if(!r||e?.repositoryId!==r)throw Error("Run-scoped MCP may only access preparations for the run repository")}return this.callBuiltInTool(e,t,i)}async invokeTool(e){if(this.builtInTools.hasGroup(e.groupId))return await this.assertProviderToolConfigured(e.groupId),this.builtInTools.call(e.groupId,e.name,e.arguments);if(!e.groupId.startsWith(ad))throw Error("Unknown tool group");let t=e.groupId.slice(ad.length),r=await this.externalServerWithSecrets(t);if(!e.name.startsWith(r.toolNamePrefix))throw Error("Tool name does not use this server's configured prefix");let i=e.name.slice(r.toolNamePrefix.length);if(!i)throw Error("Tool name is required");return this.withClient(r,t=>t.callTool({name:i,arguments:e.arguments},void 0,{timeout:12e4,resetTimeoutOnProgress:!0}))}async assertProviderToolConfigured(e){let t="builtin:github"===e||"builtin:cache-administration:github"===e?t2.CREDENTIALS.githubPersonalAccessToken:"builtin:gitlab"===e||"builtin:cache-administration:gitlab"===e?t2.CREDENTIALS.gitlabAccessToken:null;if(t&&!await this.credentials.isConfigured(t))throw Error(`${e.includes("github")?"GitHub":"GitLab"} tools are unavailable until the provider's primary access token is configured`)}async externalServerWithSecrets(e){let t=await (0,t1.getPrismaClient)(),r=await t.externalMcpServer.findUnique({where:{id:e},include:{headers:!0}});if(!r)throw Error("External MCP server not found");if(af(r.transport),!r.headers.length)return{...r,headers:[]};let i=await this.credentials.getJson((0,t2.externalMcpHeadersCredential)(r.id));if(!i)throw Error("External MCP server headers are not configured; re-enter them in Settings");let a=new Map(i.map(e=>[e.id,e]));return{...r,headers:r.headers.map(e=>{let t=a.get(e.id);if(!t?.value)throw Error(`External MCP header ${e.name} is missing; re-enter it in Settings`);return{id:e.id,name:e.name,value:t.value}})}}async withClient(e,t){var r;let i,a=new em({name:"ai-development-environment-tools",version:"0.1.0"}),n=(r=e,async(e,t)=>{let i=new Headers(r.headers.map(e=>[e.name,e.value]));return e instanceof Request&&e.headers.forEach((e,t)=>i.set(t,e)),new Headers(t?.headers).forEach((e,t)=>i.set(t,e)),fetch(e,{...t,headers:i})}),s="STREAMABLE_HTTP"===af(e.transport)?new t0(new URL(e.url),{fetch:n}):new tY(new URL(e.url),{fetch:n}),o=()=>i??=a.close().catch(()=>void 0);try{let e;try{await Promise.race([a.connect(s,{timeout:15e3}),new Promise((t,r)=>{e=setTimeout(()=>{o(),r(Error("External MCP server connection timed out after 15000ms"))},15e3)})])}finally{e&&clearTimeout(e)}return await t(a)}finally{await o()}}async listRemoteTools(e){return this.withClient(e,async e=>{let t,r=[],i=new Set,a=0;do{let n=await e.listTools(t?{cursor:t}:void 0,{timeout:15e3});a+=1,r.push(...n.tools.map(e=>({name:e.name,title:e.title??null,description:e.description??null,inputSchema:e.inputSchema,outputSchema:e.outputSchema??null,annotations:e.annotations?{readOnlyHint:e.annotations.readOnlyHint??!1,destructiveHint:e.annotations.destructiveHint??!1,idempotentHint:e.annotations.idempotentHint??!1,openWorldHint:e.annotations.openWorldHint??!0}:null})));let s=n.nextCursor;if(s){if(i.has(s))throw Error("External MCP server returned a repeated tools/list cursor");if(a>=100)throw Error("External MCP server exceeded the tools/list pagination limit of 100 pages");i.add(s)}t=s}while(t)return r})}}e.i(406478);var ab=e.i(406315),av=e.i(354470);function ak(e){let t=e.headers.get("x-request-id")?.trim();return t&&t.length<=128?t:(0,b.randomUUID)()}function aE(e){return e.headers.get("cf-connecting-ip")??e.headers.get("x-forwarded-for")?.split(",")[0]?.trim()??"unknown"}function aS(e){return Response.json({error:{code:"TOOL_API_UNAUTHORIZED",message:e}},{status:401,headers:{"www-authenticate":"Bearer"}})}async function aI(e,t){let r=(0,ab.crossOriginError)(e);if(r)return{response:r};try{let r=await (0,av.resolveRequestPrincipal)(e.headers);if("user"!==r.kind&&("MCP"!==t||"apiKey"!==r.kind))return{response:aS("TOOLS_PAGE"===t?"A user session is required":"A user session or X-API-Key is required")};let i="user"===r.kind?`user:${r.userId}`:`api-key:${r.apiKeyId}`;return{context:{caller:`${i}@${aE(e)}`,correlationId:ak(e),source:t}}}catch(e){if(e instanceof av.PrincipalResolutionError)return{response:aS(e.message)};throw e}}async function aA(e){return aI(e,"MCP")}async function ax(e,t){try{let r=await (0,av.resolveRequestPrincipal)(e.headers,t);if("agent"!==r.kind)return{response:aS("A valid enrolled agent credential is required")};return{agentId:r.agentId,context:{caller:`agent:${r.agentId}@${aE(e)}`,correlationId:ak(e),source:"MCP"}}}catch(e){if(e instanceof av.PrincipalResolutionError)return{response:aS(e.message)};throw e}}e.s(["authorizeMcpPresetRequest",0,aA,"authorizeRunMcpRequest",0,ax,"authorizeToolRequest",0,aI],583801);class a_{constructor(e){this._server=e}requestStream(e,t,r){return this._server.requestStream(e,t,r)}createMessageStream(e,t){let r=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!r?.sampling?.tools)throw Error("Client does not support sampling tools capability.");if(e.messages.length>0){let t=e.messages[e.messages.length-1],r=Array.isArray(t.content)?t.content:[t.content],i=r.some(e=>"tool_result"===e.type),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,n=a?Array.isArray(a.content)?a.content:[a.content]:[],s=n.some(e=>"tool_use"===e.type);if(i){if(r.some(e=>"tool_result"!==e.type))throw Error("The last message must contain only tool_result content if any is present");if(!s)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(s){let e=new Set(n.filter(e=>"tool_use"===e.type).map(e=>e.id)),t=new Set(r.filter(e=>"tool_result"===e.type).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},E.CreateMessageResultSchema,t)}elicitInputStream(e,t){let r=this._server.getClientCapabilities(),i=e.mode??"form";switch(i){case"url":if(!r?.elicitation?.url)throw Error("Client does not support url elicitation.");break;case"form":if(!r?.elicitation?.form)throw Error("Client does not support form elicitation.")}let a="form"===i&&void 0===e.mode?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:a},E.ElicitResultSchema,t)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,r){return this._server.getTaskResult({taskId:e},t,r)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}}class aC extends en{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(E.LoggingLevelSchema.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{let r=this._loggingLevels.get(t);return!!r&&this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(r)},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new eu,this.setRequestHandler(E.InitializeRequestSchema,e=>this._oninitialize(e)),this.setNotificationHandler(E.InitializedNotificationSchema,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(E.SetLevelRequestSchema,async(e,t)=>{let r=t.sessionId||t.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=e.params,a=E.LoggingLevelSchema.safeParse(i);return a.success&&this._loggingLevels.set(r,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new a_(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=eo(this._capabilities,e)}setRequestHandler(e,t){let r,i=(0,k.getObjectShape)(e),a=i?.method;if(!a)throw Error("Schema is missing a method literal");if((0,k.isZ4Schema)(a)){let e=a._zod?.def;r=e?.value??a.value}else{let e=a._def;r=e?.value??a.value}if("string"!=typeof r)throw Error("Schema method literal must be a string");if("tools/call"===r){let r=async(e,r)=>{let i=(0,k.safeParse)(E.CallToolRequestSchema,e);if(!i.success){let e=i.error instanceof Error?i.error.message:String(i.error);throw new E.McpError(E.ErrorCode.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:a}=i.data,n=await Promise.resolve(t(e,r));if(a.task){let e=(0,k.safeParse)(E.CreateTaskResultSchema,n);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new E.McpError(E.ErrorCode.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let s=(0,k.safeParse)(E.CallToolResultSchema,n);if(!s.success){let e=s.error instanceof Error?s.error.message:String(s.error);throw new E.McpError(E.ErrorCode.InvalidParams,`Invalid tools/call result: ${e}`)}return s.data};return super.setRequestHandler(e,r)}return super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`)}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`)}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${e})`)}}assertTaskCapability(e){eh(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&ep(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:E.SUPPORTED_PROTOCOL_VERSIONS.includes(t)?t:E.LATEST_PROTOCOL_VERSION,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},E.EmptyResultSchema)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.");if(e.messages.length>0){let t=e.messages[e.messages.length-1],r=Array.isArray(t.content)?t.content:[t.content],i=r.some(e=>"tool_result"===e.type),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,n=a?Array.isArray(a.content)?a.content:[a.content]:[],s=n.some(e=>"tool_use"===e.type);if(i){if(r.some(e=>"tool_result"!==e.type))throw Error("The last message must contain only tool_result content if any is present");if(!s)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(s){let e=new Set(n.filter(e=>"tool_use"===e.type).map(e=>e.id)),t=new Set(r.filter(e=>"tool_result"===e.type).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},E.CreateMessageResultWithToolsSchema,t):this.request({method:"sampling/createMessage",params:e},E.CreateMessageResultSchema,t)}async elicitInput(e,t){switch(e.mode??"form"){case"url":if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");return this.request({method:"elicitation/create",params:e},E.ElicitResultSchema,t);case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let r="form"===e.mode?e:{...e,mode:"form"},i=await this.request({method:"elicitation/create",params:r},E.ElicitResultSchema,t);if("accept"===i.action&&i.content&&r.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(r.requestedSchema)(i.content);if(!e.valid)throw new E.McpError(E.ErrorCode.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){if(e instanceof E.McpError)throw e;throw new E.McpError(E.ErrorCode.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return i}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:"roots/list",params:e},E.ListRootsResultSchema,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}let aR=Symbol.for("mcp.completable");function aT(e){return!!e&&"object"==typeof e&&aR in e}(i||(i={})).Completable="McpCompletable";let aD=/^[A-Za-z0-9._-]{1,128}$/;function aN(e){let t=function(e){let t=[];if(0===e.length)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(" ")&&t.push("Tool name contains spaces, which may cause parsing issues"),e.includes(",")&&t.push("Tool name contains commas, which may cause parsing issues"),(e.startsWith("-")||e.endsWith("-"))&&t.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(e.startsWith(".")||e.endsWith("."))&&t.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!aD.test(e)){let r=e.split("").filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,r)=>r.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${r.map(e=>`"${e}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}(e);var r=t.warnings;if(r.length>0){for(let t of(console.warn(`Tool name validation warning for "${e}":`),r))console.warn(` - ${t}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}return t.isValid}class aO{constructor(e){this._mcpServer=e}registerToolTask(e,t,r){let i={taskSupport:"required",...t.execution};if("forbidden"===i.taskSupport)throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,i,t._meta,r)}}class aP{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new aC(e,t)}get experimental(){return this._experimental||(this._experimental={tasks:new aO(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(aq(E.ListToolsRequestSchema)),this.server.assertCanSetRequestHandler(aq(E.CallToolRequestSchema)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(E.ListToolsRequestSchema,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let r,i={name:e,title:t.title,description:t.description,inputSchema:(r=(0,k.normalizeObjectSchema)(t.inputSchema))?er(r,{strictUnions:!0,pipeStrategy:"input"}):aL,annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=(0,k.normalizeObjectSchema)(t.outputSchema);e&&(i.outputSchema=er(e,{strictUnions:!0,pipeStrategy:"output"}))}return i})})),this.server.setRequestHandler(E.CallToolRequestSchema,async(e,t)=>{try{let r=this._registeredTools[e.params.name];if(!r)throw new E.McpError(E.ErrorCode.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new E.McpError(E.ErrorCode.InvalidParams,`Tool ${e.params.name} disabled`);let i=!!e.params.task,a=r.execution?.taskSupport,n="createTask"in r.handler;if(("required"===a||"optional"===a)&&!n)throw new E.McpError(E.ErrorCode.InternalError,`Tool ${e.params.name} has taskSupport '${a}' but was not registered with registerToolTask`);if("required"===a&&!i)throw new E.McpError(E.ErrorCode.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if("optional"===a&&!i&&n)return await this.handleAutomaticTaskPolling(r,e,t);let s=await this.validateToolInput(r,e.params.arguments,e.params.name),o=await this.executeToolHandler(r,s,t);if(i)return o;return await this.validateToolOutput(r,o,e.params.name),o}catch(e){if(e instanceof E.McpError&&e.code===E.ErrorCode.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,t,r){if(!e.inputSchema)return;let i=(0,k.normalizeObjectSchema)(e.inputSchema)??e.inputSchema,a=await (0,k.safeParseAsync)(i,t);if(!a.success){let e="error"in a?a.error:"Unknown error",t=(0,k.getParseErrorMessage)(e);throw new E.McpError(E.ErrorCode.InvalidParams,`Input validation error: Invalid arguments for tool ${r}: ${t}`)}return a.data}async validateToolOutput(e,t,r){if(!e.outputSchema||!("content"in t)||t.isError)return;if(!t.structuredContent)throw new E.McpError(E.ErrorCode.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);let i=(0,k.normalizeObjectSchema)(e.outputSchema),a=await (0,k.safeParseAsync)(i,t.structuredContent);if(!a.success){let e="error"in a?a.error:"Unknown error",t=(0,k.getParseErrorMessage)(e);throw new E.McpError(E.ErrorCode.InvalidParams,`Output validation error: Invalid structured content for tool ${r}: ${t}`)}}async executeToolHandler(e,t,r){let i=e.handler;if("createTask"in i){if(!r.taskStore)throw Error("No task store provided.");let a={...r,taskStore:r.taskStore};return e.inputSchema?await Promise.resolve(i.createTask(t,a)):await Promise.resolve(i.createTask(a))}return e.inputSchema?await Promise.resolve(i(t,r)):await Promise.resolve(i(r))}async handleAutomaticTaskPolling(e,t,r){if(!r.taskStore)throw Error("No task store provided for task-capable tool.");let i=await this.validateToolInput(e,t.params.arguments,t.params.name),a=e.handler,n={...r,taskStore:r.taskStore},s=i?await Promise.resolve(a.createTask(i,n)):await Promise.resolve(a.createTask(n)),o=s.task.taskId,l=s.task,c=l.pollInterval??5e3;for(;"completed"!==l.status&&"failed"!==l.status&&"cancelled"!==l.status;){await new Promise(e=>setTimeout(e,c));let e=await r.taskStore.getTask(o);if(!e)throw new E.McpError(E.ErrorCode.InternalError,`Task ${o} not found during polling`);l=e}return await r.taskStore.getTaskResult(o)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(aq(E.CompleteRequestSchema)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(E.CompleteRequestSchema,async e=>{switch(e.params.ref.type){case"ref/prompt":return(0,E.assertCompleteRequestPrompt)(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return(0,E.assertCompleteRequestResourceTemplate)(e),this.handleResourceCompletion(e,e.params.ref);default:throw new E.McpError(E.ErrorCode.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,t){let r,i=this._registeredPrompts[t.name];if(!i)throw new E.McpError(E.ErrorCode.InvalidParams,`Prompt ${t.name} not found`);if(!i.enabled)throw new E.McpError(E.ErrorCode.InvalidParams,`Prompt ${t.name} disabled`);if(!i.argsSchema)return aF;let a=(0,k.getObjectShape)(i.argsSchema),n=a?.[e.params.argument.name];if(!aT(n))return aF;let s=(r=n[aR],r?.complete);return s?a$(await s(e.params.argument.value,e.params.context)):aF}async handleResourceCompletion(e,t){let r=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!r){if(this._registeredResources[t.uri])return aF;throw new E.McpError(E.ErrorCode.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let i=r.resourceTemplate.completeCallback(e.params.argument.name);return i?a$(await i(e.params.argument.value,e.params.context)):aF}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(aq(E.ListResourcesRequestSchema)),this.server.assertCanSetRequestHandler(aq(E.ListResourceTemplatesRequestSchema)),this.server.assertCanSetRequestHandler(aq(E.ReadResourceRequestSchema)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(E.ListResourcesRequestSchema,async(e,t)=>{let r=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),i=[];for(let e of Object.values(this._registeredResourceTemplates))if(e.resourceTemplate.listCallback)for(let r of(await e.resourceTemplate.listCallback(t)).resources)i.push({...e.metadata,...r});return{resources:[...r,...i]}}),this.server.setRequestHandler(E.ListResourceTemplatesRequestSchema,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(E.ReadResourceRequestSchema,async(e,t)=>{let r=new URL(e.params.uri),i=this._registeredResources[r.toString()];if(i){if(!i.enabled)throw new E.McpError(E.ErrorCode.InvalidParams,`Resource ${r} disabled`);return i.readCallback(r,t)}for(let e of Object.values(this._registeredResourceTemplates)){let i=e.resourceTemplate.uriTemplate.match(r.toString());if(i)return e.readCallback(r,i,t)}throw new E.McpError(E.ErrorCode.InvalidParams,`Resource ${r} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(aq(E.ListPromptsRequestSchema)),this.server.assertCanSetRequestHandler(aq(E.GetPromptRequestSchema)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(E.ListPromptsRequestSchema,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>{var r;let i;return{name:e,title:t.title,description:t.description,arguments:t.argsSchema?(r=t.argsSchema,(i=(0,k.getObjectShape)(r))?Object.entries(i).map(([e,t])=>({name:e,description:(0,k.getSchemaDescription)(t),required:!(0,k.isSchemaOptional)(t)})):[]):void 0}})})),this.server.setRequestHandler(E.GetPromptRequestSchema,async(e,t)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new E.McpError(E.ErrorCode.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new E.McpError(E.ErrorCode.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let i=(0,k.normalizeObjectSchema)(r.argsSchema),a=await (0,k.safeParseAsync)(i,e.params.arguments);if(!a.success){let t="error"in a?a.error:"Unknown error",r=(0,k.getParseErrorMessage)(t);throw new E.McpError(E.ErrorCode.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${r}`)}let n=a.data,s=r.callback;return await Promise.resolve(s(n,t))}{let e=r.callback;return await Promise.resolve(e(t))}}),this._promptHandlersInitialized=!0)}resource(e,t,...r){let i;"object"==typeof r[0]&&(i=r.shift());let a=r[0];if("string"==typeof t){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let r=this._createRegisteredResource(e,void 0,t,i,a);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),r}{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let r=this._createRegisteredResourceTemplate(e,void 0,t,i,a);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),r}}registerResource(e,t,r,i){if("string"==typeof t){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let a=this._createRegisteredResource(e,r.title,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let a=this._createRegisteredResourceTemplate(e,r.title,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}}_createRegisteredResource(e,t,r,i,a){let n={name:e,title:t,metadata:i,readCallback:a,enabled:!0,disable:()=>n.update({enabled:!1}),enable:()=>n.update({enabled:!0}),remove:()=>n.update({uri:null}),update:e=>{void 0!==e.uri&&e.uri!==r&&(delete this._registeredResources[r],e.uri&&(this._registeredResources[e.uri]=n)),void 0!==e.name&&(n.name=e.name),void 0!==e.title&&(n.title=e.title),void 0!==e.metadata&&(n.metadata=e.metadata),void 0!==e.callback&&(n.readCallback=e.callback),void 0!==e.enabled&&(n.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[r]=n,n}_createRegisteredResourceTemplate(e,t,r,i,a){let n={resourceTemplate:r,title:t,metadata:i,readCallback:a,enabled:!0,disable:()=>n.update({enabled:!1}),enable:()=>n.update({enabled:!0}),remove:()=>n.update({name:null}),update:t=>{void 0!==t.name&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=n)),void 0!==t.title&&(n.title=t.title),void 0!==t.template&&(n.resourceTemplate=t.template),void 0!==t.metadata&&(n.metadata=t.metadata),void 0!==t.callback&&(n.readCallback=t.callback),void 0!==t.enabled&&(n.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=n;let s=r.uriTemplate.variableNames;return Array.isArray(s)&&s.some(e=>!!r.completeCallback(e))&&this.setCompletionRequestHandler(),n}_createRegisteredPrompt(e,t,r,i,a){let n={title:t,description:r,argsSchema:void 0===i?void 0:(0,k.objectFromShape)(i),callback:a,enabled:!0,disable:()=>n.update({enabled:!1}),enable:()=>n.update({enabled:!0}),remove:()=>n.update({name:null}),update:t=>{void 0!==t.name&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=n)),void 0!==t.title&&(n.title=t.title),void 0!==t.description&&(n.description=t.description),void 0!==t.argsSchema&&(n.argsSchema=(0,k.objectFromShape)(t.argsSchema)),void 0!==t.callback&&(n.callback=t.callback),void 0!==t.enabled&&(n.enabled=t.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=n,i&&Object.values(i).some(e=>aT(e instanceof e6.ZodOptional?e._def?.innerType:e))&&this.setCompletionRequestHandler(),n}_createRegisteredTool(e,t,r,i,a,n,s,o,l){aN(e);let c={title:t,description:r,inputSchema:aM(i),outputSchema:aM(a),annotations:n,execution:s,_meta:o,handler:l,enabled:!0,disable:()=>c.update({enabled:!1}),enable:()=>c.update({enabled:!0}),remove:()=>c.update({name:null}),update:t=>{void 0!==t.name&&t.name!==e&&("string"==typeof t.name&&aN(t.name),delete this._registeredTools[e],t.name&&(this._registeredTools[t.name]=c)),void 0!==t.title&&(c.title=t.title),void 0!==t.description&&(c.description=t.description),void 0!==t.paramsSchema&&(c.inputSchema=(0,k.objectFromShape)(t.paramsSchema)),void 0!==t.outputSchema&&(c.outputSchema=(0,k.objectFromShape)(t.outputSchema)),void 0!==t.callback&&(c.handler=t.callback),void 0!==t.annotations&&(c.annotations=t.annotations),void 0!==t._meta&&(c._meta=t._meta),void 0!==t.enabled&&(c.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=c,this.setToolRequestHandlers(),this.sendToolListChanged(),c}tool(e,...t){let r,i,a,n;if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);if("string"==typeof t[0]&&(r=t.shift()),t.length>1){let r=t[0];if(aj(r))i=t.shift(),t.length>1&&"object"==typeof t[0]&&null!==t[0]&&!aj(t[0])&&(n=t.shift());else if("object"==typeof r&&null!==r){if(Object.values(r).some(e=>"object"==typeof e&&null!==e))throw Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);n=t.shift()}}let s=t[0];return this._createRegisteredTool(e,void 0,r,i,a,n,{taskSupport:"forbidden"},void 0,s)}registerTool(e,t,r){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:i,description:a,inputSchema:n,outputSchema:s,annotations:o,_meta:l}=t;return this._createRegisteredTool(e,i,a,n,s,o,{taskSupport:"forbidden"},l,r)}prompt(e,...t){let r,i;if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);"string"==typeof t[0]&&(r=t.shift()),t.length>1&&(i=t.shift());let a=t[0],n=this._createRegisteredPrompt(e,void 0,r,i,a);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),n}registerPrompt(e,t,r){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:i,description:a,argsSchema:n}=t,s=this._createRegisteredPrompt(e,i,a,n,r);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}isConnected(){return void 0!==this.server.transport}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}}let aL={type:"object",properties:{}};function aB(e){return null!==e&&"object"==typeof e&&"parse"in e&&"function"==typeof e.parse&&"safeParse"in e&&"function"==typeof e.safeParse}function aU(e){return"_def"in e||"_zod"in e||aB(e)}function aj(e){return!("object"!=typeof e||null===e||aU(e))&&(0===Object.keys(e).length||Object.values(e).some(aB))}function aM(e){if(e){if(aj(e))return(0,k.objectFromShape)(e);if(!aU(e))throw Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return e}}function aq(e){let t=(0,k.getObjectShape)(e),r=t?.method;if(!r)throw Error("Schema is missing a method literal");let i=(0,k.getLiteralValue)(r);if("string"==typeof i)return i;throw Error("Schema method literal must be a string")}function a$(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}let aF={completion:{values:[],hasMore:!1}};e.s(["createBuiltInMcpServer",0,function(e,t=(t,r)=>e.callByName(t,r),r){let i=new aP({name:"ai-development-environment",version:"0.1.0"}),a=i.registerTool.bind(i);for(let i of e.definitions())(!r||r.has(i.name))&&a(i.name,{title:i.title,description:i.description,inputSchema:i.inputSchema,outputSchema:i.outputSchema,annotations:i.annotations},async e=>t(i.name,e));return i}],700909),e.s([],719961);let aG="server:worktree-automations",aK=new Set(["SUCCEEDED","FAILED","CANCELLED","TIMED_OUT"]),aH=new Set(["SUCCEEDED","FAILED","CANCELLED"]);function aV(e){let[t,r,i]=e.split("/");if(!t||!r||i)throw Error("A GitHub repository must be in owner/name format");return{owner:t,name:r}}function aW(e){return{worktreeId:e.worktreeId,state:e.state,conflictWorkflowId:e.conflictWorkflowId,conflictWorkflowChoice:e.conflictWorkflowChoice,lastError:e.lastError,pauseReason:e.pauseReason,lastSyncedAt:e.lastSyncedAt?.toISOString()??null,updatedAt:e.updatedAt.toISOString()}}function aJ(e){return{...e,mergeMethod:e.mergeMethod,updatedAt:e.updatedAt.toISOString()}}class az{worktrees;github;jira;workflows;agentControl;polling;timer;running;rerunRequested;constructor(e,t,r,i,a,n){this.worktrees=e,this.github=t,this.jira=r,this.workflows=i,this.agentControl=a,this.polling=n,this.timer=null,this.running=!1,this.rerunRequested=!1,this.agentControl.registerCompletionObserver(async e=>{e.kind===i0.WORKTREE_AUTO_SYNC_JOB_KIND&&this.changed()}),this.polling?.register({id:aG,kind:"WORKTREE_AUTOMATION",runtime:"SERVER",enabled:!0,cadenceSeconds:60,details:{}})}startRuntime(){queueMicrotask(()=>void this.reconcile())}schedule(){this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>void this.reconcile(),6e4),this.timer.unref(),this.polling?.schedule(aG,new Date(Date.now()+6e4))}changed(){if(this.running){this.rerunRequested=!0;return}this.timer&&clearTimeout(this.timer),this.timer=null,queueMicrotask(()=>void this.reconcile())}async stopAutoSyncWork(e){e?.activeJobId&&await this.agentControl.cancelJob(e.activeJobId).catch(()=>null),e?.workflowRunId&&await this.workflows.lifecycle(e.workflowRunId,"CANCEL").catch(()=>null)}async autoSync(e){let t=await (0,t1.getPrismaClient)(),r=await t.worktreeAutoSync.findUnique({where:{worktreeId:e}});return r?aW(r):null}async configureAutoSync(e){let t=await (0,t1.getPrismaClient)(),r=await t.worktree.findFirst({where:{id:e.worktreeId,missingAt:null},select:{id:!0,branch:!0,codebaseId:!0,codebase:{select:{repositoryId:!0}}}});if(!r?.branch)throw Error("Auto Sync requires a branch");await this.stopAutoSyncWork(await t.worktreeAutoSync.findUnique({where:{worktreeId:r.id},select:{activeJobId:!0,workflowRunId:!0}}));let i=e.conflictWorkflowId?.trim()||null;if(i){let e=await t.workflow.findUnique({where:{id:i},select:{enabled:!0,archivedAt:!0,activeVersionId:!0,quickActionKind:!0,quickActionRepositories:{select:{repositoryId:!0}}}});if(!e?.enabled||e.archivedAt||!e.activeVersionId||"MERGE_CONFLICT"!==e.quickActionKind)throw Error("Select an enabled merge-conflict quick action workflow");if(e.quickActionRepositories.length>0&&!e.quickActionRepositories.some(({repositoryId:e})=>e===r.codebase.repositoryId))throw Error("The merge-conflict workflow is not available for this repository")}let a=await t.worktreeAutoSync.upsert({where:{worktreeId:r.id},create:{worktreeId:r.id,branch:r.branch,conflictWorkflowId:i,conflictWorkflowChoice:e.conflictWorkflowChoice?.trim()||null},update:{state:"ACTIVE",branch:r.branch,conflictWorkflowId:i,conflictWorkflowChoice:e.conflictWorkflowChoice?.trim()||null,activeJobId:null,workflowRunId:null,lastError:null,pauseReason:null}});return this.worktrees.publishAutomationChange(r.id,r.codebaseId),this.changed(),aW(a)}async cancelAutoSync(e){let t=await (0,t1.getPrismaClient)(),r=await t.worktreeAutoSync.findUnique({where:{worktreeId:e},select:{activeJobId:!0,workflowRunId:!0}});await this.stopAutoSyncWork(r);let i=await t.worktreeAutoSync.deleteMany({where:{worktreeId:e}});return this.worktrees.publishAutomationChange(e),i.count>0}async retryAutoSync(e){let t=await (0,t1.getPrismaClient)(),r=await t.worktreeAutoSync.update({where:{worktreeId:e},data:{state:"ACTIVE",activeJobId:null,workflowRunId:null,lastError:null,pauseReason:null}});return this.worktrees.publishAutomationChange(e),this.changed(),aW(r)}async autoMerge(e){let t=await (0,t1.getPrismaClient)(),r=await t.worktreeAutoMerge.findUnique({where:{worktreeId:e}});return r?aJ(r):null}async configureAutoMerge(e){let t=await (0,t1.getPrismaClient)(),r=await t.worktree.findFirst({where:{id:e.worktreeId,missingAt:null},select:{id:!0,primary:!0,branch:!0,codebaseId:!0,codebase:{select:{repository:{select:{canonicalOrigin:!0}}}}}});if(!r?.branch)throw Error("Auto Merge requires a branch");if(e.deleteWorktree&&r.primary)throw Error("The primary worktree cannot be deleted after merge");let i=await t.worktreeAutoMerge.findUnique({where:{worktreeId:r.id}}),a=await this.worktrees.ticketKeyForWorktree(r.id);if(e.moveTicketToDone){if(!a)throw Error("This worktree is not linked to a Jira ticket");let e=await t.jiraProject.findUnique({where:{key:a.split("-")[0]??""},select:{doneStatusId:!0}});if(!e?.doneStatusId)throw Error("Configure this Jira project's done status before enabling this option")}let n=aV(e.repositoryNameWithOwner),s=await this.github.pullRequestAutomationState(n.owner,n.name,e.pullRequestNumber);if(s.headRefName!==r.branch)throw Error("The pull request does not belong to this worktree branch");if(!s.headRepositoryNameWithOwner)throw Error("The pull request head repository is unavailable");if(r.codebase.repository.canonicalOrigin.toLowerCase()!==`github.com/${s.headRepositoryNameWithOwner.toLowerCase()}`)throw Error("The pull request head repository does not match this worktree");let o=!!(i&&(i.repositoryNameWithOwner.toLowerCase()!==e.repositoryNameWithOwner.toLowerCase()||i.pullRequestNumber!==e.pullRequestNumber)),l=!1,c=!1;try{if(i&&o){let e=aV(i.repositoryNameWithOwner),t=await this.github.pullRequestAutomationState(e.owner,e.name,i.pullRequestNumber);"OPEN"===t.state&&t.autoMergeEnabled&&(await this.github.disablePullRequestAutoMerge({...e,number:i.pullRequestNumber},"WORKTREE_AUTOMATION"),l=!0)}c=!0,await this.github.enablePullRequestAutoMerge({...n,number:e.pullRequestNumber,method:e.method,commitHeadline:e.commitHeadline,commitBody:e.commitBody,authorEmail:e.authorEmail},"WORKTREE_AUTOMATION");let s=await t.worktreeAutoMerge.upsert({where:{worktreeId:r.id},create:{worktreeId:r.id,repositoryNameWithOwner:e.repositoryNameWithOwner,pullRequestNumber:e.pullRequestNumber,branch:r.branch,mergeMethod:e.method,commitHeadline:e.commitHeadline.trim(),commitBody:e.commitBody,authorEmail:e.authorEmail?.trim()||null,deleteWorktree:e.deleteWorktree,moveTicketToDone:e.moveTicketToDone,ticketKey:a},update:{state:"ACTIVE",repositoryNameWithOwner:e.repositoryNameWithOwner,pullRequestNumber:e.pullRequestNumber,branch:r.branch,mergeMethod:e.method,commitHeadline:e.commitHeadline.trim(),commitBody:e.commitBody,authorEmail:e.authorEmail?.trim()||null,deleteWorktree:e.deleteWorktree,moveTicketToDone:e.moveTicketToDone,ticketKey:a,ticketMovedAt:null,deleteJobId:null,lastError:null}});return this.worktrees.publishAutomationChange(r.id,r.codebaseId),this.changed(),aJ(s)}catch(t){if(c&&await this.github.disablePullRequestAutoMerge({...n,number:e.pullRequestNumber},"WORKTREE_AUTOMATION").catch(()=>null),i&&(l||!o)){let e=aV(i.repositoryNameWithOwner);await this.github.enablePullRequestAutoMerge({...e,number:i.pullRequestNumber,method:i.mergeMethod,commitHeadline:i.commitHeadline,commitBody:i.commitBody,authorEmail:i.authorEmail},"WORKTREE_AUTOMATION").catch(()=>null)}throw t}}async forceAutoSync(e,t){if(!t.trim())throw Error("requestId is required");let r=await (0,t1.getPrismaClient)(),i=await r.worktreeAutoSync.findUnique({where:{worktreeId:e}});if(!i||"PAUSED"!==i.state||"PREPARATION_CONFLICT"!==i.pauseReason)throw Error("Auto Sync is not paused for a preparation conflict");let a=await this.worktrees.createAutoSyncJob(e,"SYNC",i.branch,t,!0);return await r.worktreeAutoSync.update({where:{worktreeId:e},data:{state:"SYNCING",activeJobId:a.id,workflowRunId:null,lastError:null,pauseReason:null}}),this.worktrees.publishAutomationChange(e),this.changed(),a}async cancelAutoMerge(e){let t=await (0,t1.getPrismaClient)(),r=await t.worktreeAutoMerge.findUnique({where:{worktreeId:e}});if(!r)return!1;let i=aV(r.repositoryNameWithOwner),a=await this.github.pullRequestAutomationState(i.owner,i.name,r.pullRequestNumber);return"OPEN"===a.state&&a.autoMergeEnabled&&await this.github.disablePullRequestAutoMerge({...i,number:r.pullRequestNumber},"WORKTREE_AUTOMATION"),await t.worktreeAutoMerge.delete({where:{worktreeId:e}}),this.worktrees.publishAutomationChange(e),!0}async retryAutoMerge(e){let t=await (0,t1.getPrismaClient)(),r=await t.worktreeAutoMerge.findUniqueOrThrow({where:{worktreeId:e}}),i=aV(r.repositoryNameWithOwner),a="MERGED"===(await this.github.pullRequestAutomationState(i.owner,i.name,r.pullRequestNumber)).state?"POST_MERGE":"ACTIVE",n=await t.worktreeAutoMerge.update({where:{worktreeId:e},data:{state:a,lastError:null,deleteJobId:null}});return this.worktrees.publishAutomationChange(e),this.changed(),aJ(n)}async reconcile(){if(this.running){this.rerunRequested=!0;return}this.running=!0;try{let e=async()=>{do this.rerunRequested=!1,await this.reconcileAutoSync(),await this.reconcileAutoMerge();while(this.rerunRequested)};this.polling?await this.polling.run(aG,e):await e()}catch{}finally{this.running=!1,this.schedule()}}async reconcileAutoSync(){let e=await (0,t1.getPrismaClient)();for(let t of(await e.worktreeAutoSync.findMany({where:{state:{in:["ACTIVE","SYNCING","RESOLVING"]}},include:{worktree:{select:{codebaseId:!0}}}})))try{let r=await e.worktree.findUnique({where:{id:t.worktreeId},select:{branch:!0}});if(r?.branch!==t.branch)throw Error("Auto Sync paused because the worktree branch changed");if("ACTIVE"===t.state){let r=await this.worktrees.createAutoSyncJob(t.worktreeId,"SYNC",t.branch,(0,b.randomUUID)());await e.worktreeAutoSync.update({where:{worktreeId:t.worktreeId},data:{state:"SYNCING",activeJobId:r.id,lastError:null,pauseReason:null}});continue}if("RESOLVING"===t.state){if(!t.workflowRunId)throw Error("The conflict workflow run is missing");let r=await this.workflows.run(t.workflowRunId);if(!r||!aH.has(r.status))continue;if("SUCCEEDED"!==r.status)throw Error(`The conflict workflow ${r.status.toLowerCase()}`);let i=await this.worktrees.createAutoSyncJob(t.worktreeId,"FINALIZE",t.branch,(0,b.randomUUID)());await e.worktreeAutoSync.update({where:{worktreeId:t.worktreeId},data:{state:"SYNCING",activeJobId:i.id,workflowRunId:null,pauseReason:null}});continue}if(!t.activeJobId)throw Error("The Auto Sync job is missing");let i=await this.agentControl.getJob(t.activeJobId);if(!i||!aK.has(i.status))continue;if("SUCCEEDED"!==i.status)throw Error(i.error||`Auto Sync ${i.status.toLowerCase()}`);let a=function(e){if(!e)return null;try{let t=JSON.parse(e);if(!t||"object"!=typeof t||Array.isArray(t))return null;return"string"==typeof t.outcome?String(t.outcome):null}catch{return null}}(i.resultJson);if("PREPARATION_CONFLICT"===a){let r=function(e){if(!e)return[];try{let t=JSON.parse(e);if(!t||"object"!=typeof t||Array.isArray(t))return[];let r=t.preparationConflictPaths;return Array.isArray(r)?r.filter(e=>"string"==typeof e):[]}catch{return[]}}(i.resultJson);await e.worktreeAutoSync.update({where:{worktreeId:t.worktreeId},data:{state:"PAUSED",activeJobId:null,workflowRunId:null,lastError:"Auto Sync paused because repository preparations block the rebase"+(r.length?`: ${r.join(", ")}`:""),pauseReason:"PREPARATION_CONFLICT"}});continue}if("CONFLICT"===a){if(!t.conflictWorkflowId){await e.worktreeAutoSync.update({where:{worktreeId:t.worktreeId},data:{state:"PAUSED",activeJobId:null,workflowRunId:null,lastError:"Auto Sync paused because the rebase has merge conflicts",pauseReason:"REBASE_CONFLICT"}});continue}let r=await this.workflows.trigger({workflowId:t.conflictWorkflowId,resourceKind:"WORKTREE",resourceId:t.worktreeId,subjectKey:`auto-sync:${t.worktreeId}:${i.id}`,choice:t.conflictWorkflowChoice});if(!r)throw Error("The conflict workflow did not start");await e.worktreeAutoSync.update({where:{worktreeId:t.worktreeId},data:{state:"RESOLVING",activeJobId:null,workflowRunId:r.id,lastError:null,pauseReason:null}});continue}if("UNRESOLVED"===a)throw Error("The conflict workflow did not fully resolve the rebase");if("SYNCED"!==a&&"NO_CHANGE"!==a)throw Error("The Auto Sync job returned an unknown result");await e.worktreeAutoSync.update({where:{worktreeId:t.worktreeId},data:{state:"ACTIVE",activeJobId:null,workflowRunId:null,lastError:null,pauseReason:null,..."SYNCED"===a?{lastSyncedAt:new Date}:{}}})}catch(n){let r=n instanceof Error?n.message:String(n),i=/offline|busy|already has an active job|temporarily/i.test(r),a=/branch changed/i.test(r)?"BRANCH_CHANGED":"ERROR";await e.worktreeAutoSync.updateMany({where:{worktreeId:t.worktreeId},data:{state:i?"ACTIVE":"PAUSED",activeJobId:null,workflowRunId:null,lastError:r,pauseReason:i?null:a}})}finally{this.worktrees.publishAutomationChange(t.worktreeId,t.worktree.codebaseId)}}async reconcileAutoMerge(){let e=await (0,t1.getPrismaClient)();for(let t of(await e.worktreeAutoMerge.findMany({where:{state:{in:["ACTIVE","POST_MERGE"]}},include:{worktree:{select:{codebaseId:!0,branch:!0,headSha:!0,primary:!0}}}})))try{let r=aV(t.repositoryNameWithOwner);if("ACTIVE"===t.state){let i=await this.github.pullRequestAutomationState(r.owner,r.name,t.pullRequestNumber);if("MERGED"===i.state)await e.worktreeAutoMerge.update({where:{worktreeId:t.worktreeId},data:{state:"POST_MERGE",lastError:null}}),this.rerunRequested=!0;else if("OPEN"!==i.state)throw Error("The pull request closed without merging");else if(!i.autoMergeEnabled)throw Error("GitHub Auto Merge is no longer enabled");continue}if(t.moveTicketToDone&&t.ticketKey&&!t.ticketMovedAt&&(await this.jira.transitionTicketToConfiguredDone(t.ticketKey),await e.worktreeAutoMerge.update({where:{worktreeId:t.worktreeId},data:{ticketMovedAt:new Date,lastError:null}})),!t.deleteWorktree){await e.worktreeAutoMerge.update({where:{worktreeId:t.worktreeId},data:{state:"COMPLETED",lastError:null}});continue}if(t.worktree.primary)throw Error("The primary worktree cannot be deleted");if(!t.deleteJobId){let i=await this.github.pullRequestAutomationState(r.owner,r.name,t.pullRequestNumber);if("MERGED"!==i.state)throw Error("The pull request is no longer merged");if(i.headRefName!==t.branch)throw Error("The merged pull request branch does not match the Auto Merge rule");if(t.worktree.branch!==t.branch)throw Error("The worktree branch changed after Auto Merge completed");if(!t.worktree.headSha||t.worktree.headSha!==i.headRefOid)throw Error("The worktree HEAD does not match the merged pull request");let a=await this.worktrees.deleteWorktree({worktreeId:t.worktreeId,deleteRemoteBranch:!1,requireClean:!0,expectedBranch:t.branch,expectedHeadSha:i.headRefOid,requestId:`auto-merge-${(0,b.randomUUID)()}`});await e.worktreeAutoMerge.update({where:{worktreeId:t.worktreeId},data:{deleteJobId:a.id,lastError:null}});continue}let i=await this.agentControl.getJob(t.deleteJobId);if(!i||!aK.has(i.status))continue;if("SUCCEEDED"!==i.status)throw Error(i.error||`Worktree deletion ${i.status.toLowerCase()}`);await e.worktreeAutoMerge.updateMany({where:{worktreeId:t.worktreeId},data:{state:"COMPLETED",lastError:null}})}catch(r){await e.worktreeAutoMerge.updateMany({where:{worktreeId:t.worktreeId},data:{state:"ACTION_REQUIRED",lastError:r instanceof Error?r.message:String(r)}})}finally{this.worktrees.publishAutomationChange(t.worktreeId,t.worktree.codebaseId)}}}var aY=e.i(750227),aZ=e.i(320058);function aQ(e,t){let r=[],i=e.includes("CLAUDE");return i&&r.push("CLAUDE"),(e.includes("CODEX")||!i&&e.length>0||"GLOBAL"===t&&e.includes("GITHUB_COPILOT"))&&r.push("AGENTS"),r}let aX="default",a0=["PREPARING","READY","APPLYING","NEEDS_RESOLUTION"],a1=["SCAN","READ"],a2=[...a1,"APPLY"],a3={files:{orderBy:{path:"asc"}},groups:{include:{group:!0}}},a4={skills:{include:{skill:{include:{files:!0}}}},repositories:{include:{repository:!0}}};function a6(e,t){if(!e)return t;try{return JSON.parse(e)}catch{return t}}function a8(e){return[...e.cursorEnabled?["CURSOR"]:[],...e.githubCopilotEnabled?["GITHUB_COPILOT"]:[],...e.codexEnabled?["CODEX"]:[],...e.claudeEnabled?["CLAUDE"]:[],...e.openCodeEnabled?["OPENCODE"]:[]]}function a5(e,t){return"AGENTS"===t?[".agents","skills"]:"CLAUDE"===t?[".claude","skills"]:"GLOBAL"===e?"CURSOR"===t?[".cursor","skills"]:"GITHUB_COPILOT"===t?[".copilot","skills"]:"CODEX_LEGACY"===t?[".codex","skills"]:[".config","opencode","skills"]:"CURSOR"===t?[".cursor","skills"]:"GITHUB_COPILOT"===t?[".github","skills"]:"CODEX_LEGACY"===t?[".codex","skills"]:[".opencode","skills"]}function a9(e){return/^[A-Za-z]:[\\/]/.test(e)||e.startsWith("\\\\")?aY.win32:aY.posix}function a7(e,...t){return a9(e).join(e,...t)}function ne(e){return a9(e).dirname(e)}class nt{agentControl;constructor(e){this.agentControl=e,this.agentControl.registerCompletionHandler(aZ.SKILL_SCAN_JOB_KIND,e=>this.completeScan(e)),this.agentControl.registerCompletionHandler(aZ.SKILL_READ_JOB_KIND,e=>this.completeRead(e)),this.agentControl.registerCompletionHandler(aZ.SKILL_APPLY_JOB_KIND,e=>this.completeApply(e)),this.agentControl.registerConnectionHandler(async()=>{await this.requestAutoReconcile()})}publish(e){ie.agentEventBus.publish(ie.SKILLS_CHANGED_TOPIC,{id:e??null}),e&&ie.agentEventBus.publish((0,ie.skillSyncRunTopic)(e),{id:e})}subscribe(){return ie.agentEventBus.iterate(ie.SKILLS_CHANGED_TOPIC)}subscribeRun(e){return ie.agentEventBus.iterate((0,ie.skillSyncRunTopic)(e))}async settings(){return(await (0,t1.getPrismaClient)()).skillSettings.upsert({where:{id:aX},create:{id:aX},update:{}})}async overview(e=""){let t=await (0,t1.getPrismaClient)(),r=e.trim().toLocaleLowerCase(),[i,a,n,s,o,l]=await Promise.all([t.skill.findMany({where:{deletedAt:null},include:a3,orderBy:{name:"asc"}}),t.skillGroup.findMany({include:a4,orderBy:{name:"asc"}}),t.skillToolObservation.findMany({include:{agent:!0},orderBy:[{tool:"asc"},{agent:{name:"asc"}}]}),t.skillInstallation.findMany({where:{present:!0},include:{agent:!0,codebase:{include:{repository:!0}},worktree:!0,baseline:!0,skill:!0},orderBy:[{skillName:"asc"},{rootPath:"asc"}]}),this.settings(),t.codebaseRepository.findMany({orderBy:{name:"asc"}})]);return{skills:r?i.filter(e=>[e.name,e.description,...e.groups.map(({group:e})=>e.name)].some(e=>e.toLocaleLowerCase().includes(r))):i,groups:a,observations:n,installations:r?s.filter(e=>[e.skillName,e.description,e.agent.name,e.rootPath,e.codebase?.repository.name??""].some(e=>e.toLocaleLowerCase().includes(r))):s,settings:o,repositories:l}}async getSkill(e){return(await (0,t1.getPrismaClient)()).skill.findFirst({where:{id:e,deletedAt:null},include:a3})}async saveSkill(e){let t,r=(t=e.files.map(e=>({path:e.path,contentsBase64:e.contentsBase64,executable:e.executable})),(0,aZ.parseSkillPackage)({name:e.name,description:e.description,packageHash:(0,aZ.hashSkillFiles)(t),files:t})),i=[...new Set(e.groupIds)].slice(0,100),a=await (0,t1.getPrismaClient)();if(await a.skillGroup.count({where:{id:{in:i}}})!==i.length)throw Error("One or more skill groups were not found");let n=await a.skill.findUnique({where:{name:r.name}});if(n&&n.id!==e.id)throw Error("Skill names must be unique");let s=e.id??(0,b.randomUUID)(),o=e.id?await a.skillGroupSkill.findMany({where:{skillId:s},select:{groupId:!0}}):[];return await a.$transaction(async t=>{await t.skill.upsert({where:{id:s},create:{id:s,name:r.name,description:r.description,syncGlobally:e.syncGlobally,packageHash:r.packageHash},update:{name:r.name,description:r.description,syncGlobally:e.syncGlobally,packageHash:r.packageHash,deletedAt:null}}),await t.skillFile.deleteMany({where:{skillId:s}}),await t.skillFile.createMany({data:r.files.map(e=>{let t=Buffer.from(e.contentsBase64,"base64");return{id:(0,b.randomUUID)(),skillId:s,path:e.path,contents:t,executable:e.executable,contentHash:(0,b.createHash)("sha256").update(t).digest("hex")}})}),await t.skillGroupSkill.deleteMany({where:{skillId:s}}),i.length&&await t.skillGroupSkill.createMany({data:i.map(e=>({groupId:e,skillId:s}))})}),this.publish(),await this.scheduleAutoSync([...i,...o.map(e=>e.groupId)]),await this.getSkill(s)}async deleteSkill(e){let t=await (0,t1.getPrismaClient)(),r=await t.skill.findUnique({where:{id:e},include:{groups:!0}});return!!r&&(await t.skill.update({where:{id:e},data:{deletedAt:new Date}}),this.publish(),await this.scheduleAutoSync(r.groups.map(e=>e.groupId)),!0)}async saveGroup(e){let t=e.name.trim();if(!t||t.length>80)throw Error("Group names must contain 1-80 characters");let r=[...new Set(e.skillIds)].slice(0,500),i=[...new Set(e.repositoryIds)].slice(0,500),a=await (0,t1.getPrismaClient)(),[n,s,o]=await Promise.all([a.skill.count({where:{id:{in:r},deletedAt:null}}),a.codebaseRepository.count({where:{id:{in:i}}}),a.skillGroup.findUnique({where:{name:t}})]);if(n!==r.length)throw Error("One or more skills were not found");if(s!==i.length)throw Error("One or more repositories were not found");if(o&&o.id!==e.id)throw Error("Group names must be unique");let l=e.id??(0,b.randomUUID)();return await a.$transaction(async e=>{await e.skillGroup.upsert({where:{id:l},create:{id:l,name:t},update:{name:t}}),await e.skillGroupSkill.deleteMany({where:{groupId:l}}),await e.codebaseRepositorySkillGroup.deleteMany({where:{groupId:l}}),r.length&&await e.skillGroupSkill.createMany({data:r.map(e=>({groupId:l,skillId:e}))}),i.length&&await e.codebaseRepositorySkillGroup.createMany({data:i.map(e=>({groupId:l,repositoryId:e}))})}),this.publish(),await this.scheduleAutoSync([l]),a.skillGroup.findUniqueOrThrow({where:{id:l},include:a4})}async validateGroupIds(e){let t=[...new Set(e)].slice(0,100),r=await (0,t1.getPrismaClient)();if(await r.skillGroup.count({where:{id:{in:t}}})!==t.length)throw Error("One or more skill groups were not found");return t}async groupsForRepository(e){let t=await (0,t1.getPrismaClient)();return(await t.codebaseRepositorySkillGroup.findMany({where:{repositoryId:e},include:{group:!0},orderBy:{group:{name:"asc"}}})).map(e=>e.group)}async deleteGroup(e){let t=await (0,t1.getPrismaClient)(),r=await t.skillGroup.deleteMany({where:{id:e}});return r.count&&this.publish(),r.count&&(await this.settings()).autoSyncProjectGroups&&await this.prepareSync("GROUP",null,!0),r.count>0}async saveSettings(e){let t=await (0,t1.getPrismaClient)(),r=await t.skillSettings.upsert({where:{id:aX},create:{id:aX,...e},update:e});return this.publish(),r.autoSyncProjectGroups&&await this.prepareSync("GROUP",null,!0),r}async setRepositoryGroups(e,t){let r=await this.validateGroupIds(t),i=await (0,t1.getPrismaClient)();await i.$transaction(async t=>{await t.codebaseRepositorySkillGroup.deleteMany({where:{repositoryId:e}}),r.length&&await t.codebaseRepositorySkillGroup.createMany({data:r.map(t=>({repositoryId:e,groupId:t}))})}),this.publish(),(await this.settings()).autoSyncProjectGroups&&await this.prepareSync("GROUP",null,!0)}async scheduleAutoSync(e){if((await this.settings()).autoSyncProjectGroups&&e.length)for(let t of[...new Set(e)])await this.prepareSync("GROUP",t,!0)}async requestAutoReconcile(){return(await this.settings()).autoSyncProjectGroups?this.prepareSync("GROUP",null,!0):null}async targets(e){let t=await (0,t1.getPrismaClient)(),r=await t.codebase.findMany({where:{agentId:e,availability:"AVAILABLE"},include:{worktrees:{where:{missingAt:null}}}}),i=new Map;for(let e of r)for(let t of(i.set(e.folder,{codebaseId:e.id,worktreeId:null,folder:e.folder}),e.worktrees))i.set(t.folder,{codebaseId:e.id,worktreeId:t.id,folder:t.folder});return[...i.values()]}async prepareSync(e,t,r=!1){let i=await (0,t1.getPrismaClient)();if(t&&!await i.skillGroup.findUnique({where:{id:t}}))throw Error("Skill group not found");if(r){let r=await i.skillSyncRun.findFirst({where:{kind:e,groupId:t??null,status:{in:a0}},orderBy:{createdAt:"desc"}});if(r)return r}let a=await i.skillSyncRun.create({data:{id:(0,b.randomUUID)(),kind:e,groupId:t??null,automatic:r,status:"PREPARING"}}),n=a8(await this.settings()),s=await i.agent.findMany({orderBy:{name:"asc"}});for(let e of s){let t=await i.skillSyncItem.create({data:{id:(0,b.randomUUID)(),runId:a.id,agentId:e.id,direction:"SCAN",status:"PENDING"}});await this.agentControl.createJob({agentId:e.id,kind:aZ.SKILL_SCAN_JOB_KIND,payload:{tools:n,targets:await this.targets(e.id),syncRunId:a.id,syncItemId:t.id},idempotencyKey:`skills:scan:${a.id}:${e.id}`,timeoutSeconds:300,visibility:r?"SYSTEM":"USER"})}return!s.length&&(await i.skillSyncRun.update({where:{id:a.id},data:{status:"READY"}}),r)?this.applyRun(a.id):(this.publish(a.id),this.getRun(a.id))}async getRun(e){return(await (0,t1.getPrismaClient)()).skillSyncRun.findUnique({where:{id:e},include:{group:!0,items:{include:{skill:!0,installation:{include:{agent:!0}},agent:!0},orderBy:{createdAt:"asc"}}}})}completionIds(e){return a6(e.payloadJson,{})}async completeScan(e){let{syncRunId:t,syncItemId:r}=this.completionIds(e);if(!t||!r)return;let i=await (0,t1.getPrismaClient)();if(await i.skillSyncItem.findFirst({where:{id:r,runId:t,direction:"SCAN",status:"PENDING"}})){if("SUCCEEDED"===e.status&&e.resultJson){let t=a6(e.resultJson,{configuredTools:[],installations:[],warnings:[]}),a=new Date;await i.$transaction(async i=>{for(let r of(await i.skillInstallation.updateMany({where:{agentId:e.agentId},data:{present:!1}}),t.configuredTools))aZ.AI_TOOLS.includes(r.tool)&&await i.skillToolObservation.upsert({where:{agentId_tool:{agentId:e.agentId,tool:r.tool}},create:{agentId:e.agentId,tool:r.tool,configured:r.configured,homePath:r.homePath,checkedAt:a},update:{configured:r.configured,homePath:r.homePath,checkedAt:a}});for(let r of t.installations){let t=await i.skill.findUnique({where:{name:r.skillName},select:{id:!0,deletedAt:!0}});await i.skillInstallation.upsert({where:{agentId_rootPath_skillName:{agentId:e.agentId,rootPath:r.rootPath,skillName:r.skillName}},create:{id:(0,b.randomUUID)(),agentId:e.agentId,skillId:t&&!t.deletedAt?t.id:null,codebaseId:r.codebaseId,worktreeId:r.worktreeId,scope:r.scope,rootKind:r.rootKind,rootPath:r.rootPath,skillName:r.skillName,description:r.description,packageHash:r.packageHash,present:!0,fileCount:r.fileCount,totalBytes:r.totalBytes,tracked:r.tracked,consumersJson:JSON.stringify(r.consumers),lastSeenAt:a},update:{skillId:t&&!t.deletedAt?t.id:void 0,codebaseId:r.codebaseId,worktreeId:r.worktreeId,scope:r.scope,rootKind:r.rootKind,description:r.description,packageHash:r.packageHash,present:!0,fileCount:r.fileCount,totalBytes:r.totalBytes,tracked:r.tracked,consumersJson:JSON.stringify(r.consumers),lastSeenAt:a}})}await i.skillSyncItem.updateMany({where:{id:r,status:"PENDING"},data:{status:"COMPLETE",error:t.warnings?.length?t.warnings.join("\n").slice(0,64e3):null}})})}else await i.skillSyncItem.updateMany({where:{id:r,status:"PENDING"},data:{status:"FAILED",error:e.error??"Skill scan failed"}});await i.skillSyncItem.count({where:{runId:t,direction:"SCAN",status:"PENDING"}})||await this.buildPlan(t),this.publish(t)}}async configuredByAgent(){let e=await (0,t1.getPrismaClient)(),t=new Set(a8(await this.settings())),r=await e.skillToolObservation.findMany({where:{configured:!0}}),i=new Map;for(let e of r){if(!t.has(e.tool))continue;let r=i.get(e.agentId)??[];r.push(e.tool),i.set(e.agentId,r)}return i}async desiredLocations(e,t=new Set){let r=await (0,t1.getPrismaClient)(),i=await this.configuredByAgent(),a=await r.skillToolObservation.findMany({where:{configured:!0}}),n=new Map;for(let e of a)n.set(e.agentId,e.homePath);let s=[];if("ALL"===e.kind){let e=await r.skill.findMany({where:{deletedAt:null,syncGlobally:!0},include:a3});for(let[r,a]of i){if(t.has(r))continue;let i=n.get(r);if(i)for(let t of aQ(a,"GLOBAL")){let a=a7(i,...a5("GLOBAL",t));for(let i of e)s.push({skill:i,agentId:r,codebaseId:null,worktreeId:null,scope:"GLOBAL",rootKind:t,folder:null,rootPath:a,targetPath:a7(a,i.name)})}}}for(let a of(await r.skillGroup.findMany({where:"GROUP"===e.kind&&e.groupId?{id:e.groupId}:void 0,include:{skills:{where:{skill:{deletedAt:null}},include:{skill:{include:a3}}},repositories:{include:{repository:{include:{codebases:{where:{availability:"AVAILABLE"},include:{worktrees:{where:{missingAt:null}}}}}}}}}})))for(let e of a.repositories)for(let r of e.repository.codebases){if(t.has(r.agentId))continue;let e=aQ(i.get(r.agentId)??[],"PROJECT");for(let t of[{folder:r.folder,worktreeId:null},...r.worktrees.map(e=>({folder:e.folder,worktreeId:e.id}))])for(let i of e){let e=a7(t.folder,...a5("PROJECT",i));for(let n of a.skills)s.push({skill:n.skill,agentId:r.agentId,codebaseId:r.id,worktreeId:t.worktreeId,scope:"PROJECT",rootKind:i,folder:t.folder,rootPath:e,targetPath:a7(e,n.skill.name)})}}return[...new Map(s.map(e=>[`${e.agentId}\0${e.targetPath}`,e])).values()]}installationWhere(e,t){return{present:!0,...t.size?{agentId:{notIn:[...t]}}:{},..."GROUP"===e.kind?{scope:"PROJECT",...e.groupId?{codebase:{repository:{skillGroups:{some:{groupId:e.groupId}}}}}:{}}:{}}}async buildPlan(e){let t=await (0,t1.getPrismaClient)(),r=await t.skillSyncRun.findUniqueOrThrow({where:{id:e}}),i=new Set((await t.skillSyncItem.findMany({where:{runId:e,direction:"SCAN",status:"SKIPPED"},select:{agentId:!0}})).flatMap(e=>e.agentId?[e.agentId]:[]));await t.skillSyncItem.deleteMany({where:{runId:e,direction:{not:"SCAN"}}});let[a,n,s,o,l]=await Promise.all([t.skill.findMany({where:{deletedAt:null},include:a3}),t.skill.findMany({where:{deletedAt:{not:null}}}),t.skillInstallation.findMany({where:this.installationWhere(r,i),include:{baseline:!0}}),this.desiredLocations(r,i),"GROUP"===r.kind&&r.groupId?this.desiredLocations({...r,groupId:null},i):this.desiredLocations(r,i)]),c=new Map(a.map(e=>[e.name,e])),u=new Map(a.map(e=>[e.id,e])),d=new Map(n.map(e=>[e.name,e])),p=new Map(n.map(e=>[e.id,e])),h=new Map;for(let e of s){let t=h.get(e.skillName)??[];t.push(e.packageHash),h.set(e.skillName,t)}let m=new Set([...h].flatMap(([e,t])=>{var r;return(r=c.get(e)?.packageHash??null,new Set(t.filter(e=>null===r||e!==r)).size>1)?[e]:[]})),f=[];for(let t of o)s.find(e=>e.agentId===t.agentId&&e.rootPath===t.rootPath&&e.skillName===t.skill.name)||f.push({id:(0,b.randomUUID)(),runId:e,skillId:t.skill.id,agentId:t.agentId,direction:"EXPORT",status:"READY",sourceHash:t.skill.packageHash,candidatePackageJson:JSON.stringify({location:t})});for(let r of s){let i=r.baseline?.skillId??r.skillId,a=(i?u.get(i):void 0)??c.get(r.skillName),n=(i?p.get(i):void 0)??d.get(r.skillName),s=!!r.baseline&&!!a&&a.name!==r.skillName,h=o.find(e=>e.agentId===r.agentId&&e.rootPath===r.rootPath&&e.skill.name===r.skillName),y=l.find(e=>e.agentId===r.agentId&&e.rootPath===r.rootPath&&e.skill.name===r.skillName);a&&r.packageHash===a.packageHash&&!r.baseline&&await t.skillSyncBaseline.upsert({where:{installationId:r.id},create:{id:(0,b.randomUUID)(),installationId:r.id,skillId:a.id,packageHash:a.packageHash},update:{skillId:a.id,packageHash:a.packageHash,syncedAt:new Date}});let w="UNCHANGED",v="COMPLETE";if(n&&r.baseline&&!r.tracked)w="DELETE_MANAGED",v="READY";else if(s)w=r.tracked?"CONFLICT":"DELETE_MANAGED",v=r.tracked?"BLOCKED":"READY";else if(y||!r.baseline||r.tracked)if(a)if(r.packageHash!==a.packageHash){var g;v="CONFLICT"===(w=m.has(r.skillName)?"CONFLICT":(g={databaseHash:a.packageHash,targetHash:r.packageHash,baselineHash:r.baseline?.packageHash??null,tracked:r.tracked}).databaseHash===g.targetHash?"UNCHANGED":g.tracked?"CONFLICT":g.baselineHash===g.databaseHash?"IMPORT":g.baselineHash===g.targetHash?"EXPORT":"CONFLICT")?"BLOCKED":"READY"}else!y&&["CURSOR","GITHUB_COPILOT","CODEX_LEGACY","OPENCODE"].includes(r.rootKind)&&l.some(e=>e.agentId===r.agentId&&e.scope===r.scope&&("GLOBAL"===r.scope||e.codebaseId===r.codebaseId&&e.worktreeId===r.worktreeId)&&e.skill.name===r.skillName&&e.skill.packageHash===r.packageHash)&&!r.tracked&&(w="DELETE_REDUNDANT",v="READY");else v="CONFLICT"==(w=m.has(r.skillName)?"CONFLICT":"IMPORT")||"PROJECT"===r.scope?"BLOCKED":"READY";else w="DELETE_MANAGED",v="READY";f.push({id:(0,b.randomUUID)(),runId:e,skillId:a?.id??n?.id??null,installationId:r.id,agentId:r.agentId,direction:w,status:v,sourceHash:a?.packageHash??null,targetHash:r.packageHash,candidatePackageJson:JSON.stringify({location:{scope:r.scope,rootKind:r.rootKind,folder:"PROJECT"===r.scope?h?.folder??null:null,skillName:r.skillName},projectGroupRequired:!a&&"PROJECT"===r.scope})})}f.length&&await t.skillSyncItem.createMany({data:f});let y=await t.skillSyncItem.findMany({where:{runId:e,installationId:{not:null},direction:{in:["IMPORT","CONFLICT"]}},include:{installation:!0}}),w=new Map;for(let e of y){if(!e.agentId||!e.installation)continue;let t=w.get(e.agentId)??[];t.push(e),w.set(e.agentId,t)}let v=a8(await this.settings());for(let[r,i]of w){let a=await t.skillSyncItem.create({data:{id:(0,b.randomUUID)(),runId:e,agentId:r,direction:"READ",status:"PENDING"}}),n=await this.targets(r);await this.agentControl.createJob({agentId:r,kind:aZ.SKILL_READ_JOB_KIND,payload:{tools:v,targets:n,requests:i.map(e=>({scope:e.installation.scope,rootKind:e.installation.rootKind,folder:"PROJECT"===e.installation.scope?n.find(t=>t.codebaseId===e.installation.codebaseId&&t.worktreeId===e.installation.worktreeId)?.folder??null:null,skillName:e.installation.skillName})),syncRunId:e,syncItemId:a.id},idempotencyKey:`skills:read:${e}:${r}`,timeoutSeconds:300})}await this.refreshRunStatus(e)}async completeRead(e){let{syncRunId:t,syncItemId:r}=this.completionIds(e);if(!t||!r)return;let i=await (0,t1.getPrismaClient)();if(await i.skillSyncItem.findFirst({where:{id:r,runId:t,direction:"READ",status:"PENDING"}})){if("SUCCEEDED"===e.status&&e.resultJson){let a=a6(e.resultJson,{packages:[]}),n=await i.skillSyncItem.findMany({where:{runId:t,agentId:e.agentId,installationId:{not:null},direction:{in:["IMPORT","CONFLICT"]}},include:{installation:!0}});for(let e of a.packages){let t=n.find(t=>t.installation?.skillName===e.package.name&&t.installation?.rootKind===e.rootKind&&t.installation?.scope===e.scope&&("GLOBAL"===e.scope||t.installation?.rootPath===a7(e.folder,...a5("PROJECT",e.rootKind))));if(!t)continue;let r=a6(t.candidatePackageJson,{});await i.skillSyncItem.update({where:{id:t.id},data:{candidatePackageJson:JSON.stringify({...r,package:e.package})}})}await i.skillSyncItem.updateMany({where:{id:r,status:"PENDING"},data:{status:"COMPLETE"}})}else await i.skillSyncItem.updateMany({where:{id:r,status:"PENDING"},data:{status:"FAILED",error:e.error??"Skill package read failed"}});await this.refreshRunStatus(t),this.publish(t)}}async refreshRunStatus(e){let t=await (0,t1.getPrismaClient)(),r=await t.skillSyncItem.findMany({where:{runId:e}});if(r.some(e=>a1.includes(e.direction)&&"PENDING"===e.status))return;let i=r.some(e=>"BLOCKED"===e.status),a=r.some(e=>"FAILED"===e.status),n=i?"NEEDS_RESOLUTION":a?"PARTIAL":"READY",s=await t.skillSyncRun.update({where:{id:e},data:{status:n}});this.publish(e),s.automatic&&"READY"===n&&await this.applyRun(e)}async skipPending(e){let t=await (0,t1.getPrismaClient)();await t.skillSyncRun.findUniqueOrThrow({where:{id:e}});let r=await t.skillSyncItem.findMany({where:{runId:e,direction:{in:a2},status:"PENDING",agentId:{not:null}}}),i=[];for(let a of r){if(1!==(await t.skillSyncItem.updateMany({where:{id:a.id,status:"PENDING"},data:{status:"SKIPPED",resolution:"SKIP"}})).count||!a.agentId)continue;i.push(a);let r=await t.agentJob.findUnique({where:{agentId_idempotencyKey:{agentId:a.agentId,idempotencyKey:`skills:${a.direction.toLowerCase()}:${e}:${a.agentId}`}}});r&&await this.agentControl.cancelJob(r.id)}if(!i.length)return this.getRun(e);let a=[...new Set(i.flatMap(e=>"READ"===e.direction&&e.agentId?[e.agentId]:[]))];a.length&&await t.skillSyncItem.updateMany({where:{runId:e,agentId:{in:a},direction:{notIn:a2},status:{in:["READY","BLOCKED"]}},data:{status:"SKIPPED",resolution:"SKIP"}});let n=i.filter(e=>"APPLY"===e.direction),s=n.flatMap(e=>{let{deployments:t=[]}=a6(e.candidatePackageJson,{});return t.map(e=>e.id)});return s.length&&await t.skillDeployment.updateMany({where:{id:{in:s},status:"PENDING"},data:{status:"SKIPPED"}}),i.some(e=>"SCAN"===e.direction)?await t.skillSyncItem.count({where:{runId:e,direction:"SCAN",status:"PENDING"}})||await this.buildPlan(e):a.length&&await this.refreshRunStatus(e),n.length&&(await t.skillSyncItem.count({where:{runId:e,direction:"APPLY",status:"PENDING"}})||await t.skillSyncRun.update({where:{id:e},data:{status:"PARTIAL",finishedAt:new Date}})),this.publish(e),this.getRun(e)}async resolveItem(e){let t=await (0,t1.getPrismaClient)(),r=await t.skillSyncItem.findUniqueOrThrow({where:{id:e.itemId}});if(!["BLOCKED","READY"].includes(r.status))throw Error("Sync item cannot be resolved");let i=a6(r.candidatePackageJson,{});if("MANUAL"===e.resolution&&(i.package=(0,aZ.parseSkillPackage)(e.package,"manual resolution package")),"TARGET"===e.resolution&&!i.package)throw Error("The target package is unavailable");if("DELETE"===e.resolution&&!r.installationId)throw Error("The client skill installation is unavailable");if(i.projectGroupRequired&&["TARGET","MANUAL"].includes(e.resolution)){if(!e.groupId||!await t.skillGroup.findUnique({where:{id:e.groupId}}))throw Error("A project skill import requires a skill group");i.groupId=e.groupId}if(await t.skillSyncItem.update({where:{id:r.id},data:{resolution:e.resolution,direction:"DELETE"===e.resolution?"DELETE_REDUNDANT":r.direction,candidatePackageJson:JSON.stringify(i),status:"SKIP"===e.resolution?"SKIPPED":"READY"}}),["TARGET","MANUAL"].includes(e.resolution)){let e=i.package?.name??null;if(e){let i=(await t.skillSyncItem.findMany({where:{runId:r.runId,id:{not:r.id},direction:"CONFLICT",status:{in:["BLOCKED","READY"]}},include:{skill:!0,installation:!0}})).flatMap(t=>(t.skill?.name??t.installation?.skillName)===e?[t.id]:[]);i.length&&await t.skillSyncItem.updateMany({where:{id:{in:i}},data:{resolution:"DATABASE",status:"READY"}})}}return await this.refreshRunStatus(r.runId),this.getRun(r.runId)}async importCandidates(e){let t=await (0,t1.getPrismaClient)();for(let r of(await t.skillSyncItem.findMany({where:{runId:e,status:"READY",OR:[{direction:"IMPORT"},{direction:"CONFLICT",resolution:{in:["TARGET","MANUAL"]}}]},include:{installation:!0}}))){let e=a6(r.candidatePackageJson,{});if(!e.package)continue;let i=await t.skill.findUnique({where:{name:e.package.name},include:a3}),a=await this.saveSkill({id:i?.id,name:e.package.name,description:e.package.description,syncGlobally:i?.syncGlobally??!e.groupId,groupIds:[...i?.groups.map(e=>e.groupId)??[],...e.groupId?[e.groupId]:[]],files:e.package.files});r.installationId&&(await t.skillInstallation.update({where:{id:r.installationId},data:{skillId:a.id}}),r.targetHash===a.packageHash&&await t.skillSyncBaseline.upsert({where:{installationId:r.installationId},create:{id:(0,b.randomUUID)(),installationId:r.installationId,skillId:a.id,packageHash:a.packageHash},update:{skillId:a.id,packageHash:a.packageHash,syncedAt:new Date}}))}}async applyRun(e){let t=await (0,t1.getPrismaClient)(),r=await t.skillSyncRun.findUniqueOrThrow({where:{id:e}});if(await t.skillSyncItem.count({where:{runId:e,status:"BLOCKED"}}))throw Error("Resolve all conflicts before applying sync");await this.importCandidates(e);let i=new Set((await t.skillSyncItem.findMany({where:{runId:e,direction:{in:a1},status:"SKIPPED"},select:{agentId:!0}})).flatMap(e=>e.agentId?[e.agentId]:[])),a=await this.desiredLocations(r,i),n=await t.skillInstallation.findMany({where:this.installationWhere(r,i)}),s=new Map,o=new Map,l=(e,t)=>{let r=s.get(e)??[];r.push(t),s.set(e,r)},c=(e,t)=>{let r=o.get(e)??[];r.push(t),o.set(e,r)};for(let e of a){let r=n.find(t=>t.agentId===e.agentId&&t.rootPath===e.rootPath&&t.skillName===e.skill.name);if(r?.packageHash===e.skill.packageHash||r?.tracked)continue;l(e.agentId,{kind:"WRITE",scope:e.scope,rootKind:e.rootKind,folder:e.folder,package:function(e){let t=e.files.map(e=>({path:e.path,contentsBase64:Buffer.from(e.contents).toString("base64"),executable:e.executable}));return{name:e.name,description:e.description,packageHash:e.packageHash,files:t}}(e.skill),manageGitExclude:"PROJECT"===e.scope});let i=await t.skillDeployment.upsert({where:{agentId_targetPath:{agentId:e.agentId,targetPath:e.targetPath}},create:{id:(0,b.randomUUID)(),skillId:e.skill.id,agentId:e.agentId,codebaseId:e.codebaseId,worktreeId:e.worktreeId,scope:e.scope,rootKind:e.rootKind,targetPath:e.targetPath,desiredHash:e.skill.packageHash,status:"PENDING"},update:{skillId:e.skill.id,desiredHash:e.skill.packageHash,status:"PENDING",lastError:null}});c(e.agentId,{id:i.id,desiredHash:e.skill.packageHash})}let u=await t.skillSyncItem.findMany({where:{runId:e,direction:{in:["DELETE_REDUNDANT","DELETE_MANAGED"]},status:"READY"},include:{installation:!0}}),d=new Set(u.flatMap(e=>e.installationId?[e.installationId]:[])),p=n.filter(e=>!d.has(e.id)&&!e.tracked&&["CURSOR","GITHUB_COPILOT","CODEX_LEGACY","OPENCODE"].includes(e.rootKind)&&!a.some(t=>t.agentId===e.agentId&&t.rootPath===e.rootPath&&t.skill.name===e.skillName)&&a.some(t=>t.agentId===e.agentId&&t.scope===e.scope&&("GLOBAL"===e.scope||t.codebaseId===e.codebaseId&&t.worktreeId===e.worktreeId)&&t.skill.name===e.skillName&&t.skill.packageHash===e.packageHash));for(let e of[...u.flatMap(e=>e.installation?[e.installation]:[]),...p]){if(!e||e.tracked)continue;let t=await this.targets(e.agentId),r="PROJECT"===e.scope?t.find(t=>t.codebaseId===e.codebaseId&&t.worktreeId===e.worktreeId)?.folder??null:null;("PROJECT"!==e.scope||r)&&l(e.agentId,{kind:"DELETE",scope:e.scope,rootKind:e.rootKind,folder:r,skillName:e.skillName,manageGitExclude:"PROJECT"===e.scope})}for(let[r,i]of s){let a=await t.skillSyncItem.create({data:{id:(0,b.randomUUID)(),runId:e,agentId:r,direction:"APPLY",status:"PENDING",candidatePackageJson:JSON.stringify({deployments:o.get(r)??[]})}});await this.agentControl.createJob({agentId:r,kind:aZ.SKILL_APPLY_JOB_KIND,payload:{operations:i,syncRunId:e,syncItemId:a.id},idempotencyKey:`skills:apply:${e}:${r}`,timeoutSeconds:600})}return await t.skillSyncRun.update({where:{id:e},data:s.size?{status:"APPLYING"}:{status:"SUCCEEDED",finishedAt:new Date}}),this.publish(e),this.getRun(e)}async completeApply(e){let{syncRunId:t,syncItemId:r}=this.completionIds(e);if(!t||!r)return;let i=await (0,t1.getPrismaClient)(),a=await i.skillSyncItem.findFirst({where:{id:r,runId:t,direction:"APPLY",status:"PENDING"}});if(!a)return;let n="SUCCEEDED"===e.status,{deployments:s=[]}=a6(a?.candidatePackageJson??null,{});await i.skillSyncItem.updateMany({where:{id:r,status:"PENDING"},data:{status:n?"COMPLETE":"FAILED",error:n?null:e.error??"Skill apply failed"}});let o=await i.skillDeployment.findMany({where:{id:{in:s.map(e=>e.id)},agentId:e.agentId,status:"PENDING"},include:{skill:{include:{files:!0}}}}),l=a6(e.resultJson,{});if(n){let t=await this.configuredByAgent();for(let e of o){let r=s.find(t=>t.id===e.id),a=l.results?.find(t=>"WRITE"===t.kind&&t.path===e.targetPath);if(!r||e.desiredHash!==r.desiredHash||a?.packageHash!==r.desiredHash)continue;let n=await i.skillInstallation.upsert({where:{agentId_rootPath_skillName:{agentId:e.agentId,rootPath:ne(e.targetPath),skillName:e.skill.name}},create:{id:(0,b.randomUUID)(),skillId:e.skillId,agentId:e.agentId,codebaseId:e.codebaseId,worktreeId:e.worktreeId,scope:e.scope,rootKind:e.rootKind,rootPath:ne(e.targetPath),skillName:e.skill.name,description:e.skill.description,packageHash:e.desiredHash,present:!0,fileCount:e.skill.files.length,totalBytes:e.skill.files.reduce((e,t)=>e+t.contents.byteLength,0),tracked:!1,consumersJson:JSON.stringify(t.get(e.agentId)??[]),lastSeenAt:new Date},update:{skillId:e.skillId,codebaseId:e.codebaseId,worktreeId:e.worktreeId,scope:e.scope,rootKind:e.rootKind,description:e.skill.description,packageHash:e.desiredHash,present:!0,fileCount:e.skill.files.length,totalBytes:e.skill.files.reduce((e,t)=>e+t.contents.byteLength,0),tracked:!1,consumersJson:JSON.stringify(t.get(e.agentId)??[]),lastSeenAt:new Date}});await i.skillSyncBaseline.upsert({where:{installationId:n.id},create:{id:(0,b.randomUUID)(),installationId:n.id,skillId:e.skillId,packageHash:e.desiredHash},update:{skillId:e.skillId,packageHash:e.desiredHash,syncedAt:new Date}}),await i.skillDeployment.update({where:{id:e.id},data:{status:"INSTALLED",installedHash:e.desiredHash,lastError:null}})}for(let t of l.results??[])if("DELETE"===t.kind){var c;await i.skillInstallation.updateMany({where:{agentId:e.agentId,rootPath:ne(t.path),skillName:a9(c=t.path).basename(c)},data:{present:!1,lastSeenAt:new Date}})}}else for(let t of s)await i.skillDeployment.updateMany({where:{id:t.id,agentId:e.agentId,desiredHash:t.desiredHash,status:"PENDING"},data:{status:"FAILED",lastError:e.error??"Skill apply failed"}});if(!await i.skillSyncItem.count({where:{runId:t,direction:"APPLY",status:"PENDING"}})){let e=await i.skillSyncItem.count({where:{runId:t,direction:"APPLY",status:{in:["FAILED","SKIPPED"]}}});await i.skillSyncRun.update({where:{id:t},data:{status:e?"PARTIAL":"SUCCEEDED",finishedAt:new Date}})}this.publish(t)}}e.i(464841);var nr=e.i(220629),ni=e.i(692680);e.i(493015);var na=e.i(49172);function nn(e){if(!e)return{};let t=JSON.parse(e);return t&&"object"==typeof t&&!Array.isArray(t)?t:{}}function ns(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.valueOf())?null:t}function no(e){try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}catch{return[]}}class nl{agentControl;fetcher;credentials;constructor(e,t=fetch,r=new t3.CredentialService){for(const i of(this.agentControl=e,this.fetcher=t,this.credentials=r,this.agentControl.registerCompletionHandler(ni.SIGNING_ASSETS_SCAN_JOB_KIND,e=>this.completeScan(e)),[ni.SIGNING_PROFILE_READ_JOB_KIND,ni.SIGNING_PROFILE_INSTALL_JOB_KIND,ni.SIGNING_PROFILE_DELETE_JOB_KIND,ni.SIGNING_IDENTITY_IMPORT_JOB_KIND,ni.SIGNING_IDENTITY_DELETE_JOB_KIND]))this.agentControl.registerCompletionHandler(i,e=>this.completeOperation(e))}changed(){ie.agentEventBus.publish(ie.SIGNING_ASSETS_CHANGED_TOPIC,{changed:!0})}deleteTransferJobSoon(e){setTimeout(()=>{(0,t1.getPrismaClient)().then(t=>t.agentJob.deleteMany({where:{id:e,visibility:"SYSTEM"}}))},3e4).unref()}subscribe(){return ie.agentEventBus.iterate(ie.SIGNING_ASSETS_CHANGED_TOPIC)}async completeScan(e){if("SUCCEEDED"!==e.status)return;let t=(0,ni.parseSigningAssetsScanResult)(nn(e.resultJson)),r=await (0,t1.getPrismaClient)(),i=new Date;await r.$transaction(async r=>{for(let a of(await r.signingProfileAsset.updateMany({where:{agentId:e.agentId,missingAt:null},data:{missingAt:i}}),await r.signingCertificateAsset.updateMany({where:{agentId:e.agentId,missingAt:null},data:{missingAt:i}}),t.profiles))await r.signingProfileAsset.upsert({where:{agentId_uuid:{agentId:e.agentId,uuid:a.uuid}},create:{id:(0,b.randomUUID)(),agentId:e.agentId,uuid:a.uuid,contentHash:a.contentHash,name:a.name,profileType:a.profileType,bundleId:a.bundleId,teamId:a.teamId,teamName:a.teamName,platformsJson:JSON.stringify(a.platforms),deviceCount:a.deviceCount,deviceUdidsJson:JSON.stringify(a.deviceUdids),certificateSha1sJson:JSON.stringify(a.certificateSha1s),createdAt:ns(a.createdAt),expiresAt:ns(a.expiresAt),expired:a.expired,xcodeManaged:a.xcodeManaged,observedAt:i},update:{contentHash:a.contentHash,name:a.name,profileType:a.profileType,bundleId:a.bundleId,teamId:a.teamId,teamName:a.teamName,platformsJson:JSON.stringify(a.platforms),deviceCount:a.deviceCount,deviceUdidsJson:JSON.stringify(a.deviceUdids),certificateSha1sJson:JSON.stringify(a.certificateSha1s),createdAt:ns(a.createdAt),expiresAt:ns(a.expiresAt),expired:a.expired,xcodeManaged:a.xcodeManaged,observedAt:i,missingAt:null}});for(let a of t.certificates)await r.signingCertificateAsset.upsert({where:{agentId_sha1:{agentId:e.agentId,sha1:a.sha1}},create:{id:(0,b.randomUUID)(),agentId:e.agentId,sha1:a.sha1,sha256:a.sha256,name:a.name,teamId:a.teamId,certificateType:a.certificateType,notBefore:ns(a.notBefore),expiresAt:ns(a.expiresAt),expired:a.expired,hasPrivateKey:a.hasPrivateKey,observedAt:i},update:{sha256:a.sha256,name:a.name,teamId:a.teamId,certificateType:a.certificateType,notBefore:ns(a.notBefore),expiresAt:ns(a.expiresAt),expired:a.expired,hasPrivateKey:a.hasPrivateKey,observedAt:i,missingAt:null}})}),this.deleteTransferJobSoon(e.id),this.changed()}async refreshAfterMutation(e,t){await this.agentControl.createJob({agentId:e,kind:ni.SIGNING_ASSETS_SCAN_JOB_KIND,payload:{},idempotencyKey:`signing:${t}:${e}:refresh`,timeoutSeconds:60,visibility:"SYSTEM"})}async finishOperation(e){let t=await (0,t1.getPrismaClient)(),r=await t.signingOperationItem.findMany({where:{operationId:e}});if(r.some(e=>["WAITING","QUEUED","RUNNING"].includes(e.status)))return;let i=r.filter(e=>"SUCCEEDED"!==e.status);await t.signingOperation.update({where:{id:e},data:{status:i.length?"FAILED":"SUCCEEDED",error:i.map(e=>e.error).filter(Boolean).join("; ")||null,finishedAt:new Date}}),this.changed()}async completeOperation(e){let t=await (0,t1.getPrismaClient)(),r=await t.signingOperationItem.findUnique({where:{jobId:e.id},include:{operation:!0}});if(r){if(await t.signingOperationItem.update({where:{id:r.id},data:{status:e.status,error:e.error,finishedAt:new Date}}),e.kind===ni.SIGNING_PROFILE_READ_JOB_KIND&&"SUCCEEDED"===e.status&&"SYNC_PROFILE"===r.operation.kind){let i=nn(e.resultJson).contentBase64;if("string"==typeof i&&i)for(let e of(await t.signingOperationItem.findMany({where:{operationId:r.operationId,status:"WAITING"}}))){let a=await this.agentControl.createJob({agentId:e.agentId,kind:ni.SIGNING_PROFILE_INSTALL_JOB_KIND,payload:{contentBase64:i},idempotencyKey:`signing:${r.operationId}:${e.agentId}:install`,timeoutSeconds:60,visibility:"SYSTEM"});await t.signingOperationItem.update({where:{id:e.id},data:{jobId:a.id,status:a.status}})}else await t.signingOperation.update({where:{id:r.operationId},data:{status:"FAILED",error:"Profile read returned no content"}})}e.kind===ni.SIGNING_PROFILE_READ_JOB_KIND&&"SUCCEEDED"!==e.status&&"SYNC_PROFILE"===r.operation.kind&&await t.signingOperationItem.updateMany({where:{operationId:r.operationId,status:"WAITING"},data:{status:"FAILED",error:"Source profile could not be read",finishedAt:new Date}}),"SUCCEEDED"===e.status&&e.kind!==ni.SIGNING_PROFILE_READ_JOB_KIND&&await this.refreshAfterMutation(e.agentId,r.operationId),await this.finishOperation(r.operationId),this.deleteTransferJobSoon(e.id)}}async refresh(e){let t=await (0,t1.getPrismaClient)(),r=await t.agent.findMany({where:e?.length?{id:{in:[...new Set(e)]}}:void 0,orderBy:{name:"asc"}}),i=[];for(let e of r)no(e.capabilitiesJson).includes(ni.SIGNING_ASSETS_SCAN_JOB_KIND)&&i.push(await this.agentControl.createJob({agentId:e.id,kind:ni.SIGNING_ASSETS_SCAN_JOB_KIND,payload:{},idempotencyKey:`signing:scan:${Date.now()}:${e.id}`,timeoutSeconds:60,visibility:"SYSTEM"}));return i}async agents(){let e=await (0,t1.getPrismaClient)();return(await e.agent.findMany({orderBy:{name:"asc"}})).map(e=>({id:e.id,name:e.name,hostname:e.hostname,supported:no(e.capabilitiesJson).includes(ni.SIGNING_ASSETS_SCAN_JOB_KIND),lastSeenAt:e.lastSeenAt?.toISOString()??null}))}async profiles(){let e=await (0,t1.getPrismaClient)(),t=await e.signingProfileAsset.findMany({where:{missingAt:null},include:{agent:{select:{id:!0,name:!0}}},orderBy:[{expiresAt:"asc"},{name:"asc"}]}),r=new Map;for(let e of t){let t=`${e.uuid}:${e.contentHash}`;r.set(t,[...r.get(t)??[],e])}return[...r.values()].map(e=>{let t=e[0];return{id:`${t.uuid}:${t.contentHash}`,uuid:t.uuid,contentHash:t.contentHash,name:t.name,profileType:t.profileType,bundleId:t.bundleId,teamId:t.teamId,teamName:t.teamName,platforms:no(t.platformsJson),deviceCount:t.deviceCount,deviceUdids:no(t.deviceUdidsJson),certificateSha1s:no(t.certificateSha1sJson),createdAt:t.createdAt?.toISOString()??null,expiresAt:t.expiresAt?.toISOString()??null,expired:t.expired,xcodeManaged:t.xcodeManaged,installedAgents:e.map(({agent:e})=>e)}})}async profile(e){return(await this.profiles()).find(t=>t.id===e)??null}async profileDevices(e){let t=new Set,r=e.filter(e=>{let r=e.toUpperCase();return!t.has(r)&&(t.add(r),!0)}),i=r.map(e=>e.toUpperCase());if(!i.length)return[];let a=await (0,t1.getPrismaClient)(),n=new Map((await a.iosDevice.findMany({where:{udid:{in:i}},select:{id:!0,udid:!0,displayName:!0,product:!0,osVersion:!0,status:!0}})).map(e=>[e.udid.toUpperCase(),e]));return r.map(e=>{let t=n.get(e.toUpperCase());return{udid:e,deviceId:t?.id??null,displayName:t?.displayName??null,product:t?.product??null,osVersion:t?.osVersion??null,status:t?.status??null}})}async certificates(){let e=await (0,t1.getPrismaClient)(),t=await e.signingCertificateAsset.findMany({where:{missingAt:null},include:{agent:{select:{id:!0,name:!0}}},orderBy:[{expiresAt:"asc"},{name:"asc"}]}),r=new Map;for(let e of t)r.set(e.sha1,[...r.get(e.sha1)??[],e]);return[...r.values()].map(e=>{let t=e[0];return{id:t.sha1,sha1:t.sha1,sha256:t.sha256,name:t.name,teamId:t.teamId,certificateType:t.certificateType,notBefore:t.notBefore?.toISOString()??null,expiresAt:t.expiresAt?.toISOString()??null,expired:t.expired,hasPrivateKey:e.some(e=>e.hasPrivateKey),installedAgents:e.map(({agent:e})=>e),privateKeyAgents:e.filter(e=>e.hasPrivateKey).map(({agent:e})=>e)}})}async operations(e=50){return(await (0,t1.getPrismaClient)()).signingOperation.findMany({include:{items:{include:{agent:{select:{id:!0,name:!0}}},orderBy:{createdAt:"asc"}}},orderBy:{createdAt:"desc"},take:Math.max(1,Math.min(e,200))})}async operation(e,t,r,i=null,a=[]){let n=await (0,t1.getPrismaClient)(),s=(0,b.randomUUID)();return n.signingOperation.create({data:{id:s,kind:e,assetKey:t,sourceAgentId:i,items:{create:[...new Set(r)].map(e=>({id:(0,b.randomUUID)(),agentId:e,status:a.includes(e)?"WAITING":"QUEUED"}))}},include:{items:{include:{agent:{select:{id:!0,name:!0}}}}}})}async attachJob(e,t){let r=await (0,t1.getPrismaClient)();await r.signingOperationItem.update({where:{id:e},data:{jobId:t.id,status:t.status}})}async uploadProfile(e,t){if(!t.length)throw Error("Select at least one agent");let r=(0,b.createHash)("sha256").update(Buffer.from(e,"base64")).digest("hex").toUpperCase(),i=await this.operation("INSTALL_PROFILE",r,t);for(let t of i.items){let r=await this.agentControl.createJob({agentId:t.agentId,kind:ni.SIGNING_PROFILE_INSTALL_JOB_KIND,payload:{contentBase64:e},idempotencyKey:`signing:${i.id}:${t.agentId}:install`,timeoutSeconds:60,visibility:"SYSTEM"});await this.attachJob(t.id,r)}return this.changed(),i}async downloadProfile(e,t){let r=(0,b.randomUUID)(),i=await this.agentControl.createJob({agentId:t,kind:ni.SIGNING_PROFILE_READ_JOB_KIND,payload:{uuid:e},idempotencyKey:`signing:download:${r}:${e}`,timeoutSeconds:60,visibility:"SYSTEM"}),a=await (0,t1.getPrismaClient)();try{let t=Date.now()+55e3;for(;Date.now()<t;){let t=await this.agentControl.getJob(i.id);if(!t)throw Error("Profile download job was removed");if(["FAILED","CANCELLED","TIMED_OUT"].includes(t.status))throw Error(t.error||"Could not read provisioning profile");if("SUCCEEDED"===t.status){let r=nn(t.resultJson);if("string"!=typeof r.contentBase64)throw Error("Agent returned no provisioning profile content");return{uuid:e,filename:`${e}.mobileprovision`,contentBase64:r.contentBase64}}await new Promise(e=>setTimeout(e,250))}throw Error("Timed out reading provisioning profile")}finally{await a.agentJob.deleteMany({where:{id:i.id,visibility:"SYSTEM"}})}}async syncProfile(e,t,r){let i=[...new Set(r)].filter(e=>e!==t);if(!i.length)throw Error("Select at least one target agent");let a=await this.operation("SYNC_PROFILE",e,[t,...i],t,i),n=a.items.find(e=>e.agentId===t),s=await this.agentControl.createJob({agentId:t,kind:ni.SIGNING_PROFILE_READ_JOB_KIND,payload:{uuid:e},idempotencyKey:`signing:${a.id}:${t}:read`,timeoutSeconds:60,visibility:"SYSTEM"});return await this.attachJob(n.id,s),this.changed(),a}async deleteProfile(e,t){if(!t.length)throw Error("Select at least one agent");let r=await this.operation("DELETE_PROFILE",e,t);for(let t of r.items){let i=await this.agentControl.createJob({agentId:t.agentId,kind:ni.SIGNING_PROFILE_DELETE_JOB_KIND,payload:{uuid:e},idempotencyKey:`signing:${r.id}:${t.agentId}:delete`,timeoutSeconds:60,visibility:"SYSTEM"});await this.attachJob(t.id,i)}return this.changed(),r}async deleteExpiredProfiles(e){let t=await (0,t1.getPrismaClient)(),r=await t.signingProfileAsset.findMany({where:{expired:!0,missingAt:null,...e?.length?{agentId:{in:e}}:{}}}),i=new Map;for(let e of r)i.set(e.uuid,[...i.get(e.uuid)??[],e.agentId]);let a=[];for(let[e,t]of i)a.push(await this.deleteProfile(e,t));return a}async importIdentity(e){if(!e.targetAgentIds.length)throw Error("Select at least one agent");let t=Buffer.from(e.p12Base64,"base64");if(!t.length||t.length>0x1400000)throw Error("The .p12 file is empty or larger than 20 MiB");let r=[...new Set(e.targetAgentIds)],i=await (0,t1.getPrismaClient)(),n=new Map((await i.agent.findMany({where:{id:{in:r}},select:{id:!0,name:!0,capabilitiesJson:!0,lastSeenAt:!0,disconnectedAt:!0,heartbeatIntervalSeconds:!0}})).map(e=>[e.id,e])),s=Date.now(),o=r.filter(e=>{let t=n.get(e);return!t||!function(e,t=Date.now()){return null!==e.lastSeenAt&&t-e.lastSeenAt.getTime()<=(0,a.agentOnlineWindowMs)(e)&&null===e.disconnectedAt}(t,s)||!no(t.capabilitiesJson).includes(ni.SIGNING_IDENTITY_IMPORT_JOB_KIND)});if(o.length)throw Error(`Identity imports require online supported agents: ${o.map(e=>n.get(e)?.name??e).join(", ")}`);let l=(0,b.createHash)("sha256").update(t).digest("hex").toUpperCase(),c=await this.operation("IMPORT_IDENTITY",l,r);for(let t of c.items){let r=this.agentControl.createSigningSecretTransfer(t.agentId,{p12Base64:e.p12Base64,passphrase:e.passphrase});try{let e=await this.agentControl.createJob({agentId:t.agentId,kind:ni.SIGNING_IDENTITY_IMPORT_JOB_KIND,payload:{transferId:r,sha256:l},idempotencyKey:`signing:${c.id}:${t.agentId}:import`,timeoutSeconds:120,visibility:"SYSTEM"});await this.attachJob(t.id,e)}catch(e){throw this.agentControl.revokeSigningSecretTransfer(r),e}}return this.changed(),c}async deleteIdentity(e,t){if(!t.length)throw Error("Select at least one agent");let r=e.toUpperCase(),i=[...new Set(t)],a=await (0,t1.getPrismaClient)(),n=new Set((await a.signingCertificateAsset.findMany({where:{sha1:r,agentId:{in:i},hasPrivateKey:!0,missingAt:null},select:{agentId:!0}})).map(e=>e.agentId)),s=i.filter(e=>n.has(e));if(!s.length)throw Error("The identity has no private key on the selected agents");let o=await this.operation("DELETE_IDENTITY",r,s);for(let e of o.items){let t=await this.agentControl.createJob({agentId:e.agentId,kind:ni.SIGNING_IDENTITY_DELETE_JOB_KIND,payload:{sha1:r},idempotencyKey:`signing:${o.id}:${e.agentId}:delete`,timeoutSeconds:60,visibility:"SYSTEM"});await this.attachJob(e.id,t)}return this.changed(),o}async appleClient(){return new na.AppleDeveloperClient(await (0,na.storedAppleDeveloperCredentials)(this.credentials),this.fetcher)}async portalInventory(){let e=await this.appleClient(),[t,r,i,a]=await Promise.all([e.listProfiles(),e.listCertificates(),e.listBundleIds(),e.listDevices()]);return{profiles:t,certificates:r,bundleIds:i,devices:a}}async createPortalProfile(e){let t=await (await this.appleClient()).createProfile(e);return this.changed(),t.data}async deletePortalProfile(e){return await (await this.appleClient()).deleteProfile(e),this.changed(),!0}async revokePortalCertificate(e){return await (await this.appleClient()).revokeCertificate(e),this.changed(),!0}}var nc=e.i(308810),nu=e.i(783396),nd=e.i(247287),np=e.i(726355);let nh=/^[A-Za-z0-9][A-Za-z0-9.-]{0,254}$/;function nm(e,t,r){if("string"!=typeof e||!e.trim())throw Error(`${t} is required`);let i=e.trim();if(i.length>r||i.includes("\0"))throw Error(`${t} is invalid`);return i}function nf(e,t,r){return null==e||""===e?null:nm(e,t,r)}let ng={IOS_BUILD_SUCCEEDED:{key:"IOS_BUILD_SUCCEEDED",category:"BUILDS",label:"iOS build succeeded",description:"An iOS build finishes successfully.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1,defaultApnsEnabled:!0},IOS_BUILD_FAILED:{key:"IOS_BUILD_FAILED",category:"BUILDS",label:"iOS build failed",description:"An iOS build finishes with a failure.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1,defaultApnsEnabled:!0},COMMAND_RUN_SUCCEEDED:{key:"COMMAND_RUN_SUCCEEDED",category:"COMMANDS",label:"Command run succeeded",description:"A saved command finishes successfully.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1,defaultApnsEnabled:!0},COMMAND_RUN_FAILED:{key:"COMMAND_RUN_FAILED",category:"COMMANDS",label:"Command run failed",description:"A saved command finishes with a failure.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1,defaultApnsEnabled:!0},GITHUB_ACTIONS_SUCCEEDED:{key:"GITHUB_ACTIONS_SUCCEEDED",category:"GITHUB",label:"GitHub Actions succeeded",description:"A GitHub Actions workflow finishes successfully.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1,defaultApnsEnabled:!0},GITHUB_ACTIONS_FAILED:{key:"GITHUB_ACTIONS_FAILED",category:"GITHUB",label:"GitHub Actions failed",description:"A GitHub Actions workflow finishes with a failure.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1,defaultApnsEnabled:!0},GITLAB_PIPELINE_SUCCEEDED:{key:"GITLAB_PIPELINE_SUCCEEDED",category:"GITLAB",label:"GitLab pipeline succeeded",description:"A GitLab CI/CD pipeline finishes successfully.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1,defaultApnsEnabled:!0},GITLAB_PIPELINE_FAILED:{key:"GITLAB_PIPELINE_FAILED",category:"GITLAB",label:"GitLab pipeline failed",description:"A GitLab CI/CD pipeline finishes with a failure.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1,defaultApnsEnabled:!0},GITLAB_REVIEW_REQUESTED:{key:"GITLAB_REVIEW_REQUESTED",category:"GITLAB",label:"GitLab review requested",description:"A GitLab merge request requests a review.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1,defaultApnsEnabled:!0},RUN_NEEDS_ANSWER:{key:"RUN_NEEDS_ANSWER",category:"RUNS",label:"Plan or session needs an answer",description:"A managed plan or session asks for user input.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1,defaultApnsEnabled:!0},RUN_COMPLETED:{key:"RUN_COMPLETED",category:"RUNS",label:"Plan or session completed",description:"A managed plan or session completes successfully.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1,defaultApnsEnabled:!0},RUN_FAILED:{key:"RUN_FAILED",category:"RUNS",label:"Plan or session failed",description:"A managed plan or session fails.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1,defaultApnsEnabled:!0},RUN_CANCELLED:{key:"RUN_CANCELLED",category:"RUNS",label:"Plan or session cancelled",description:"A managed plan or session is cancelled.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!1,defaultWebPushEnabled:!1,defaultApnsEnabled:!1},RUN_RECOVERY_PAUSED:{key:"RUN_RECOVERY_PAUSED",category:"RUNS",label:"Plan or session paused after recovery",description:"A managed plan or session is paused after its agent restarts.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1,defaultApnsEnabled:!0},WORKFLOW_MESSAGE:{key:"WORKFLOW_MESSAGE",category:"WORKFLOWS",label:"Workflow message",description:"A workflow sends a generic notification.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1,defaultApnsEnabled:!0},WORKFLOW_NEEDS_ATTENTION:{key:"WORKFLOW_NEEDS_ATTENTION",category:"WORKFLOWS",label:"Workflow needs attention",description:"A workflow is waiting for data or a decision.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1,defaultApnsEnabled:!0},WORKFLOW_COMPLETED:{key:"WORKFLOW_COMPLETED",category:"WORKFLOWS",label:"Workflow completed",description:"A workflow run completes successfully.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1,defaultApnsEnabled:!0},WORKFLOW_FAILED:{key:"WORKFLOW_FAILED",category:"WORKFLOWS",label:"Workflow failed",description:"A workflow run fails.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1,defaultApnsEnabled:!0},WORKFLOW_RECOVERY_PAUSED:{key:"WORKFLOW_RECOVERY_PAUSED",category:"WORKFLOWS",label:"Workflow paused after recovery",description:"A workflow pauses while recovering durable work.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1,defaultApnsEnabled:!0}};function ny(e){return e in ng?ng[e]:null}let nw="default",nb=new Set(["BadDeviceToken","DeviceTokenNotForTopic","Unregistered"]);function nv(e,t,r){let i=e.trim();if(!i)throw Error(`${t} is required`);if(i.length>r)throw Error(`${t} is too long`);return i}function nk(e){let t,r=nv(e,"Push endpoint",4e3);try{t=new URL(r)}catch{throw Error("Push endpoint must be a valid URL")}if("https:"!==t.protocol)throw Error("Push endpoint must use HTTPS");return r}function nE(e,t){let r=new Date(e);if(!Number.isFinite(r.getTime()))throw Error(`${t} is invalid`);return r}function nS(){let e=process.env.PUBLIC_BASE_URL?.trim();if(e)try{let t=new URL(e);if("https:"===t.protocol)return t.origin}catch{}return"mailto:notifications@ai-development-environment.local"}function nI(e){if(!e||"object"!=typeof e)return null;let t=e.statusCode;return"number"==typeof t?t:null}function nA(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function nx(e,t,r){if(4096>=nA(r(e)))return e;let i=Array.from(e),a=e=>0===e?"":`${i.slice(0,e).join("")}${t}`,n=0,s=i.length-1;for(;n<s;){let e=Math.ceil((n+s)/2);4096>=nA(r(a(e)))?n=e:s=e-1}return a(n)}class n_{credentialService;apns;vapidPreparation;constructor(e,t=new nd.ApnsClient){this.credentialService=e,this.apns=t,this.vapidPreparation=null}publish(e){ie.agentEventBus.publish(ie.APP_NOTIFICATIONS_CHANGED_TOPIC,{notificationsChanged:e})}subscribe(){return ie.agentEventBus.iterate(ie.APP_NOTIFICATIONS_CHANGED_TOPIC)}async preferences(){let e=await (0,t1.getPrismaClient)(),t=new Map((await e.notificationPreference.findMany()).map(e=>[e.typeKey,e]));return Object.values(ng).map(e=>{let r=t.get(e.key);return{...e,sidebarEnabled:r?.sidebarEnabled??e.defaultSidebarEnabled,browserEnabled:r?.browserEnabled??e.defaultBrowserEnabled,webPushEnabled:r?.webPushEnabled??e.defaultWebPushEnabled,apnsEnabled:r?.apnsEnabled??e.defaultApnsEnabled,updatedAt:r?.updatedAt??null}})}async savePreference(e){let t=ny(e.typeKey);if(!t)throw Error("Unknown notification type");let r=await (0,t1.getPrismaClient)(),i=await r.notificationPreference.findUnique({where:{typeKey:t.key}}),a=e.apnsEnabled??i?.apnsEnabled??t.defaultApnsEnabled,n=await r.notificationPreference.upsert({where:{typeKey:t.key},create:{typeKey:t.key,sidebarEnabled:e.sidebarEnabled,browserEnabled:e.browserEnabled,webPushEnabled:e.webPushEnabled,apnsEnabled:a},update:{sidebarEnabled:e.sidebarEnabled,browserEnabled:e.browserEnabled,webPushEnabled:e.webPushEnabled,apnsEnabled:a}});return this.publish({kind:"PREFERENCES_UPDATED",notification:null,notificationId:null}),{...t,...n}}async recordInTransaction(e,t){let r=ny(t.typeKey);if(!r)throw Error("Unknown notification type");let i=await e.notificationPreference.findUnique({where:{typeKey:r.key}}),a=i?.sidebarEnabled??r.defaultSidebarEnabled,n=i?.browserEnabled??r.defaultBrowserEnabled,s=i?.webPushEnabled??r.defaultWebPushEnabled,o=i?.apnsEnabled??r.defaultApnsEnabled;if(!a&&!n&&!s&&!o)return null;let l=nv(t.dedupeKey,"Deduplication key",500);return await e.appNotification.findUnique({where:{dedupeKey:l}})?null:e.appNotification.create({data:{id:(0,b.randomUUID)(),dedupeKey:l,typeKey:r.key,title:nv(t.title,"Notification title",240),body:nv(t.body,"Notification body",1e3),href:function(e){let t=nv(e,"Notification link",2e3);if(!t.startsWith("/")||t.startsWith("//"))throw Error("Notification links must be same-origin paths");return t}(t.href),resourceKind:nv(t.resourceKind,"Resource kind",100),resourceId:nv(t.resourceId,"Resource ID",500),worktreeId:t.worktreeId??null,highlightColor:t.highlightColor?.trim()||null,sidebarRequested:a,browserRequested:n,webPushRequested:s,apnsRequested:o}})}created(e){e&&(this.publish({kind:"CREATED",notification:e,notificationId:e.id}),e.webPushRequested&&this.deliverWebPush(e).catch(e=>{console.error("Web Push delivery failed:",e)}),e.apnsRequested&&this.deliverApns(e).catch(e=>{console.error("APNs delivery failed:",e)}))}async history(e={}){let t=Math.max(1,Math.min(e.first??100,200)),r=await (0,t1.getPrismaClient)(),[i,a]=await Promise.all([r.appNotification.findMany({orderBy:[{createdAt:"desc"},{id:"desc"}],take:t+1,...e.after?{cursor:{id:e.after},skip:1}:void 0}),r.appNotification.count()]);return{items:i.slice(0,t),nextCursor:i.length>t?i[t-1].id:null,totalCount:a}}async sidebar(e=50){return(await (0,t1.getPrismaClient)()).appNotification.findMany({where:{sidebarRequested:!0,sidebarDismissedAt:null},orderBy:[{createdAt:"desc"},{id:"desc"}],take:Math.max(1,Math.min(e,100))})}async dismiss(e){let t=await (0,t1.getPrismaClient)(),r=await t.appNotification.updateMany({where:{id:e,sidebarRequested:!0,sidebarDismissedAt:null},data:{sidebarDismissedAt:new Date}});return r.count&&this.publish({kind:"DISMISSED",notification:null,notificationId:e}),r.count>0}async dismissAll(){let e=await (0,t1.getPrismaClient)(),t=await e.appNotification.updateMany({where:{sidebarRequested:!0,sidebarDismissedAt:null},data:{sidebarDismissedAt:new Date}});return t.count&&this.publish({kind:"SIDEBAR_CLEARED",notification:null,notificationId:null}),t.count}selectionWhere(e){let t=e.excludedRanges??[],r=e.all&&0===t.length?[]:[...new Set(e.ids??[])],i=[...new Set(e.excludedIds??[])],a=e.ranges??[];if(r.length>5e3||i.length>5e3)throw Error("Notification selection is too large");if(a.length>366||t.length>366)throw Error("Notification date selection is too large");let n=t.map(e=>{let t=nE(e.start,"Excluded selection start"),r=nE(e.end,"Excluded selection end");if(t>=r)throw Error("Excluded selection range is invalid");return{createdAt:{gte:t,lt:r}}}),s={NOT:{OR:n}},o=[];if(r.length&&o.push({id:{in:r}}),e.all)o.push(n.length?s:{});else if(a.length){let e=a.map(e=>{let t=nE(e.start,"Selection start"),r=nE(e.end,"Selection end");if(t>=r)throw Error("Selection range is invalid");return{createdAt:{gte:t,lt:r}}});o.push({AND:[{OR:e},...n.length?[s]:[]]})}if(!o.length)return{id:{in:[]}};let l=1===o.length?o[0]:{OR:o};return i.length?{AND:[l,{id:{notIn:i}}]}:l}async deleteSelection(e){let t=await (0,t1.getPrismaClient)(),r=await t.appNotification.deleteMany({where:this.selectionWhere(e)});return r.count&&this.publish({kind:"DELETED",notification:null,notificationId:null}),r.count}async deleteAll(){let e=await (0,t1.getPrismaClient)(),t=await e.appNotification.deleteMany();return t.count&&this.publish({kind:"HISTORY_CLEARED",notification:null,notificationId:null}),t.count}async webPushState(){let e=await (0,t1.getPrismaClient)(),[t,r]=await Promise.all([e.webPushSettings.findUnique({where:{id:nw}}),e.webPushSubscription.count()]),i=await this.credentialService.isConfigured(t2.CREDENTIALS.webPushVapidPrivateKey);return{configured:!!(t?.vapidPublicKey&&i),publicKey:t?.vapidPublicKey??null,subscriptionCount:r}}async webPushSubscriptions(){return(await (0,t1.getPrismaClient)()).webPushSubscription.findMany({orderBy:[{lastSeenAt:"desc"},{createdAt:"desc"}],select:{id:!0,endpoint:!0,expirationTime:!0,locale:!0,userAgent:!0,lastSeenAt:!0,createdAt:!0,updatedAt:!0}})}async prepareWebPush(){return this.vapidPreparation||(this.vapidPreparation=this.prepareWebPushOnce().finally(()=>{this.vapidPreparation=null})),this.vapidPreparation}async prepareWebPushOnce(){let e=await (0,t1.getPrismaClient)(),t=await e.webPushSettings.findUnique({where:{id:nw}});if(t?.vapidPublicKey){if(!await this.credentialService.getText(t2.CREDENTIALS.webPushVapidPrivateKey))throw Error("The Web Push private key is unavailable");return{publicKey:t.vapidPublicKey}}let r=np.default.generateVAPIDKeys();return await this.credentialService.setText(t2.CREDENTIALS.webPushVapidPrivateKey,r.privateKey,e=>e.webPushSettings.upsert({where:{id:nw},create:{id:nw,vapidPublicKey:r.publicKey,vapidGeneratedAt:new Date},update:{vapidPublicKey:r.publicKey,vapidGeneratedAt:new Date}}).then(()=>void 0)),{publicKey:r.publicKey}}async registerWebPush(e){let t=nk(e.endpoint),r=nv(e.p256dh,"Push p256dh key",1e3),i=nv(e.auth,"Push auth key",1e3),a=null===e.expirationTime||void 0===e.expirationTime?null:new Date(e.expirationTime);if(a&&!Number.isFinite(a.getTime()))throw Error("Push subscription expiration is invalid");return await this.prepareWebPush(),(await (0,t1.getPrismaClient)()).webPushSubscription.upsert({where:{endpoint:t},create:{id:(0,b.randomUUID)(),endpoint:t,p256dh:r,auth:i,expirationTime:a,locale:e.locale?.trim().slice(0,35)||null,userAgent:e.userAgent?.trim().slice(0,1e3)||null},update:{p256dh:r,auth:i,expirationTime:a,locale:e.locale?.trim().slice(0,35)||null,userAgent:e.userAgent?.trim().slice(0,1e3)||null,lastSeenAt:new Date}})}async unregisterWebPush(e){let t=nk(e),r=await (0,t1.getPrismaClient)();return(await r.webPushSubscription.deleteMany({where:{endpoint:t}})).count>0}async deleteWebPushSubscription(e){let t=nv(e,"Push subscription",200),r=await (0,t1.getPrismaClient)();return(await r.webPushSubscription.deleteMany({where:{id:t}})).count>0}async testWebPushSubscription(e){let t=nv(e,"Push subscription",200),r=await (0,t1.getPrismaClient)(),[i,a]=await Promise.all([r.webPushSettings.findUnique({where:{id:nw}}),r.webPushSubscription.findUnique({where:{id:t}})]);if(!a)throw Error("Push subscription was not found");if(!i?.vapidPublicKey)throw Error("Web Push is not configured");let n=await this.credentialService.getText(t2.CREDENTIALS.webPushVapidPrivateKey);if(!n)throw Error("The Web Push private key is unavailable");np.default.setVapidDetails(nS(),i.vapidPublicKey,n);try{return await np.default.sendNotification({endpoint:a.endpoint,expirationTime:a.expirationTime?.getTime()??null,keys:{p256dh:a.p256dh,auth:a.auth}},JSON.stringify({id:`test:${Date.now()}`,title:"Test notification",body:"Web Push is working for this browser.",href:"/notifications",icon:"/icon-192.png",badge:"/icon-192.png"}),{TTL:60,timeout:1e4}),!0}catch(e){if([404,410].includes(nI(e)??0))throw await r.webPushSubscription.deleteMany({where:{id:t}}),Error("The browser subscription expired and was removed");throw e}}async apnsState(){let e=await (0,t1.getPrismaClient)(),[t,r]=await Promise.all([(0,nu.readConnectionSettings)(this.credentialService,t2.CREDENTIALS.apnsTokenSettings,nu.apnsTokenConnectionSettings),e.notificationDevice.count({where:{status:"ACTIVE"}})]),i=await this.credentialService.isConfigured(t2.CREDENTIALS.apnsTokenPrivateKey);return{configured:!!(t&&i),deviceCount:r}}async notificationDevices(){let e=await (0,t1.getPrismaClient)();return(await e.notificationDevice.findMany({orderBy:[{status:"asc"},{lastRegisteredAt:"desc"}]})).map(({token:e,tokenHash:t,...r})=>({...r,tokenMasked:`${e.slice(0,8)}…${e.slice(-8)}`}))}async registerDevice(e,t){let r=function(e){let t=function(e,t){if(!e||"object"!=typeof e||Array.isArray(e))throw Error(`${t} must be an object`);return e}(e,"device"),r=new Set(["clientRegistrationId","token","tokenEncoding","topic","environment","displayName","deviceModel","osVersion","appVersion","appBuild","locale"]),i=Object.keys(t).filter(e=>!r.has(e));if(i.length)throw Error(`device has unsupported fields: ${i.join(", ")}`);let a=t.tokenEncoding??"HEX";if("HEX"!==a&&"BASE64"!==a)throw Error("tokenEncoding must be HEX or BASE64");let n=t.environment;if("SANDBOX"!==n&&"PRODUCTION"!==n)throw Error("environment must be SANDBOX or PRODUCTION");let s=nm(t.topic,"topic",255);if(!nh.test(s))throw Error("topic is invalid");return{clientRegistrationId:nm(t.clientRegistrationId,"clientRegistrationId",200),token:(0,rN.normalizeDeviceToken)(nm(t.token,"token",500),a),topic:s,environment:n,displayName:nm(t.displayName,"displayName",120),deviceModel:nf(t.deviceModel,"deviceModel",120),osVersion:nf(t.osVersion,"osVersion",60),appVersion:nf(t.appVersion,"appVersion",60),appBuild:nf(t.appBuild,"appBuild",60),locale:nf(t.locale,"locale",35)}}(e);return this.registerDeviceValidated(r,t)}async registerDeviceValidated(e,t){let r=await (0,t1.getPrismaClient)(),i=(0,b.createHash)("sha256").update(e.token).digest("hex"),a=new Date,n={token:e.token,tokenHash:i,topic:e.topic,environment:e.environment,displayName:e.displayName,deviceModel:e.deviceModel,osVersion:e.osVersion,appVersion:e.appVersion,appBuild:e.appBuild,locale:e.locale,lastIpAddress:t,status:"ACTIVE",lastFailureReason:null,lastFailureAt:null,lastRegisteredAt:a},s=await r.$transaction(async t=>{let r=await t.notificationDevice.findUnique({where:{clientRegistrationId:e.clientRegistrationId}}),a=await t.notificationDevice.findUnique({where:{tokenHash:i}});return a&&a.id!==r?.id&&await t.notificationDevice.delete({where:{id:a.id}}),{device:r?await t.notificationDevice.update({where:{id:r.id},data:n}):await t.notificationDevice.create({data:{id:(0,b.randomUUID)(),clientRegistrationId:e.clientRegistrationId,...n}}),created:!r}});return this.publish({kind:"DEVICES_CHANGED",notification:null,notificationId:null}),s}async deleteNotificationDevice(e){let t=nv(e,"Notification device",200),r=await (0,t1.getPrismaClient)(),i=await r.notificationDevice.deleteMany({where:{id:t}});return i.count&&this.publish({kind:"DEVICES_CHANGED",notification:null,notificationId:null}),i.count>0}async renameNotificationDevice(e,t){let r=nv(e,"Notification device",200),i=nv(t,"Display name",120),a=await (0,t1.getPrismaClient)(),n=await a.notificationDevice.update({where:{id:r},data:{displayName:i}});return this.publish({kind:"DEVICES_CHANGED",notification:null,notificationId:null}),n}async apnsAuthentication(){let e=await (0,nu.readConnectionSettings)(this.credentialService,t2.CREDENTIALS.apnsTokenSettings,nu.apnsTokenConnectionSettings),t=await this.credentialService.getText(t2.CREDENTIALS.apnsTokenPrivateKey);if(!e||!t)throw Error("APNs token authentication is not configured. Add the team ID, key ID, and .p8 key under Settings.");return{kind:"TOKEN",teamId:e.value.teamId,keyId:e.value.keyId,privateKey:t}}async sendApns(e,t,r){let i,a=await (0,t1.getPrismaClient)(),n=new Date;try{i=await this.apns.send({environment:e.environment,authentication:t,deviceToken:e.token,payload:function(e){let t=e.title,r=e.body,i=e.href,a=(a=t,n=r,s=i)=>({aps:{alert:{title:a,body:n},sound:"default","thread-id":e.typeKey,"interruption-level":"active"},notificationId:e.id,typeKey:e.typeKey,href:s});r=nx(r,"…",e=>a(t,e,i)),i=nx(i,"",e=>a(t,r,e)),t=nx(t,"…",e=>a(e,r,i));let n=a();if(nA(n)>4096)throw Error("APNs payload exceeds the 4096-byte alert limit");return n}(r),headers:{"apns-topic":e.topic,"apns-push-type":"alert","apns-priority":"10","apns-expiration":String(Math.floor(n.getTime()/1e3)+3600),...r.collapseId?{"apns-collapse-id":r.collapseId.slice(0,64)}:{}}})}catch(t){throw await a.notificationDevice.updateMany({where:{id:e.id,token:e.token},data:{lastFailureReason:t instanceof Error?t.message.slice(0,200):"SendFailed",lastFailureAt:n}}),t}if(200===i.status)return await a.notificationDevice.updateMany({where:{id:e.id,token:e.token},data:{lastDeliveredAt:n,lastFailureReason:null,lastFailureAt:null}}),!0;let s=i.reason??`HTTP ${i.status}`,o=410===i.status||nb.has(s),l=await a.notificationDevice.updateMany({where:{id:e.id,token:e.token},data:{lastFailureReason:s,lastFailureAt:n,...o?{status:"INACTIVE"}:{}}});return o&&l.count>0&&this.publish({kind:"DEVICES_CHANGED",notification:null,notificationId:null}),!1}async testNotificationDevice(e){let t=nv(e,"Notification device",200),r=await (0,t1.getPrismaClient)(),i=await r.notificationDevice.findUnique({where:{id:t}});if(!i)throw Error("Notification device was not found");let a=await this.apnsAuthentication();if(!await this.sendApns(i,a,{id:`test:${Date.now()}`,title:"Test notification",body:"Native notifications are working on this device.",href:"/notifications",typeKey:"TEST"})){let e=await r.notificationDevice.findUnique({where:{id:t}});throw Error(e?.lastFailureReason?`APNs rejected the notification: ${e.lastFailureReason}`:"APNs rejected the notification")}return!0}async deliverApns(e){let t;if(!e.apnsRequested)return;let r=await (0,t1.getPrismaClient)(),i=await r.notificationDevice.findMany({where:{status:"ACTIVE"}});if(i.length){try{t=await this.apnsAuthentication()}catch(e){console.error("APNs delivery skipped:",e);return}await Promise.allSettled(i.map(async r=>{try{await this.sendApns(r,t,{id:e.id,title:e.title,body:e.body,href:e.href,typeKey:e.typeKey,collapseId:e.dedupeKey})}catch(e){console.error(`APNs delivery to ${r.displayName} failed:`,e)}}))}}async deliverWebPush(e){if(!e.webPushRequested)return;let t=await (0,t1.getPrismaClient)(),[r,i]=await Promise.all([t.webPushSettings.findUnique({where:{id:nw}}),t.webPushSubscription.findMany()]);if(!r?.vapidPublicKey||!i.length)return;let a=await this.credentialService.getText(t2.CREDENTIALS.webPushVapidPrivateKey);if(!a)return;np.default.setVapidDetails(nS(),r.vapidPublicKey,a);let n=JSON.stringify({id:e.id,title:e.title,body:e.body,href:e.href,icon:"/icon-192.png",badge:"/icon-192.png"});await Promise.allSettled(i.map(async e=>{try{await np.default.sendNotification({endpoint:e.endpoint,expirationTime:e.expirationTime?.getTime()??null,keys:{p256dh:e.p256dh,auth:e.auth}},n,{TTL:3600,timeout:1e4})}catch(r){if([404,410].includes(nI(r)??0))return void await t.webPushSubscription.deleteMany({where:{endpoint:e.endpoint}});console.error(`Web Push delivery to ${e.endpoint} failed:`,r)}}))}}var nC=e.i(986847);let nR=e=>e?.toISOString()??null;function nT(e,t,r,i,a){return e?t?"RUNNING":a?"ERROR":r&&!i||r&&i&&Date.now()-i.getTime()>2e3*r+5e3?"STALE":"HEALTHY":"DISABLED"}class nD{operations=new Map;register(e){let t=this.operations.get(e.id);this.operations.set(e.id,{...e,lastStartedAt:t?.lastStartedAt??null,lastCompletedAt:t?.lastCompletedAt??null,lastSucceededAt:t?.lastSucceededAt??null,nextScheduledAt:t?.nextScheduledAt??null,durationMs:t?.durationMs??null,lastError:t?.lastError??null}),this.changed(e.id)}configure(e,t){let r=this.operations.get(e);r&&(Object.assign(r,t),r.enabled||(r.nextScheduledAt=null),this.changed(e))}schedule(e,t){let r=this.operations.get(e);r&&(r.nextScheduledAt=t,this.changed(e))}async run(e,t,r){let i=this.operations.get(e);if(!i)throw Error(`Polling operation ${e} is not registered`);let a=new Date;i.lastStartedAt=a,i.lastError=null,this.changed(e);try{let e=await t(),n=new Date;return i.lastCompletedAt=n,i.lastSucceededAt=n,i.durationMs=n.getTime()-a.getTime(),i.lastError=null,r&&(i.details={...i.details,...r(e)}),e}catch(t){let e=new Date;throw i.lastCompletedAt=e,i.durationMs=e.getTime()-a.getTime(),i.lastError=t instanceof Error?t.message:String(t),t}finally{this.changed(e)}}changed(e){ie.agentEventBus.publish(ie.POLLING_CHANGED_TOPIC,{pollingOperationChanged:e})}subscribe(){return ie.agentEventBus.iterate(ie.POLLING_CHANGED_TOPIC)}serverViews(){return[...this.operations.values()].map(e=>({...e,status:nT(e.enabled,!!(e.lastStartedAt&&(!e.lastCompletedAt||e.lastStartedAt>e.lastCompletedAt)),e.cadenceSeconds,e.lastCompletedAt,e.lastError),lastStartedAt:nR(e.lastStartedAt),lastCompletedAt:nR(e.lastCompletedAt),lastSucceededAt:nR(e.lastSucceededAt),nextScheduledAt:nR(e.nextScheduledAt)}))}async list(){let e=await (0,t1.getPrismaClient)(),[t,r,i]=await Promise.all([e.codebaseSettings.findUnique({where:{id:"default"}}),e.agent.findMany({orderBy:{name:"asc"},select:{id:!0,name:!0,lastSeenAt:!0,disconnectedAt:!0,codebaseScanIntervalSeconds:!0,jobReconciliationIntervalSeconds:!0,gitFetchIntervalSeconds:!0,heartbeatIntervalSeconds:!0,codebases:{select:{lastCheckedAt:!0,lastFetchedAt:!0,lastFetchAttemptAt:!0,lastFetchError:!0}},diskSpaceState:{select:{enabled:!0,lastReportedAt:!0,lastError:!0,volumesJson:!0}}}}),e.agentJob.groupBy({by:["agentId","status"],where:{status:{in:["QUEUED","RUNNING"]}},_count:{_all:!0}})]),n=t?.refreshIntervalSeconds??30,s=t?.fetchIntervalSeconds??300,o=new Map;for(let e of i)o.set(e.agentId,(o.get(e.agentId)??0)+e._count._all);let l=[];for(let e of r){let t=e.heartbeatIntervalSeconds??nC.DEFAULT_AGENT_HEARTBEAT_INTERVAL_SECONDS,r=e.jobReconciliationIntervalSeconds??nC.DEFAULT_AGENT_JOB_RECONCILIATION_INTERVAL_SECONDS,i=e.codebaseScanIntervalSeconds??n,c=e.gitFetchIntervalSeconds??s,u=null!==e.lastSeenAt&&null===e.disconnectedAt&&Date.now()-e.lastSeenAt.getTime()<=(0,a.agentOnlineWindowMs)(e);l.push({id:`agent-heartbeat:${e.id}`,kind:"AGENT_HEARTBEAT",runtime:"AGENT",status:u?"HEALTHY":"STALE",enabled:!0,cadenceSeconds:t,lastStartedAt:null,lastCompletedAt:nR(e.lastSeenAt),lastSucceededAt:nR(e.lastSeenAt),nextScheduledAt:e.lastSeenAt?new Date(e.lastSeenAt.getTime()+1e3*t).toISOString():null,durationMs:null,lastError:null,details:{agentId:e.id,agentName:e.name,connection:u?"ONLINE":"OFFLINE"}});let d=e.diskSpaceState,p=d?.enabled??!0,h=d?.lastReportedAt??null,m=0;try{let e=JSON.parse(d?.volumesJson??"[]");m=Array.isArray(e)?e.length:0}catch{m=0}l.push({id:`agent-disk-space:${e.id}`,kind:"AGENT_DISK_SPACE",runtime:"AGENT",status:p?nT(!0,!1,r7.DISK_SPACE_POLL_INTERVAL_SECONDS,h,d?.lastError??null):"DISABLED",enabled:p,cadenceSeconds:r7.DISK_SPACE_POLL_INTERVAL_SECONDS,lastStartedAt:null,lastCompletedAt:nR(h),lastSucceededAt:d?.lastError?null:nR(h),nextScheduledAt:p&&h?new Date(h.getTime()+1e3*r7.DISK_SPACE_POLL_INTERVAL_SECONDS).toISOString():null,durationMs:null,lastError:d?.lastError??null,details:{agentId:e.id,agentName:e.name,volumes:m}}),l.push({id:`agent-job-reconciliation:${e.id}`,kind:"AGENT_JOB_RECONCILIATION",runtime:"AGENT",status:u?"HEALTHY":"STALE",enabled:!0,cadenceSeconds:r,lastStartedAt:null,lastCompletedAt:nR(e.lastSeenAt),lastSucceededAt:nR(e.lastSeenAt),nextScheduledAt:e.lastSeenAt?new Date(e.lastSeenAt.getTime()+1e3*r).toISOString():null,durationMs:null,lastError:null,details:{agentId:e.id,agentName:e.name,pendingJobs:o.get(e.id)??0}});let f=e.codebases.map(e=>e.lastCheckedAt).filter(e=>null!==e).sort((e,t)=>t.getTime()-e.getTime())[0]??null,g=e.codebases.map(e=>e.lastFetchAttemptAt??e.lastFetchedAt).filter(e=>null!==e).sort((e,t)=>t.getTime()-e.getTime())[0]??null,y=e.codebases.filter(e=>e.lastFetchError).length;l.push({id:`agent-codebase-scan:${e.id}`,kind:"CODEBASE_SCAN",runtime:"AGENT",status:nT(e.codebases.length>0,!1,i,f,null),enabled:e.codebases.length>0,cadenceSeconds:i,lastStartedAt:null,lastCompletedAt:nR(f),lastSucceededAt:nR(f),nextScheduledAt:f?new Date(f.getTime()+1e3*i).toISOString():null,durationMs:null,lastError:null,details:{agentId:e.id,agentName:e.name,repositories:e.codebases.length}}),l.push({id:`agent-git-fetch:${e.id}`,kind:"GIT_FETCH",runtime:"AGENT",status:y>0?"ERROR":nT(e.codebases.length>0,!1,c,g,null),enabled:e.codebases.length>0,cadenceSeconds:c,lastStartedAt:null,lastCompletedAt:nR(g),lastSucceededAt:y>0?null:nR(g),nextScheduledAt:g?new Date(g.getTime()+1e3*c).toISOString():null,durationMs:null,lastError:y>0?`${y} repositories have fetch errors`:null,details:{agentId:e.id,agentName:e.name,repositories:e.codebases.length,fetchErrors:y}})}return[...this.serverViews(),...l]}}let nN="default",nO="https://raw.githubusercontent.com/BerriAI/litellm/refs/heads/main/model_prices_and_context_window.json",nP=new Set(["sample_spec"]);function nL(e){return"number"==typeof e&&Number.isFinite(e)?e:null}function nB(e){let t=nL(e);return null===t?null:Math.trunc(t)}function nU(e){return"string"==typeof e&&e.trim()?e.trim():null}function nj(e){let t=e.lastIndexOf("/");return t<0?e:e.slice(t+1)}let nM={MODEL:"model",PROVIDER:"provider",INPUT_COST:"inputCostPerToken",OUTPUT_COST:"outputCostPerToken",CACHE_READ_COST:"cacheReadCostPerToken",CACHE_WRITE_COST:"cacheWriteCostPerToken",CONTEXT_WINDOW:"maxInputTokens"};function nq(e){return{model:e.model,provider:e.provider,mode:e.mode,inputCostPerToken:e.inputCostPerToken,outputCostPerToken:e.outputCostPerToken,cacheReadCostPerToken:e.cacheReadCostPerToken,cacheWriteCostPerToken:e.cacheWriteCostPerToken,maxInputTokens:e.maxInputTokens,maxOutputTokens:e.maxOutputTokens,updatedAt:e.updatedAt.toISOString()}}class n${refreshing=null;checkedAt=0;async getCatalog(){let e=await (0,t1.getPrismaClient)(),t=await e.modelCostSettings.upsert({where:{id:nN},create:{id:nN},update:{}}),r=t.catalogUrl??nO;return{url:r,defaultUrl:nO,customUrl:t.catalogUrl,fetchedAt:t.fetchedAt?.toISOString()??null,entryCount:t.entryCount,error:t.error,stale:this.isStale(t.fetchedAt)||t.sourceUrl!==r}}isStale(e){return!e||Date.now()-e.getTime()>=864e5}async saveSettings(e){let t=e?.trim()??"",r=t&&t!==nO?t:null;if(r){let e;try{e=new URL(r)}catch{throw Error("The model cost URL must be a valid URL")}if("https:"!==e.protocol&&"http:"!==e.protocol)throw Error("The model cost URL must be an http or https URL")}let i=await (0,t1.getPrismaClient)();await i.modelCostSettings.upsert({where:{id:nN},create:{id:nN,catalogUrl:r},update:{catalogUrl:r}}),this.checkedAt=0;let a=await this.getCatalog();return ie.agentEventBus.publish(ie.MODEL_COST_CATALOG_CHANGED_TOPIC,{catalog:a}),a}async refresh(){return this.refreshing||(this.refreshing=this.runRefresh().finally(()=>{this.refreshing=null})),this.refreshing}async runRefresh(){let e=await (0,t1.getPrismaClient)(),t=await this.getCatalog();try{let r=await fetch(t.url,{headers:{accept:"application/json"},signal:AbortSignal.timeout(3e4)});if(!r.ok)throw Error(`The model cost catalog request failed with ${r.status}`);let i=function(e){if(!e||"object"!=typeof e||Array.isArray(e))throw Error("The model cost catalog is not a JSON object");let t=[];for(let[r,i]of Object.entries(e)){if(nP.has(r)||!i||"object"!=typeof i||Array.isArray(i))continue;let e=nL(i.input_cost_per_token),a=nL(i.output_cost_per_token);if((null!==e||null!==a)&&(t.push({model:r,provider:nU(i.litellm_provider),mode:nU(i.mode),inputCostPerToken:e,outputCostPerToken:a,cacheReadCostPerToken:nL(i.cache_read_input_token_cost),cacheWriteCostPerToken:nL(i.cache_creation_input_token_cost),maxInputTokens:nB(i.max_input_tokens),maxOutputTokens:nB(i.max_output_tokens)}),t.length>=2e4))break}if(!t.length)throw Error("The model cost catalog contained no priced models");return t}(await r.json());await e.$transaction(async e=>{await e.modelCostEntry.deleteMany({});for(let t=0;t<i.length;t+=500)await e.modelCostEntry.createMany({data:i.slice(t,t+500)});await e.modelCostSettings.update({where:{id:nN},data:{fetchedAt:new Date,sourceUrl:t.url,entryCount:i.length,error:null}})})}catch(r){let t=r instanceof Error?r.message:String(r);await e.modelCostSettings.update({where:{id:nN},data:{error:t.slice(0,2e3)}})}let r=await this.getCatalog();return ie.agentEventBus.publish(ie.MODEL_COST_CATALOG_CHANGED_TOPIC,{catalog:r}),r}async ensureFresh(){this.refreshing&&await this.refreshing,Date.now()-this.checkedAt<3e5||((await this.getCatalog()).stale&&await this.refresh(),this.checkedAt=Date.now())}async listEntries({search:e,first:t=100,offset:r=0,sortKey:i="MODEL",direction:a="ASC"}){var n;let s,o;await this.ensureFresh();let l=await (0,t1.getPrismaClient)(),c=e?.trim(),u=c?{OR:[{model:{contains:c}},{provider:{contains:c}}]}:{},d=Math.min(Math.max(t??100,1),500),p=Math.max(r??0,0),[h,m]=await Promise.all([l.modelCostEntry.findMany({where:u,orderBy:(n=i??"MODEL",s="DESC"===(a??"ASC")?"desc":"asc","model"===(o=nM[n]??"model")?[{model:s}]:[{[o]:{sort:s,nulls:"last"}},{model:s}]),skip:p,take:d}),l.modelCostEntry.count({where:u})]);return{items:h.map(nq),totalCount:m}}async lookup(e){let t=[...new Set(e.filter(Boolean))],r=new Map;if(!t.length)return r;let i=await (0,t1.getPrismaClient)(),a=[...new Set(t.flatMap(e=>[e,nj(e)]))],n=new Map((await i.modelCostEntry.findMany({where:{model:{in:a}}})).map(e=>[e.model,e])),s=[];for(let e of t){let t=n.get(e)??n.get(nj(e));t?r.set(e,nq(t)):s.push(e)}if(!s.length)return r;let o=await i.modelCostEntry.findMany({where:{OR:s.map(e=>({model:{endsWith:`/${nj(e)}`}}))}});for(let e of s){let t=nj(e).toLowerCase(),i=o.find(e=>nj(e.model).toLowerCase()===t);i&&r.set(e,nq(i))}return r}estimate(e,t){if(!e)return null;let r=e.inputCostPerToken,i=e.outputCostPerToken;if(null===r&&null===i)return null;let a=e.cacheReadCostPerToken??r??0,n=e.cacheWriteCostPerToken??r??0;return t.inputTokens*(r??0)+t.outputTokens*(i??0)+t.cacheReadTokens*a+t.cacheWriteTokens*n}}e.i(648153);var nF=e.i(594875),nG=e.i(937121),nK=e.i(988349);let nH=["ANY_AGENT_HOME","SPECIFIC_AGENT_HOME","ANY_WORKTREE","REPOSITORY_WORKTREE"],nV=["NEVER","ON_FAILURE","ALWAYS"],nW=["EXCLUSIVE","NON_EXCLUSIVE","EXCLUDED"],nJ=["QUEUED","RUNNING","RESTARTING","CANCELLING"],nz=["SUCCEEDED","FAILED","CANCELLED"],nY=["SUCCEEDED","FAILED","CANCELLED","TIMED_OUT"],nZ=e=>!!(e&&!nY.includes(e.status)),nQ="aide.command.export",nX=()=>({targetAgent:!0,repositories:{include:{repository:!0},orderBy:[{createdAt:"asc"},{repositoryId:"asc"}]}}),n0=e=>{let{repositories:t=[],...r}=e,i=Array.isArray(t)?t:[],a=i.map(e=>e.repository);return{...r,targetRepositoryIds:i.map(e=>e.repositoryId),targetRepositories:a,targetRepositoryId:1===i.length?i[0]?.repositoryId:null,targetRepository:1===a.length?a[0]:null}},n1=["QUEUED","RESTARTING"],n2=(e,t)=>e.queuedAt.getTime()-t.queuedAt.getTime()||e.id.localeCompare(t.id);function n3(e,t,r){let i=t.trim().toUpperCase();if(!e.includes(i))throw Error(`${r} is not supported`);return i}function n4(e,t,r){let i=e.trim();if(!i)throw Error(`${t} is required`);if(i.length>r)throw Error(`${t} is too long`);return i}function n6(e,t){if(!e||"object"!=typeof e||Array.isArray(e))throw Error(`${t} must be an object`);return e}let n8=e=>"string"==typeof e&&e.trim()?e.trim():null;function n5(e){ie.agentEventBus.publish(ie.COMMANDS_CHANGED_TOPIC,{commandsChanged:e})}function n9(e){ie.agentEventBus.publish(ie.COMMAND_RUNS_CHANGED_TOPIC,{commandRunsChanged:e}),ie.agentEventBus.publish((0,ie.commandRunChangedTopic)(e.id),{commandRunChanged:e}),ie.agentEventBus.publish(ie.SIDEBAR_STATUS_CHANGED_TOPIC,{sidebarStatusChanged:!0})}class n7{agentControl;notifications;timer;reconciliation;dispatchChain;constructor(e,t){this.agentControl=e,this.notifications=t,this.timer=null,this.reconciliation=null,this.dispatchChain=Promise.resolve(),this.agentControl.registerCompletionHandler(nG.COMMAND_RUN_JOB_KIND,e=>this.handleAttemptCompletion(e)),this.agentControl.registerConnectionHandler(e=>this.reconcileWithReporting({agentId:e}))}startRuntime(){this.timer||(this.reconcileWithReporting(),this.timer=setInterval(()=>void this.reconcileWithReporting(),1e3),this.timer.unref())}async reconcileWithReporting(e={}){if(this.reconciliation)return this.reconciliation;this.reconciliation=this.reconcile(e);try{await this.reconciliation}catch(e){console.error("Command runtime reconciliation failed:",e)}finally{this.reconciliation=null}}async listDefinitions(e=!1){let t=await (0,t1.getPrismaClient)();return(await t.commandDefinition.findMany({where:e?{}:{archivedAt:null},include:nX(),orderBy:[{archivedAt:"asc"},{name:"asc"}]})).map(n0)}async getDefinition(e){let t=await (0,t1.getPrismaClient)(),r=await t.commandDefinition.findUnique({where:{id:e},include:nX()});return r?n0(r):null}normalizeDefinition(e){let t=n3(nH,e.targetKind,"Target scope"),r=n3(nV,e.restartPolicy??"NEVER","Restart policy"),i=void 0===e.restartLimit?3:e.restartLimit;if(null!==i&&(!Number.isInteger(i)||i<0||i>100))throw Error("Restart limit must be null or an integer from 0 to 100");let a="SPECIFIC_AGENT_HOME"===t,n="REPOSITORY_WORKTREE"===t;if(void 0!==e.targetRepositoryIds&&null!==e.targetRepositoryIds&&e.targetRepositoryId)throw Error("Use targetRepositoryIds or the deprecated targetRepositoryId, not both");let s=[...new Set((e.targetRepositoryIds??(e.targetRepositoryId?[e.targetRepositoryId]:[])).map(e=>e.trim()).filter(Boolean))];if(!!e.targetAgentId!==a)throw Error(a?"A specific-agent command requires an agent":"This target scope does not accept a specific agent");if(!!s.length!==n)throw Error(n?"A repository-worktree command requires at least one repository":"This target scope does not accept repositories");let o=n3(nW,e.concurrency??"NON_EXCLUSIVE","Concurrency");return{name:n4(e.name,"Name",120),description:(e.description??"").trim().slice(0,2e3),script:n4(e.script,"Script",1e6),targetKind:t,targetAgentId:e.targetAgentId??null,targetRepositoryIds:s,restartPolicy:r,restartLimit:i,concurrency:o,blocksGitOperations:"EXCLUSIVE"===o||(e.blocksGitOperations??!1),quickActionEnabled:e.quickActionEnabled??!1,quickActionIconKey:n4(e.quickActionIconKey??"terminal","Quick action icon",40),quickActionButtonVariant:n4(e.quickActionButtonVariant??"default","Quick action style",40),notificationsEnabled:e.notificationsEnabled??!0}}async assertRepositoriesExist(e){if(!e.length)return;let t=await (0,t1.getPrismaClient)();if(await t.codebaseRepository.count({where:{id:{in:e}}})!==e.length)throw Error("One or more selected repositories do not exist")}async createDefinition(e){let t=await (0,t1.getPrismaClient)(),{targetRepositoryIds:r,...i}=this.normalizeDefinition(e);await this.assertRepositoriesExist(r);let a=n0(await t.commandDefinition.create({data:{id:(0,b.randomUUID)(),...i,repositories:{create:r.map(e=>({repositoryId:e}))}},include:nX()}));return n5(a),a}async updateDefinition(e,t){let r=await (0,t1.getPrismaClient)(),{targetRepositoryIds:i,...a}=this.normalizeDefinition(t);await this.assertRepositoriesExist(i);let n=n0(await r.commandDefinition.update({where:{id:e},data:{...a,repositories:{deleteMany:{},create:i.map(e=>({repositoryId:e}))}},include:nX()}));return n5(n),n}async deleteDefinition(e){let t=await (0,t1.getPrismaClient)(),r=await t.commandDefinition.findUnique({where:{id:e}});if(!r)return!1;if(await t.commandRun.count({where:{commandId:e}}))throw Error("Archive commands that have run history instead of deleting them");return await t.commandDefinition.delete({where:{id:e}}),n5(r),!0}async exportDefinition(e){let t=await this.getDefinition(e);if(!t)throw Error("Command not found");return{format:nQ,schemaVersion:2,exportedAt:new Date().toISOString(),command:{name:t.name,description:t.description,script:t.script,targetKind:t.targetKind,targetAgentName:t.targetAgent?.name??null,targetRepositories:t.targetRepositories.map(e=>({canonicalOrigin:e.canonicalOrigin,name:e.name})),restartPolicy:t.restartPolicy,restartLimit:t.restartLimit,concurrency:t.concurrency,blocksGitOperations:t.blocksGitOperations,quickActionEnabled:t.quickActionEnabled,quickActionIconKey:t.quickActionIconKey,quickActionButtonVariant:t.quickActionButtonVariant,notificationsEnabled:t.notificationsEnabled}}}async resolveImportTarget(e){let t=n3(nH,n8(e.targetKind)??"ANY_AGENT_HOME","Target scope"),r=await (0,t1.getPrismaClient)();if("SPECIFIC_AGENT_HOME"===t){let i=n8(e.targetAgentName),a=i?await r.agent.findFirst({where:{name:i},orderBy:{id:"asc"}}):null;return a?{targetKind:t,targetAgentId:a.id,targetRepositoryIds:[],widened:!1}:{targetKind:"ANY_AGENT_HOME",targetAgentId:null,targetRepositoryIds:[],widened:!0}}if("REPOSITORY_WORKTREE"===t){let i=Array.isArray(e.targetRepositories)?e.targetRepositories.map(e=>n6(e,"Exported target repository")):[];if(i.length){let e=await r.codebaseRepository.findMany({where:{OR:i.flatMap(e=>{let t=n8(e.canonicalOrigin),r=n8(e.name);return[...t?[{canonicalOrigin:t}]:[],...r?[{name:r}]:[]]})},orderBy:{id:"asc"}}),a=i.map(t=>{let r=n8(t.canonicalOrigin),i=n8(t.name);return e.find(e=>r&&e.canonicalOrigin===r)??e.find(e=>i&&e.name===i)}).filter(e=>!!e),n=[...new Set(a.map(e=>e.id))];return n.length?{targetKind:t,targetAgentId:null,targetRepositoryIds:n,widened:a.length!==i.length}:{targetKind:"ANY_WORKTREE",targetAgentId:null,targetRepositoryIds:[],widened:!0}}let a=n8(e.targetRepositoryName),n=a?await r.codebaseRepository.findFirst({where:{name:a},orderBy:{id:"asc"}}):null;return n?{targetKind:t,targetAgentId:null,targetRepositoryIds:[n.id],widened:!1}:{targetKind:"ANY_WORKTREE",targetAgentId:null,targetRepositoryIds:[],widened:!0}}return{targetKind:t,targetAgentId:null,targetRepositoryIds:[],widened:!1}}async importDefinition(e){let t=e.payload;if("string"==typeof t){if(Buffer.byteLength(t,"utf8")>2097152)throw Error("Command import is too large");t=JSON.parse(t)}let r=n6(t,"Command import"),i=r.format===nQ?n6(r.command,"Exported command"):r,{widened:a,...n}=await this.resolveImportTarget(i),s=e.name?.trim()||n8(i.name);if(!s)throw Error("Name is required");let o=n8(i.script);if(!o)throw Error("Script is required");return this.createDefinition({name:s,description:"string"==typeof i.description?i.description:"",script:o,...n,restartPolicy:n8(i.restartPolicy)??"NEVER",restartLimit:null===i.restartLimit||"number"==typeof i.restartLimit?i.restartLimit:3,concurrency:n8(i.concurrency)??"NON_EXCLUSIVE",blocksGitOperations:!0===i.blocksGitOperations,quickActionEnabled:!a&&!0===i.quickActionEnabled,quickActionIconKey:n8(i.quickActionIconKey)??"terminal",quickActionButtonVariant:n8(i.quickActionButtonVariant)??"default",notificationsEnabled:!1!==i.notificationsEnabled})}async archiveDefinition(e,t){let r=await (0,t1.getPrismaClient)(),i=n0(await r.commandDefinition.update({where:{id:e},data:{archivedAt:t?new Date:null},include:nX()}));return n5(i),i}async eligibleForAgent(e){let t=await (0,t1.getPrismaClient)();return(await t.commandDefinition.findMany({where:{archivedAt:null,OR:[{targetKind:"ANY_AGENT_HOME"},{targetKind:"SPECIFIC_AGENT_HOME",targetAgentId:e}]},include:nX(),orderBy:{name:"asc"}})).map(n0)}async eligibleForWorktree(e){let t=await (0,t1.getPrismaClient)(),r=await t.worktree.findUnique({where:{id:e},select:{codebase:{select:{repositoryId:!0}}}});if(!r)throw Error("Worktree not found");return(await t.commandDefinition.findMany({where:{archivedAt:null,OR:[{targetKind:"ANY_WORKTREE"},{targetKind:"REPOSITORY_WORKTREE",repositories:{some:{repositoryId:r.codebase.repositoryId}}}]},include:nX(),orderBy:{name:"asc"}})).map(n0)}async listRuns(e){let t=await (0,t1.getPrismaClient)(),r=Math.max(1,Math.min(e.first??50,200)),i=e.search?.trim(),a={...e.includeArchived?{}:{archivedAt:null},...e.agentId?{agentId:e.agentId}:{},...e.worktreeId?{worktreeId:e.worktreeId}:{},...e.statuses?.length?{status:{in:e.statuses}}:{},...i?{OR:[{snapshotName:{contains:i}},{agentName:{contains:i}},{worktreePath:{contains:i}}]}:{}},[n,s]=await Promise.all([t.commandRun.findMany({where:a,include:{command:!0,agent:!0,worktree:{include:{codebase:{include:{repository:!0}}}},attempts:{orderBy:{attempt:"asc"}}},orderBy:[{createdAt:"desc"},{id:"desc"}],take:r+1,...e.after?{cursor:{id:e.after},skip:1}:{}}),t.commandRun.count({where:a})]),o=n.length>r,l=n.slice(0,r);return{nodes:l,totalCount:s,pageInfo:{hasNextPage:o,endCursor:l.at(-1)?.id??null}}}async getRun(e){return(await (0,t1.getPrismaClient)()).commandRun.findUnique({where:{id:e},include:{command:!0,agent:!0,worktree:{include:{codebase:{include:{repository:!0}}}},attempts:{include:{agentJob:!0},orderBy:{attempt:"asc"}},predecessor:!0,successor:!0}})}async runQueue(e){let t=await (0,t1.getPrismaClient)(),r=await t.commandRun.findUnique({where:{id:e},include:{agent:{select:{lastSeenAt:!0,disconnectedAt:!0,heartbeatIntervalSeconds:!0}},predecessor:{select:{status:!0}},attempts:{select:{agentJobId:!0,completionProcessedAt:!0},orderBy:{attempt:"desc"},take:1}}});if(!r)return{reason:"NOT_QUEUED",position:0,waitingCount:0,entries:[]};let i=r.attempts[0],n=!!(r.agent?.lastSeenAt&&!r.agent.disconnectedAt&&Date.now()-r.agent.lastSeenAt.getTime()<=(0,a.agentOnlineWindowMs)(r.agent));return function(e){let{candidate:t}=e,r="EXCLUDED"!==t.concurrency,i=e.peers.filter(e=>e.holdingTarget),a=[...i,...t.holdingTarget?[t]:[]].sort(n2),n=[...e.peers.filter(e=>!e.holdingTarget),...t.holdingTarget?[]:[t]].sort(n2),s=n.findIndex(e=>e.id===t.id),o=s<0?[]:n.slice(0,s),l=e=>r&&"EXCLUDED"!==e.concurrency&&("EXCLUSIVE"===t.concurrency||"EXCLUSIVE"===e.concurrency),c=i.filter(l),u=o.filter(l),d=t.stopRequested||!n1.includes(t.status)?"NOT_QUEUED":t.holdingTarget?e.agentOnline?"WAITING_FOR_AGENT":"AGENT_OFFLINE":e.predecessorPending?"WAITING_FOR_PREDECESSOR":e.restartPending?"RESTART_DELAY":c.length?"TARGET_BUSY":u.length?"QUEUED_BEHIND":e.agentOnline?"READY":"AGENT_OFFLINE",p=new Set("TARGET_BUSY"===d||"QUEUED_BEHIND"===d?[...c,...u].map(e=>e.id):[]);return{reason:d,position:s<0?0:s+1,waitingCount:n.length,entries:[...a,...n].map(e=>({...e,blocking:p.has(e.id),currentRun:e.id===t.id}))}}({candidate:{id:r.id,displayNumber:r.displayNumber,name:r.snapshotName,status:r.status,concurrency:r.snapshotConcurrency,queuedAt:r.queuedAt,stopRequested:r.stopRequested,holdingTarget:!!(i?.agentJobId&&!i.completionProcessedAt)},peers:"EXCLUDED"===r.snapshotConcurrency?[]:await this.targetPeers(r),agentOnline:n,predecessorPending:!!(r.predecessor&&!nz.includes(r.predecessor.status)),restartPending:!!("RESTARTING"===r.status&&r.nextRestartAt&&r.nextRestartAt.getTime()>Date.now())})}async listOutput(e,t=0,r=-1,i=1e3){let a=await (0,t1.getPrismaClient)();return i<1?[]:a.commandRunOutputChunk.findMany({where:{OR:[{attempt:{runId:e,attempt:{gt:t}}},{attempt:{runId:e,attempt:t},sequence:{gt:r}}]},include:{attempt:{select:{attempt:!0,runId:!0}}},orderBy:[{attempt:{attempt:"asc"}},{sequence:"asc"}],take:Math.max(1,Math.min(i,5e3))})}async resolveTarget(e,t){let r=await (0,t1.getPrismaClient)();if("ANY_AGENT_HOME"===e.targetKind||"SPECIFIC_AGENT_HOME"===e.targetKind){if(!t.agentId||t.worktreeId)throw Error("This command requires an agent-home target");if("SPECIFIC_AGENT_HOME"===e.targetKind&&e.targetAgentId!==t.agentId)throw Error("This command is not eligible for the selected agent");let i=await r.agent.findUnique({where:{id:t.agentId}});if(!i)throw Error("Agent not found");return this.requireCapability(i.capabilitiesJson),{agent:i,worktree:null}}if(!t.worktreeId||t.agentId)throw Error("This command requires a worktree target");let i=await r.worktree.findUnique({where:{id:t.worktreeId},include:{codebase:{include:{agent:!0,repository:!0}}}});if(!i||i.missingAt)throw Error("Worktree is unavailable");if("REPOSITORY_WORKTREE"===e.targetKind&&!e.repositories.some(e=>e.repositoryId===i.codebase.repositoryId))throw Error("This command is not eligible for the selected repository");return this.requireCapability(i.codebase.agent.capabilitiesJson),{agent:i.codebase.agent,worktree:i}}requireCapability(e){if(!(function(e){try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}catch{return[]}})(e).includes(nG.COMMAND_RUN_JOB_KIND))throw Error("The selected agent must be upgraded before it can run commands")}async startRun(e){let t,r=await (0,t1.getPrismaClient)(),i=e.idempotencyKey?.trim()||(0,b.randomUUID)(),a=await r.commandRun.findUnique({where:{idempotencyKey:i}});if(a)return this.getRun(a.id);let n=await r.commandDefinition.findUnique({where:{id:e.commandId},include:nX()});if(!n||n.archivedAt)throw Error("Command not found");let{agent:s,worktree:o}=await this.resolveTarget(n,e);try{t=await r.$transaction(async t=>{let r=await t.commandRunNumberSequence.upsert({where:{id:"default"},create:{id:"default",nextValue:1},update:{nextValue:{increment:1}}});return t.commandRun.create({data:{id:(0,b.randomUUID)(),displayNumber:r.nextValue,commandId:n.id,idempotencyKey:i,origin:(e.origin??"MANUAL").trim().toUpperCase(),snapshotName:n.name,snapshotDescription:n.description,snapshotScript:n.script,snapshotTargetKind:n.targetKind,snapshotRestartPolicy:n.restartPolicy,snapshotRestartLimit:n.restartLimit,snapshotConcurrency:n.concurrency,snapshotBlocksGitOperations:n.blocksGitOperations||!0===e.blocksGitOperations,snapshotNotificationsEnabled:n.notificationsEnabled,snapshotJson:JSON.stringify(n0(n)),agentId:s.id,worktreeId:o?.id??null,agentName:s.name,agentHostname:s.hostname,worktreePath:o?.folder??null,worktreeBranch:o?.branch??null}})})}catch(t){let e=await r.commandRun.findUnique({where:{idempotencyKey:i}});if(!e)throw t;return this.getRun(e.id)}return n9(t),await this.dispatch(t.id),this.getRun(t.id)}async startCustomRun(e){let t,r=await (0,t1.getPrismaClient)(),i=e.idempotencyKey?.trim()||(0,b.randomUUID)(),a=await r.commandRun.findUnique({where:{idempotencyKey:i}});if(a)return this.getRun(a.id);let n=n4(e.script,"Script",1e6),s=e.agentId&&!e.worktreeId?"ANY_AGENT_HOME":e.worktreeId&&!e.agentId?"ANY_WORKTREE":null;if(!s)throw Error("A custom command requires exactly one agent-home or worktree target");let{agent:o,worktree:l}=await this.resolveTarget({targetKind:s,targetAgentId:null,repositories:[]},e),c={name:"Custom command",description:"",script:n,targetKind:s,restartPolicy:"NEVER",restartLimit:null,concurrency:"NON_EXCLUSIVE",blocksGitOperations:!0===e.blocksGitOperations,notificationsEnabled:!0};try{t=await r.$transaction(async t=>{let r=await t.commandRunNumberSequence.upsert({where:{id:"default"},create:{id:"default",nextValue:1},update:{nextValue:{increment:1}}});return t.commandRun.create({data:{id:(0,b.randomUUID)(),displayNumber:r.nextValue,commandId:null,idempotencyKey:i,origin:(e.origin??"MANUAL").trim().toUpperCase(),status:"QUEUED",snapshotName:c.name,snapshotDescription:c.description,snapshotScript:c.script,snapshotTargetKind:c.targetKind,snapshotRestartPolicy:c.restartPolicy,snapshotRestartLimit:c.restartLimit,snapshotConcurrency:c.concurrency,snapshotBlocksGitOperations:c.blocksGitOperations,snapshotNotificationsEnabled:c.notificationsEnabled,snapshotJson:JSON.stringify(c),agentId:o.id,worktreeId:l?.id??null,agentName:o.name,agentHostname:o.hostname,worktreePath:l?.folder??null,worktreeBranch:l?.branch??null}})})}catch(t){let e=await r.commandRun.findUnique({where:{idempotencyKey:i}});if(!e)throw t;return this.getRun(e.id)}n9(t);try{await this.dispatch(t.id)}catch(e){throw await this.failDispatch(t.id,e instanceof Error?e.message:String(e)),e}return this.getRun(t.id)}async targetPeers(e){let t=await (0,t1.getPrismaClient)();return(await t.commandRun.findMany({where:{id:{not:e.id},status:{in:[...nJ]},snapshotConcurrency:{not:"EXCLUDED"},...e.worktreeId?{worktreeId:e.worktreeId}:{agentId:e.agentId,worktreeId:null}},select:{id:!0,displayNumber:!0,snapshotName:!0,status:!0,snapshotConcurrency:!0,queuedAt:!0,attempts:{select:{agentJobId:!0,completionProcessedAt:!0},orderBy:{attempt:"desc"},take:1}}})).map(e=>{let t=e.attempts[0];return{id:e.id,displayNumber:e.displayNumber,name:e.snapshotName,status:e.status,concurrency:e.snapshotConcurrency,queuedAt:e.queuedAt,holdingTarget:!!(t?.agentJobId&&!t.completionProcessedAt)}})}async admitRun(e){if("EXCLUDED"===e.snapshotConcurrency)return!0;let t=await this.targetPeers(e),r=t.filter(e=>e.holdingTarget),i=t.filter(e=>!e.holdingTarget);var a={candidate:{id:e.id,concurrency:e.snapshotConcurrency,queuedAt:e.queuedAt},holders:r,waiting:i};if("EXCLUDED"===a.candidate.concurrency)return!0;let n=a.holders.filter(e=>"EXCLUDED"!==e.concurrency&&e.id!==a.candidate.id),s=a.waiting.filter(e=>"EXCLUDED"!==e.concurrency&&e.id!==a.candidate.id).filter(e=>{let t=e.queuedAt.getTime()-a.candidate.queuedAt.getTime();return 0!==t?t<0:e.id<a.candidate.id});return"EXCLUSIVE"===a.candidate.concurrency?0===n.length&&0===s.length:!n.some(e=>"EXCLUSIVE"===e.concurrency)&&!s.some(e=>"EXCLUSIVE"===e.concurrency)}dispatch(e){let t=this.dispatchChain.then(()=>this.dispatchRun(e),()=>this.dispatchRun(e));return this.dispatchChain=t.catch(()=>void 0),t}async dispatchRun(e){let t=await (0,t1.getPrismaClient)(),r=await t.commandRun.findUnique({where:{id:e},include:{agent:!0,worktree:{include:{codebase:!0}},attempts:!0}});if(!r||r.stopRequested)return;if(!r.agentId||!r.agent)return void await this.failDispatch(r.id,"The command agent is no longer available");if(r.predecessorRunId){let e=await t.commandRun.findUnique({where:{id:r.predecessorRunId},select:{status:!0}});if(e&&!nz.includes(e.status))return}if(new Set(["ANY_WORKTREE","REPOSITORY_WORKTREE"]).has(r.snapshotTargetKind)&&(!r.worktreeId||!r.worktree||r.worktree.missingAt))return void await this.failDispatch(r.id,"The command worktree is no longer available");if(r.worktree&&r.worktree.codebase.agentId!==r.agentId)return void await this.failDispatch(r.id,"The worktree is no longer assigned to the command agent");try{this.requireCapability(r.agent.capabilitiesJson)}catch(e){await this.failDispatch(r.id,e instanceof Error?e.message:String(e));return}let i=r.attempts.reduce((e,t)=>!e||t.attempt>e.attempt?t:e,null);if(!(i?.agentJobId&&!i.completionProcessedAt)&&!await this.admitRun(r))return;let a=!i||i.agentJobId||i.completionProcessedAt||i.finishedAt?(i?.attempt??0)+1:i.attempt,n=i?.attempt===a?i:await t.commandRunAttempt.findUnique({where:{runId_attempt:{runId:e,attempt:a}}});if(!n)try{n=await t.commandRunAttempt.create({data:{id:(0,b.randomUUID)(),runId:e,attempt:a}})}catch(r){if(!(n=await t.commandRunAttempt.findUnique({where:{runId_attempt:{runId:e,attempt:a}}})))throw r}if(!n.agentJobId){let e;try{e=await this.agentControl.createJob({agentId:r.agentId,kind:nG.COMMAND_RUN_JOB_KIND,payload:{commandRunId:r.id,attemptId:n.id,targetKind:r.worktreeId?"WORKTREE":"AGENT_HOME",cwd:r.worktree?.folder??null,script:r.snapshotScript},idempotencyKey:`command-run:${r.id}:attempt:${a}`,timeoutSeconds:0,worktreeId:r.worktreeId,codebaseId:r.worktree?.codebaseId??null,visibility:"SYSTEM",blocksGitOperations:r.snapshotBlocksGitOperations})}catch(e){if(!(0,nK.isCodebaseBusyError)(e))throw e;return}n=await t.commandRunAttempt.update({where:{id:n.id},data:{agentJobId:e.id,status:e.status}})}n9(await t.commandRun.update({where:{id:r.id},data:{status:"RUNNING"===n.status?"RUNNING":"QUEUED",startedAt:"RUNNING"===n.status?r.startedAt??new Date:null,nextRestartAt:null,error:null}}))}async failDispatch(e,t){let r=await (0,t1.getPrismaClient)(),i=await r.commandRun.update({where:{id:e},data:{status:"FAILED",error:t,finishedAt:new Date,nextRestartAt:null},include:{worktree:{select:{highlightColor:!0}}}});n9(i),await this.notifyFinishedRun(i)}async terminateRun(e){let t=await (0,t1.getPrismaClient)(),r=await t.commandRun.findUnique({where:{id:e},include:{attempts:{orderBy:{attempt:"desc"},take:1}}});if(!r)throw Error("Command run not found");if(nz.includes(r.status))return r;let i=await t.commandRun.update({where:{id:e},data:{stopRequested:!0,status:"CANCELLING",nextRestartAt:null}}),a=r.attempts[0]?.agentJobId;return nZ(a?await this.agentControl.cancelJob(a):null)||await this.finishCancelled(e),n9(i),this.getRun(e)}async rerun(e){let t=await (0,t1.getPrismaClient)(),r=await t.commandRun.findUnique({where:{id:e}});if(!r)throw Error("Command run not found");let i=await t.commandRun.findUnique({where:{predecessorRunId:r.id}});if(i)return this.getRun(i.id);let a=await t.$transaction(async e=>{let t=await e.commandRunNumberSequence.upsert({where:{id:"default"},create:{id:"default",nextValue:1},update:{nextValue:{increment:1}}});return e.commandRun.create({data:{id:(0,b.randomUUID)(),displayNumber:t.nextValue,commandId:r.commandId,idempotencyKey:`rerun:${r.id}:${(0,b.randomUUID)()}`,origin:"RERUN",snapshotName:r.snapshotName,snapshotDescription:r.snapshotDescription,snapshotScript:r.snapshotScript,snapshotTargetKind:r.snapshotTargetKind,snapshotRestartPolicy:r.snapshotRestartPolicy,snapshotRestartLimit:r.snapshotRestartLimit,snapshotConcurrency:r.snapshotConcurrency,snapshotBlocksGitOperations:r.snapshotBlocksGitOperations,snapshotNotificationsEnabled:r.snapshotNotificationsEnabled,snapshotJson:r.snapshotJson,agentId:r.agentId,worktreeId:r.worktreeId,agentName:r.agentName,agentHostname:r.agentHostname,worktreePath:r.worktreePath,worktreeBranch:r.worktreeBranch,predecessorRunId:r.id}})});return n9(a),nz.includes(r.status)?await this.dispatch(a.id):await this.terminateRun(r.id),this.getRun(a.id)}async archiveRuns(e,t){let r=await (0,t1.getPrismaClient)();for(let i of(await r.commandRun.updateMany({where:{id:{in:e},status:{in:[...nz]}},data:{archivedAt:t?new Date:null}}),e)){let e=await r.commandRun.findUnique({where:{id:i}});e&&n9(e)}return!0}async deleteRuns(e){let t=await (0,t1.getPrismaClient)();return(await t.commandRun.deleteMany({where:{id:{in:e},status:{in:[...nz]}}})).count}async appendOutput(e,t,r,i){if(!i.length||i.length>nG.MAX_COMMAND_OUTPUT_BATCH_CHUNKS)throw Error(`Output batches must contain 1 to ${nG.MAX_COMMAND_OUTPUT_BATCH_CHUNKS} chunks`);let a=await (0,t1.getPrismaClient)(),n=await a.commandRunAttempt.findUnique({where:{id:r},include:{run:!0}});if(!n||n.agentJobId!==t||n.run.agentId!==e)throw Error("Command attempt not found for this agent job");let s=i.map(e=>{if(!Number.isInteger(e.sequence)||e.sequence<0)throw Error("Output sequence must be a non-negative integer");if(!["STDOUT","STDERR","SYSTEM"].includes(e.stream))throw Error("Output stream is invalid");let t=Buffer.from(e.dataBase64,"base64");if(t.length!==e.byteLength||t.length>262144)throw Error("Output byte length is invalid");let r=new Date(e.createdAt);if(Number.isNaN(r.valueOf()))throw Error("Output date is invalid");return{...e,createdAt:r}});await Promise.all(s.map(e=>a.commandRunOutputChunk.upsert({where:{attemptId_sequence:{attemptId:r,sequence:e.sequence}},create:{id:(0,b.randomUUID)(),attemptId:r,...e},update:{}})));let o=await a.commandRunOutputChunk.findMany({where:{attemptId:r,sequence:{in:s.map(e=>e.sequence)}},orderBy:{sequence:"asc"}});for(let e of o){let t={...e,runId:n.runId,attemptNumber:n.attempt};ie.agentEventBus.publish((0,ie.commandRunOutputTopic)(n.runId),{commandRunOutputAdded:t}),ie.agentEventBus.publish(ie.COMMAND_RUN_OUTPUT_CHANGED_TOPIC,{commandRunOutputAdded:t})}return o}async finishCancelled(e){let t=await (0,t1.getPrismaClient)();n9(await t.commandRun.update({where:{id:e},data:{status:"CANCELLED",finishedAt:new Date,nextRestartAt:null}}));let r=await t.commandRun.findUnique({where:{predecessorRunId:e}});r&&await this.dispatch(r.id)}async notifyFinishedRun(e){if(!this.notifications||!e.snapshotNotificationsEnabled||"SUCCEEDED"!==e.status&&"FAILED"!==e.status)return;let t=[e.worktreeBranch??e.worktreePath??`${e.agentName} \xb7 ${e.agentHostname}`,"FAILED"===e.status?e.error:null].filter(e=>!!e).join(" · ").slice(0,1e3);try{let r=await (0,t1.getPrismaClient)(),i=await r.$transaction(r=>this.notifications.recordInTransaction(r,{dedupeKey:`command-run:${e.id}:${e.status}`,typeKey:"SUCCEEDED"===e.status?"COMMAND_RUN_SUCCEEDED":"COMMAND_RUN_FAILED",title:`${e.snapshotName} ${e.status.toLowerCase()}`,body:t,href:`/commands/runs/${e.id}`,resourceKind:"COMMAND_RUN",resourceId:e.id,worktreeId:e.worktreeId,highlightColor:e.worktree?.highlightColor??null}));this.notifications.created(i)}catch(e){console.error("Command run notification failed:",e)}}async handleAttemptCompletion(e){let t=await (0,t1.getPrismaClient)(),r=await t.commandRunAttempt.findUnique({where:{agentJobId:e.id},include:{run:!0,agentJob:!0}});if(!r||r.completionProcessedAt)return;let i=new Date,a=function(e){if(!e)return{};try{let t=JSON.parse(e);return t&&"object"==typeof t?t:{}}catch{return{}}}(e.resultJson);if(1!==(await t.commandRunAttempt.updateMany({where:{id:r.id,completionProcessedAt:null},data:{status:e.status,exitCode:a.exitCode??null,signal:a.signal??null,error:e.error,startedAt:r.agentJob?.startedAt??r.startedAt,finishedAt:r.agentJob?.finishedAt??i,completionProcessedAt:i}})).count)return;if(r.run.stopRequested||"CANCELLED"===e.status)return void await this.finishCancelled(r.runId);let n="SUCCEEDED"===e.status&&0===a.exitCode,s=n3(nV,r.run.snapshotRestartPolicy,"Restart policy"),o=r.agentJob?.startedAt??r.createdAt,l=function(e){if(e.manualStop||!("ALWAYS"===e.policy||"ON_FAILURE"===e.policy&&!e.clean))return{restart:!1,restartCount:e.restartCount,exhausted:!1};let t=(e.durationMs>=6e4?0:e.restartCount)+1,r=null!==e.limit&&t>e.limit;return{restart:!r,restartCount:t,exhausted:r}}({policy:s,limit:r.run.snapshotRestartLimit,restartCount:r.run.restartCount,durationMs:i.getTime()-o.getTime(),clean:n,manualStop:r.run.stopRequested});if(l.restart)return void n9(await t.commandRun.update({where:{id:r.runId},data:{status:"RESTARTING",restartCount:l.restartCount,nextRestartAt:new Date(i.getTime()+1e3),exitCode:a.exitCode??null,signal:a.signal??null,error:e.error}}));let c=await t.commandRun.update({where:{id:r.runId},data:{status:n?"SUCCEEDED":"FAILED",exitCode:a.exitCode??null,signal:a.signal??null,error:e.error??(l.exhausted?"Restart limit reached":n?null:"Command failed"),finishedAt:i,nextRestartAt:null},include:{worktree:{select:{highlightColor:!0}}}});n9(c),await this.notifyFinishedRun(c)}async reconcile(e={}){let t=await (0,t1.getPrismaClient)(),r=new Date;for(let i of(await t.commandRun.findMany({where:{status:{in:[...nJ]},...e.agentId?{agentId:e.agentId}:{}},include:{attempts:{include:{agentJob:!0},orderBy:{attempt:"desc"},take:1}}}))){let e=i.attempts[0];if(i.stopRequested){let t=e?.agentJob??null;t&&nZ(t)?await this.agentControl.cancelJob(t.id):await this.finishCancelled(i.id);continue}if("RESTARTING"===i.status&&(!i.nextRestartAt||i.nextRestartAt<=r)){await this.dispatch(i.id);continue}if(e?.agentJob&&["SUCCEEDED","FAILED","CANCELLED","TIMED_OUT"].includes(e.agentJob.status)){await this.handleAttemptCompletion(e.agentJob);continue}if(e?.agentJob&&["QUEUED","RUNNING"].includes(e.agentJob.status)){let a="RUNNING"===e.agentJob.status?"RUNNING":"QUEUED";e.status!==e.agentJob.status&&await t.commandRunAttempt.update({where:{id:e.id},data:{status:e.agentJob.status,startedAt:e.agentJob.startedAt}}),i.status!==a&&n9(await t.commandRun.update({where:{id:i.id},data:{status:a,startedAt:"RUNNING"===a?i.startedAt??e.agentJob.startedAt??r:i.startedAt}}));continue}"QUEUED"!==i.status||e&&(e.agentJobId||e.completionProcessedAt||e.finishedAt)||await this.dispatch(i.id)}}}var se=e.i(735255);function st(e=new Date){let t=e.getFullYear(),r=String(e.getMonth()+1).padStart(2,"0"),i=String(e.getDate()).padStart(2,"0");return`${t}-${r}-${i}`}class sr{ccusage;diskSpace;polling;usageTimer;usageRunning;constructor(e,t,r){this.ccusage=e,this.diskSpace=t,this.polling=r,this.usageRunning=!1,this.ccusage.registerCompletionObserver(e=>this.recordCompletedUsage(e))}async recordCompletedUsage(e){let t=st(),r=e.aggregate.days.find(e=>e.period===t);await this.persistUsage(t,r?.totalCost??0,new Date)}startRuntime(){this.polling.register({id:"sidebar-usage",kind:"SIDEBAR_USAGE",runtime:"SERVER",enabled:!0,cadenceSeconds:300,details:{}}),this.pruneInterruptedCollections().catch(e=>{console.error("Sidebar usage cleanup failed:",e instanceof Error?e.message:e)}).finally(()=>void this.runUsagePoll())}stopRuntime(){this.usageTimer&&clearTimeout(this.usageTimer),this.usageTimer=void 0}scheduleUsagePoll(){this.usageTimer&&clearTimeout(this.usageTimer);let e=new Date(Date.now()+3e5);this.polling.schedule("sidebar-usage",e),this.usageTimer=setTimeout(()=>void this.runUsagePoll(),3e5),this.usageTimer.unref()}async runUsagePoll(){if(!this.usageRunning){this.usageRunning=!0,this.polling.schedule("sidebar-usage",null);try{await this.polling.run("sidebar-usage",()=>this.collectUsage(),e=>({period:e.period,successfulAgents:e.successfulAgents}))}catch(e){console.error("Sidebar usage refresh failed:",e instanceof Error?e.message:e)}finally{this.usageRunning=!1,this.scheduleUsagePoll()}}}async collectUsage(){if("true"===process.env.SIDEBAR_USAGE_COLLECTION_DISABLED)return{period:st(),successfulAgents:0};let e=`sidebar-usage:${(0,b.randomUUID)()}`;try{let t=await this.ccusage.collect(e);return{period:st(),successfulAgents:t.progress.successfulCount}}finally{await this.removeCollection(e)}}async persistUsage(e,t,r){let i=await (0,t1.getPrismaClient)();await i.sidebarUsageSummary.upsert({where:{id:"default"},create:{id:"default",period:e,totalCost:t,collectedAt:r},update:{period:e,totalCost:t,collectedAt:r}}),this.publish()}async latestSuccessfulUsage(e){let t=await (0,t1.getPrismaClient)(),r=await t.ccusageHistoryState.findUnique({where:{id:"default"},select:{clearedAt:!0}}),i=r?.clearedAt?{OR:[{finishedAt:{gt:r.clearedAt}},{finishedAt:null,createdAt:{gt:r.clearedAt}}]}:{},a=await t.agentJob.findMany({where:{kind:nC.CCUSAGE_REPORT_JOB_KIND,status:"SUCCEEDED",resultJson:{not:null},...i},orderBy:[{finishedAt:"desc"},{createdAt:"desc"}],distinct:["agentId"],select:{resultJson:!0,finishedAt:!0,createdAt:!0,agent:{select:{id:!0,name:!0,hostname:!0}}}}),n=a.flatMap(e=>{try{let t=(0,nC.parseCcusageJobResult)(JSON.parse(e.resultJson));return[{agent:e.agent,report:t.report}]}catch{return[]}});if(!n.length)return null;let s=(0,se.aggregateUsage)(n).days.find(t=>t.period===e);return s?{totalCost:s.totalCost,collectedAt:a.reduce((e,t)=>{let r=t.finishedAt??t.createdAt;return r>e?r:e},new Date(0))}:null}async removeCollection(e){let t=await (0,t1.getPrismaClient)();await t.agentJob.deleteMany({where:{ccusageCollectionId:e}}),await t.ccusageCollection.deleteMany({where:{id:e}})}async pruneInterruptedCollections(){let e=await (0,t1.getPrismaClient)(),t=await e.ccusageCollection.findMany({where:{id:{startsWith:"sidebar-usage:"}},select:{id:!0}});if(!t.length)return;let r=t.map(({id:e})=>e);await e.agentJob.deleteMany({where:{ccusageCollectionId:{in:r}}}),await e.ccusageCollection.deleteMany({where:{id:{in:r}}})}async status(){let e=await (0,t1.getPrismaClient)(),t=st(),[r,i,a,n,s,o,l]=await Promise.all([e.sidebarUsageSummary.findUnique({where:{id:"default"}}),e.agentRun.count({where:{kind:"PLAN",archivedAt:null,status:"IN_PROGRESS",attempts:{some:{status:{in:["STARTING","RUNNING"]},supersededAt:null}}}}),e.agentRun.count({where:{kind:"SESSION",archivedAt:null,status:"IN_PROGRESS",attempts:{some:{status:{in:["STARTING","RUNNING"]},supersededAt:null}}}}),e.build.count({where:{status:{in:["PREPARING","RUNNING"]}}}),e.workflowRun.count({where:{archivedAt:null,status:"RUNNING"}}),e.commandRun.count({where:{archivedAt:null,status:"RUNNING"}}),this.diskSpace.overview()]),c=r?.period===t?{totalCost:r.totalCost,collectedAt:r.collectedAt}:null;if(!c){let e=await this.latestSuccessfulUsage(t);e&&(c=e,this.persistUsage(t,e.totalCost,e.collectedAt)),this.runUsagePoll()}return{usageToday:{totalCost:c?.totalCost??null,collectedAt:c?.collectedAt.toISOString()??null},activity:{plans:i,sessions:a,builds:n,workflows:s,commands:o},diskSpace:l}}subscribe(){return ie.agentEventBus.iterate(ie.SIDEBAR_STATUS_CHANGED_TOPIC)}publish(){ie.agentEventBus.publish(ie.SIDEBAR_STATUS_CHANGED_TOPIC,{sidebarStatusChanged:!0})}}var si=e.i(499162);let sa=`
633
633
  WITH agent_candidates AS (
634
634
  SELECT
635
635
  run.kind AS resourceKind,
@@ -790,7 +790,7 @@ ${t}`,d++;break;case"id":c=t.includes("\0")?void 0:t;break;case"retry":/^\d+$/.t
790
790
  AND acknowledgement.failureFingerprint = candidate.failureFingerprint
791
791
  )
792
792
  )
793
- `;function si(e){return Number(e??0)}async function sa(e,t){let r=t.cursor,[i,a]=await Promise.all([e.$queryRawUnsafe(`${sr}
793
+ `;function sn(e){return Number(e??0)}async function ss(e,t){let r=t.cursor,[i,a]=await Promise.all([e.$queryRawUnsafe(`${sa}
794
794
  SELECT resourceKind, resourceId, reason, key, updatedAt
795
795
  FROM visible
796
796
  WHERE ? = 0
@@ -800,13 +800,13 @@ ${t}`,d++;break;case"id":c=t.includes("\0")?void 0:t;break;case"retry":/^\d+$/.t
800
800
  AND (updatedAt < ? OR (updatedAt = ? AND key > ?))
801
801
  )
802
802
  ORDER BY priority ASC, updatedAt DESC, key ASC
803
- LIMIT ?`,+!!r,r?.priority??0,r?.priority??0,r?.updatedAt??"",r?.updatedAt??"",r?.key??"",t.first+1),e.$queryRawUnsafe(`${sr}
803
+ LIMIT ?`,+!!r,r?.priority??0,r?.priority??0,r?.updatedAt??"",r?.updatedAt??"",r?.key??"",t.first+1),e.$queryRawUnsafe(`${sa}
804
804
  SELECT
805
805
  COUNT(*) AS totalCount,
806
806
  COALESCE(
807
807
  SUM(CASE WHEN reason <> 'ACTIVE' THEN 1 ELSE 0 END),
808
808
  0
809
809
  ) AS needsAttentionCount
810
- FROM visible`)]),n=a[0],s=si(n?.totalCount),o=si(n?.needsAttentionCount);return{rows:i,totalCount:s,needsAttentionCount:o,activeCount:s-o}}let sn=["PLAN","SESSION","BUILD","WORKFLOW"],ss={questions:{orderBy:{position:"asc"},include:{options:{orderBy:{position:"asc"}}}}};function so(e){return e.toISOString()}function sl(e){try{return JSON.parse(e)}catch{return{}}}function sc(e,t,r,i){return[e,t,i??0,r.toISOString()].join(":")}function su(e,t){return{id:e.id,sourceKind:t,createdAt:so(e.createdAt),questions:e.questions}}function sd(e){let t=(0,st.getSessionValue)(sl(e),"worktree.id");return"string"==typeof t&&t?t:null}class sp{async list(e={}){var t,r,i,a,n;let s=await (0,t1.getPrismaClient)(),o=Math.max(1,Math.min(e.first??50,200)),l=await sa(s,{first:o,cursor:function(e){if(!e)return null;try{let t=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));if("number"!=typeof t.priority||"string"!=typeof t.updatedAt||"string"!=typeof t.key)return null;return t}catch{return null}}(e.after)}),c=l.rows.slice(0,o),u=c.flatMap(e=>"PLAN"===e.resourceKind||"SESSION"===e.resourceKind?[e.resourceId]:[]),d=c.flatMap(e=>"WORKFLOW"===e.resourceKind?[e.resourceId]:[]),p=c.flatMap(e=>"BUILD"===e.resourceKind?[e.resourceId]:[]),[h,m,f]=await Promise.all([u.length?s.agentRun.findMany({where:{id:{in:u}},take:u.length,include:{worktree:!0,questionBatches:{where:{status:"PENDING"},orderBy:{createdAt:"asc"},include:ss}}}):Promise.resolve([]),d.length?s.workflowRun.findMany({where:{id:{in:d}},take:d.length,include:{workflow:!0,attempts:{where:{supersededAt:null},include:{questionBatches:{where:{status:"PENDING"},orderBy:{createdAt:"asc"},include:ss}}}}}):Promise.resolve([]),p.length?s.build.findMany({where:{id:{in:p}},take:p.length,include:{worktree:!0,codebase:{include:{repository:!0}},configuration:!0}}):Promise.resolve([])]),g=[...new Set(m.flatMap(e=>sd(e.sessionDataJson)?[sd(e.sessionDataJson)]:[]))],y=new Map((g.length?await s.worktree.findMany({where:{id:{in:g}},select:{id:!0,folder:!0,branch:!0,highlightColor:!0}}):[]).map(e=>[e.id,e])),w=new Map(c.map(e=>[e.key,e.reason])),b=[];for(let e of h){let i=`${e.kind}:${e.id}`,a=w.get(i);if(!a)continue;let n=e.questionBatches.map(e=>su(e,null)),s="FAILED"===a?sc(e.kind,e.id,e.finishedAt??e.updatedAt):null;b.push({key:i,resourceKind:e.kind,reason:a,resourceId:e.id,href:(t=e.kind,r=e.id,`/${"PLAN"===t?"plans":"sessions"}/${encodeURIComponent(r)}`),displayNumber:e.displayNumber,label:function(e,t=220){let r=e.replace(/\s+/g," ").trim();return r.length>t?`${r.slice(0,t-1)}…`:r}(e.initialPrompt),summary:[e.repositoryName,e.branch].filter(Boolean).join(" · ")||null,status:e.status,phase:e.phase,error:e.error,createdAt:so(e.createdAt),updatedAt:so(e.updatedAt),worktree:e.worktree,questionBatches:"QUESTION"===a?n:[],buildRun:null,failureFingerprint:s})}for(let e of m){let t=`WORKFLOW:${e.id}`,r=w.get(t);if(!r)continue;let a=sd(e.sessionDataJson),n=e.attempts.flatMap(e=>e.questionBatches.map(t=>su(t,e.kind))),s="FAILED"===r?sc("WORKFLOW",e.id,e.finishedAt??e.updatedAt,e.generation):null;b.push({key:t,resourceKind:"WORKFLOW",reason:r,resourceId:e.id,href:(i=e.id,`/workflows/runs/${encodeURIComponent(i)}`),displayNumber:e.displayNumber,label:e.workflow.name,summary:e.triggerSubjectKey||null,status:e.status,phase:e.phase,error:e.blockedReason??e.error,createdAt:so(e.createdAt),updatedAt:so(e.updatedAt),worktree:a?y.get(a)??null:null,questionBatches:"QUESTION"===r?n:[],buildRun:null,failureFingerprint:s})}for(let e of f){let t=`BUILD:${e.id}`,r=w.get(t);if(!r)continue;let i="FAILED"===r?sc("BUILD",e.id,e.finishedAt??e.updatedAt):null,n=e.codebase?.repository.name??null,s=e.configuration?.name??null;b.push({key:t,resourceKind:"BUILD",reason:r,resourceId:e.id,href:(a=e.id,`/builds/${encodeURIComponent(a)}`),displayNumber:null,label:s??n??"iOS build",summary:[n,e.worktree?.branch].filter(Boolean).join(" · ")||null,status:e.status,phase:null,error:e.error,createdAt:so(e.createdAt),updatedAt:so(e.updatedAt),worktree:e.worktree,questionBatches:[],buildRun:"UNRUN_BUILD"===r?{buildId:e.id,destinationType:e.destinationType,preferredDestination:sl(e.destinationJson)}:null,failureFingerprint:i})}let v=new Map(b.map(e=>[e.key,e])),k=c.flatMap(e=>v.has(e.key)?[v.get(e.key)]:[]);return{items:k,nextCursor:l.rows.length>o&&k.length?(n=k[k.length-1],Buffer.from(JSON.stringify({priority:function(e){switch(e){case"QUESTION":return 0;case"BLOCKED":return 1;case"FAILED":return 2;case"UNRUN_BUILD":return 3;case"ACTIVE":return 4}}(n.reason),updatedAt:n.updatedAt,key:n.key})).toString("base64url")):null,totalCount:l.totalCount,needsAttentionCount:l.needsAttentionCount,activeCount:l.activeCount}}async acknowledge(e){let t=e.resourceKind.trim().toUpperCase();if(!sn.includes(t))throw Error("Action Center resource kind is invalid");let r=await (0,t1.getPrismaClient)(),i=null;if("PLAN"===t||"SESSION"===t){let a=await r.agentRun.findUnique({where:{id:e.resourceId},select:{id:!0,kind:!0,status:!0,finishedAt:!0,updatedAt:!0}});a?.kind===t&&"FAILED"===a.status&&(i=sc(t,a.id,a.finishedAt??a.updatedAt))}else if("WORKFLOW"===t){let t=await r.workflowRun.findUnique({where:{id:e.resourceId},select:{id:!0,status:!0,generation:!0,finishedAt:!0,updatedAt:!0}});t?.status==="FAILED"&&(i=sc("WORKFLOW",t.id,t.finishedAt??t.updatedAt,t.generation))}else{let t=await r.build.findUnique({where:{id:e.resourceId},select:{id:!0,status:!0,finishedAt:!0,updatedAt:!0}});t?.status==="FAILED"&&(i=sc("BUILD",t.id,t.finishedAt??t.updatedAt))}if(!i||i!==e.failureFingerprint)throw Error("Action Center failure is no longer current");return await r.actionCenterAcknowledgement.upsert({where:{resourceKind_resourceId_failureFingerprint:{resourceKind:t,resourceId:e.resourceId,failureFingerprint:i}},create:{id:(0,b.randomUUID)(),resourceKind:t,resourceId:e.resourceId,failureFingerprint:i},update:{acknowledgedAt:new Date}}),ie.agentEventBus.publish(ie.SIDEBAR_STATUS_CHANGED_TOPIC,{sidebarStatusChanged:!0}),!0}subscribe(){return ie.agentEventBus.iterate(ie.SIDEBAR_STATUS_CHANGED_TOPIC)}}let sh="apps.changed";function sm(e){let t=e.name.trim(),r=e.description?.trim()??"",i=[...new Set(e.agentIds??[])],a=[...new Set(e.repositoryIds)];if(!t)throw Error("App name is required");if(t.length>120)throw Error("App name must be 120 characters or fewer");if(r.length>2e3)throw Error("App description must be 2,000 characters or fewer");if(!a.length)throw Error("Select at least one repository");return{name:t,normalizedName:t.normalize("NFKC").toLocaleLowerCase("en-US"),description:r,agentIds:i,repositoryIds:a}}let sf={repositories:{include:{repository:{include:{codebases:{include:{agent:!0},orderBy:[{folder:"asc"},{id:"asc"}]}}}},orderBy:{createdAt:"asc"}}};class sg{publish(e){ie.agentEventBus.publish(sh,{appsChanged:{id:e}})}subscribe(){return ie.agentEventBus.iterate(sh)}async list(){let e=await (0,t1.getPrismaClient)();return Promise.all((await e.app.findMany({include:sf,orderBy:[{name:"asc"},{id:"asc"}]})).map(e=>this.withCounts(e)))}async get(e){let t=await (0,t1.getPrismaClient)(),r=await t.app.findUnique({where:{id:e},include:sf});return r?this.withCounts(r):null}async create(e){let t=sm(e),r=await (0,t1.getPrismaClient)();await this.assertRepositories(t.repositoryIds),await this.assertUniqueName(t.normalizedName);let i=await r.app.create({data:{id:(0,b.randomUUID)(),name:t.name,normalizedName:t.normalizedName,description:t.description,agentIdsJson:JSON.stringify(t.agentIds),repositories:{create:t.repositoryIds.map(e=>({repositoryId:e}))}},include:sf});return this.publish(i.id),this.withCounts(i)}async update(e){let t=sm(e),r=await (0,t1.getPrismaClient)();if(!await r.app.findUnique({where:{id:e.id}}))throw Error("App not found");await this.assertRepositories(t.repositoryIds),await this.assertUniqueName(t.normalizedName,e.id);let i=await r.$transaction(async r=>(await r.appRepository.deleteMany({where:{appId:e.id}}),r.app.update({where:{id:e.id},data:{name:t.name,normalizedName:t.normalizedName,description:t.description,agentIdsJson:JSON.stringify(t.agentIds),repositories:{create:t.repositoryIds.map(e=>({repositoryId:e}))}},include:sf})));return this.publish(i.id),this.withCounts(i)}async delete(e){let t=await (0,t1.getPrismaClient)();if(!(await t.app.deleteMany({where:{id:e}})).count)throw Error("App not found");return this.publish(e),{id:e}}async assertRepositories(e){let t=await (0,t1.getPrismaClient)();if(await t.codebaseRepository.count({where:{id:{in:e}}})!==e.length)throw Error("One or more repositories could not be found")}async assertUniqueName(e,t){let r=await (0,t1.getPrismaClient)();if(await r.app.findFirst({where:{normalizedName:e,...t?{id:{not:t}}:{}},select:{id:!0}}))throw Error("App names must be unique")}async withCounts(e){let t=await (0,t1.getPrismaClient)(),r=e.repositories.map(e=>e.repositoryId),i={in:r},[a,n,s,o,l,c]=await Promise.all([t.codebase.count({where:{repositoryId:i}}),t.worktree.count({where:{missingAt:null,codebase:{repositoryId:i}}}),t.worktree.count({where:{missingAt:null,codebase:{repositoryId:i},OR:[{hasStagedChanges:!0},{hasUnstagedChanges:!0}]}}),t.agentRun.count({where:{kind:"PLAN",archivedAt:null,repositoryId:i}}),t.agentRun.count({where:{kind:"SESSION",archivedAt:null,repositoryId:i}}),t.build.count({where:{repositoryId:i}})]),{repositories:u,agentIdsJson:d,...p}=e;return{...p,agentIds:this.stringArray(d),repositories:u.map(e=>e.repository),counts:{repositories:r.length,codebases:a,worktrees:n,dirtyWorktrees:s,plans:o,sessions:l,builds:c}}}stringArray(e){try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}catch{return[]}}}let sy=e=>encodeURIComponent(e),sw=e=>e?.toISOString()??null;function sb(e){return e.trim().toLocaleLowerCase().replace(/\s+/g," ")}function sv(e){return sb(e).split(" ").map(e=>e.replace(/^#/,"")).filter(Boolean)}function sk(e,t,r,i=[],a=[]){let n=function(e,t,r=[],i=[]){let a=sb(e).replace(/^#/,""),n=sv(e);if(!a||0===n.length)return null;let s=sb(t),o=r.filter(e=>null!=e).map(e=>sb(String(e)).replace(/^#/,"")),l=i.filter(e=>null!=e).map(e=>sb(String(e))),c=[s,...o,...l].join(" ");return n.every(e=>c.includes(e))?o.includes(a)?1e3:s===a?900:o.some(e=>e.startsWith(a))?800:s.startsWith(a)?700:s.includes(a)?600:l.some(e=>e.startsWith(a))?500:c.includes(a)?400:300+n.filter(e=>s.includes(e)).length:null}(t,r,i,a);return null===n?null:{...e,children:e.children??[],score:n}}function sE(e){return e.filter(e=>null!==e).sort((e,t)=>e.score!==t.score?t.score-e.score:(t.updatedAt??"").localeCompare(e.updatedAt??"")||e.title.localeCompare(t.title))}function sS(e,t){return sE(e).slice(0,t)}function sI(e,t,r){let i=new Set;return sE(e).filter(e=>{let t=r(e);return!i.has(t)&&(i.add(t),!0)}).slice(0,t)}function sA(e){let{score:t,...r}=e;return r}function sx(e){return`github.com/${e.toLocaleLowerCase()}`}function s_(e){let t=e.filter(e=>!!e?.trim());return t.length?t.join(" · "):null}class sC{async search(e,t=5,r=3){let i=e.trim();if(!i)return{items:[]};if(i.length>200)throw Error("query must be at most 200 characters");if(!Number.isInteger(t)||t<1||t>10)throw Error("firstPerGroup must be an integer from 1 to 10");if(!Number.isInteger(r)||r<0||r>5)throw Error("relatedFirst must be an integer from 0 to 5");let a=await (0,t1.getPrismaClient)(),n=[...sv(i)].sort((e,t)=>t.length-e.length)[0]??i,s=Number(i.replace(/^#/,"")),o=Number.isInteger(s)&&s>=0,[l,c,u,d,p,h,m,f,g,y,w,b,v,k,E,S,I,A,x,_]=await Promise.all([a.agent.findMany({where:{OR:[{id:{contains:n}},{name:{contains:n}},{hostname:{contains:n}}]},orderBy:{updatedAt:"desc"},take:100}),a.agentJob.findMany({where:{visibility:"USER",OR:[{id:{contains:n}},{kind:{contains:n}},{status:{contains:n}},{agent:{name:{contains:n}}},{agent:{hostname:{contains:n}}}]},include:{agent:!0},orderBy:{updatedAt:"desc"},take:100}),a.codebaseRepository.findMany({where:{OR:[{id:{contains:n}},{name:{contains:n}},{description:{contains:n}},{canonicalOrigin:{contains:n}},{displayOrigin:{contains:n}}]},orderBy:{updatedAt:"desc"},take:100}),a.codebase.findMany({where:{availability:{not:"MISSING"},OR:[{id:{contains:n}},{folder:{contains:n}},{branch:{contains:n}},{observedOrigin:{contains:n}},{repository:{name:{contains:n}}},{agent:{name:{contains:n}}}]},include:{repository:!0,agent:!0},orderBy:{updatedAt:"desc"},take:100}),a.worktree.findMany({where:{missingAt:null,availability:{not:"MISSING"},OR:[{id:{contains:n}},{folder:{contains:n}},{relativePath:{contains:n}},{branch:{contains:n}},{codebase:{repository:{name:{contains:n}}}},{codebase:{agent:{name:{contains:n}}}},{pullRequest:{title:{contains:n}}},{gitLabMergeRequest:{title:{contains:n}}},...o?[{pullRequest:{number:s}}]:[],...o?[{gitLabMergeRequest:{iid:s}}]:[]]},include:{codebase:{include:{repository:!0,agent:!0}},pullRequest:!0,gitLabMergeRequest:!0},orderBy:{updatedAt:"desc"},take:100}),a.build.findMany({where:{OR:[{id:{contains:n}},{requestId:{contains:n}},{status:{contains:n}},{action:{contains:n}},{commandSummary:{contains:n}},{configuration:{name:{contains:n}}},{worktree:{branch:{contains:n}}},{worktree:{folder:{contains:n}}},{codebase:{repository:{name:{contains:n}}}}]},include:{configuration:!0,worktree:{include:{codebase:{include:{repository:!0}}}},codebase:{include:{repository:!0}}},orderBy:{updatedAt:"desc"},take:100}),a.workflow.findMany({where:{OR:[{id:{contains:n}},{name:{contains:n}},{description:{contains:n}}]},orderBy:{updatedAt:"desc"},take:100}),a.workflowRun.findMany({where:{OR:[{id:{contains:n}},...o?[{displayNumber:s}]:[],{status:{contains:n}},{triggerSubjectKey:{contains:n}},{workflow:{name:{contains:n}}}]},include:{workflow:!0},orderBy:{updatedAt:"desc"},take:100}),a.jiraCachedTicket.findMany({where:{OR:[{issueKey:{contains:n}},{projectKey:{contains:n}},{summaryJson:{contains:n}},{detailJson:{contains:n}}]},orderBy:{updatedAt:"desc"},take:100}),a.worktreePullRequest.findMany({where:{worktree:{missingAt:null},OR:[{githubId:{contains:n}},...o?[{number:s}]:[],{title:{contains:n}},{repositoryNameWithOwner:{contains:n}},{headRefName:{contains:n}},{jiraKey:{contains:n}}]},include:{worktree:!0},orderBy:{updatedAt:"desc"},take:100}),a.gitHubPipelineRecord.findMany({where:{isCurrent:!0,workflowRunId:{not:null},OR:[{githubPipelineId:{contains:n}},{workflowRunId:{contains:n}},{workflowId:{contains:n}},...o?[{runNumber:s}]:[],{name:{contains:n}},{status:{contains:n}},{snapshot:{repositoryNameWithOwner:{contains:n}}}]},include:{snapshot:!0},orderBy:{updatedAt:"desc"},take:100}),a.worktreeGitLabMergeRequest?.findMany({where:{worktree:{missingAt:null},OR:[{gitlabId:{contains:n}},...o?[{iid:s}]:[],{title:{contains:n}},{sourceBranch:{contains:n}},{projectId:{contains:n}}]},include:{worktree:!0},orderBy:{updatedAt:"desc"},take:100})??Promise.resolve([]),a.gitLabPipelineRecord?.findMany({where:{OR:[{pipelineId:{contains:n}},{ref:{contains:n}},{status:{contains:n}},{snapshot:{projectId:{contains:n}}}]},include:{snapshot:!0},orderBy:{updatedAt:"desc"},take:100})??Promise.resolve([]),a.agentRun.findMany({where:{kind:{in:["PLAN","SESSION"]},OR:[{id:{contains:n}},...o?[{displayNumber:s}]:[],{initialPrompt:{contains:n}},{repositoryName:{contains:n}},{branch:{contains:n}},{jiraIssueKey:{contains:n}},{model:{contains:n}},{status:{contains:n}}]},orderBy:{updatedAt:"desc"},take:100}),a.commandDefinition.findMany({where:{OR:[{id:{contains:n}},{name:{contains:n}},{description:{contains:n}},{script:{contains:n}}]},orderBy:{updatedAt:"desc"},take:100}),a.commandRun.findMany({where:{OR:[{id:{contains:n}},...o?[{displayNumber:s}]:[],{snapshotName:{contains:n}},{snapshotDescription:{contains:n}},{agentName:{contains:n}},{worktreeBranch:{contains:n}},{status:{contains:n}}]},orderBy:{updatedAt:"desc"},take:100}),a.skill.findMany({where:{deletedAt:null,OR:[{id:{contains:n}},{name:{contains:n}},{description:{contains:n}}]},orderBy:{updatedAt:"desc"},take:100}),a.skillGroup.findMany({where:{OR:[{id:{contains:n}},{name:{contains:n}}]},orderBy:{updatedAt:"desc"},take:100}),a.iosDevice.findMany({where:{OR:[{id:{contains:n}},{udid:{contains:n}},{displayName:{contains:n}},{product:{contains:n}},{osVersion:{contains:n}},{status:{contains:n}}]},orderBy:{updatedAt:"desc"},take:100}),a.signingProfileAsset.findMany({where:{missingAt:null,OR:[{id:{contains:n}},{uuid:{contains:n}},{name:{contains:n}},{bundleId:{contains:n}},{teamName:{contains:n}},{profileType:{contains:n}}]},include:{agent:!0},orderBy:{observedAt:"desc"},take:100})]),C=[...new Set(w.map(e=>sx(e.snapshot.repositoryNameWithOwner)))],R=new Map([...u,...C.length?await a.codebaseRepository.findMany({where:{canonicalOrigin:{in:C}}}):[]].map(e=>[e.canonicalOrigin.toLocaleLowerCase(),e])),T=sS(p.map(e=>sk({key:`worktree:${e.id}`,kind:"WORKTREE",group:"WORKTREES",title:e.branch??e.relativePath,subtitle:s_([e.codebase.repository.name,e.relativePath,e.codebase.agent.name]),href:`/worktrees/${sy(e.id)}`,status:e.availability,updatedAt:sw(e.updatedAt)},i,e.branch??e.relativePath,[e.id,e.branch,e.pullRequest?.number],[e.folder,e.relativePath,e.codebase.repository.name,e.codebase.agent.name,e.pullRequest?.title,e.gitLabMergeRequest?.title])),t),D=sS(m.map(e=>sk({key:`workflow:${e.id}`,kind:"WORKFLOW",group:"WORKFLOWS",title:e.name,subtitle:e.description||null,href:`/workflows/${sy(e.id)}`,status:e.archivedAt?"ARCHIVED":e.enabled?"ENABLED":"DISABLED",updatedAt:sw(e.updatedAt)},i,e.name,[e.id],[e.description])),t);r>0&&(await this.attachWorktreeChildren(T,r),await this.attachWorkflowChildren(D,r));let N=new Set([...T,...D].flatMap(e=>e.children.map(e=>e.key))),O=sS(g.map(e=>{let t,r,a,n=(a=(r=(t=function(e){if(!e)return{};try{let t=JSON.parse(e);return t&&"object"==typeof t&&!Array.isArray(t)?t:{}}catch{return{}}}(e.detailJson??e.summaryJson)).fields&&"object"==typeof t.fields&&!Array.isArray(t.fields)?t.fields:{}).status&&"object"==typeof r.status&&!Array.isArray(r.status)?r.status:{},{summary:"string"==typeof r.summary?r.summary:null,status:"string"==typeof a.name?a.name:null});return sk({key:`ticket:${e.issueKey}`,kind:"JIRA_TICKET",group:"TICKETS",title:n.summary?`${e.issueKey} \xb7 ${n.summary}`:e.issueKey,subtitle:e.projectKey,href:`/jira/tickets/${sy(e.issueKey)}`,status:n.status,updatedAt:sw(e.updatedAt)},i,n.summary??e.issueKey,[e.issueKey],[e.projectKey,n.status])}),t),P=sI(y.map(e=>{let[t,...r]=e.repositoryNameWithOwner.split("/"),a=r.join("/");return t&&a?sk({key:`pull-request:${e.repositoryNameWithOwner}:${e.number}`,kind:"GITHUB_PULL_REQUEST",group:"PULL_REQUESTS",title:`${e.repositoryNameWithOwner} #${e.number} \xb7 ${e.title}`,subtitle:s_([e.headRefName,e.jiraKey]),href:`/pull-requests/${sy(t)}/${sy(a)}/${e.number}`,status:e.state,updatedAt:sw(e.updatedAt)},i,e.title,[e.number,`#${e.number}`,e.githubId,e.jiraKey],[e.repositoryNameWithOwner,e.headRefName]):null}),t,e=>e.key.toLocaleLowerCase()),L=sI(b.map(e=>sk({key:`gitlab-merge-request:${e.projectId}:${e.iid}`,kind:"GITLAB_MERGE_REQUEST",group:"PULL_REQUESTS",title:`!${e.iid} \xb7 ${e.title}`,subtitle:e.sourceBranch,href:`/gitlab/merge-requests/${sy(e.projectId)}/${e.iid}`,status:e.state,updatedAt:sw(e.updatedAt)},i,e.title,[e.iid,`!${e.iid}`,e.gitlabId],[e.projectId,e.sourceBranch])),t,e=>e.key.toLocaleLowerCase()),B=sS(u.map(e=>sk({key:`repository:${e.id}`,kind:"REPOSITORY",group:"REPOSITORIES",title:e.name,subtitle:e.displayOrigin,href:`/codebases/repositories/${sy(e.id)}`,status:null,updatedAt:sw(e.updatedAt)},i,e.name,[e.id],[e.displayOrigin,e.canonicalOrigin,e.description])),t),U=sS(d.map(e=>sk({key:`codebase:${e.id}`,kind:"CODEBASE",group:"CODEBASES",title:e.folder,subtitle:s_([e.repository.name,e.branch,e.agent.name]),href:`/codebases/${sy(e.id)}`,status:e.availability,updatedAt:sw(e.updatedAt)},i,e.folder,[e.id,e.branch],[e.observedOrigin,e.repository.name,e.agent.name])),t),j=sS(f.map(e=>sk({key:`workflow-run:${e.id}`,kind:"WORKFLOW_RUN",group:"WORKFLOWS",title:`${e.workflow.name} #${e.displayNumber}`,subtitle:e.triggerSubjectKey||null,href:`/workflows/runs/${sy(e.id)}`,status:e.status,updatedAt:sw(e.updatedAt)},i,e.workflow.name,[e.id,e.displayNumber,`#${e.displayNumber}`],[e.status,e.triggerSubjectKey])).filter(e=>!e||!N.has(e.key)),t),M=sS(w.map(e=>{let t=R.get(sx(e.snapshot.repositoryNameWithOwner)),r=new URLSearchParams;return t&&r.set("repository",t.id),e.workflowId&&r.set("pipeline",e.workflowId),sk({key:`github-actions:${e.id}`,kind:"GITHUB_ACTIONS_RUN",group:"GITHUB_ACTIONS",title:`${e.name}${e.runNumber?` #${e.runNumber}`:""}`,subtitle:e.snapshot.repositoryNameWithOwner,href:`/actions${r.size?`?${r.toString()}`:""}`,status:e.status,updatedAt:sw(e.updatedAt)},i,e.name,[e.githubPipelineId,e.workflowRunId,e.workflowId,e.runNumber],[e.snapshot.repositoryNameWithOwner,e.status])}),t),q=sS(v.map(e=>sk({key:`gitlab-pipeline:${e.snapshot.projectId}:${e.pipelineId}`,kind:"GITLAB_PIPELINE",group:"GITLAB_PIPELINES",title:`Pipeline #${e.pipelineId}`,subtitle:e.ref,href:`/gitlab/pipelines?project=${sy(e.snapshot.projectId)}&pipeline=${sy(e.pipelineId)}`,status:e.status,updatedAt:sw(e.updatedAt)},i,`Pipeline #${e.pipelineId}`,[e.pipelineId],[e.snapshot.projectId,e.ref,e.status])),t),$=sS(h.map(e=>{let t=e.worktree?.codebase.repository??e.codebase?.repository;return sk({key:`build:${e.id}`,kind:"BUILD",group:"BUILDS",title:e.configuration?.name??`${e.action} build`,subtitle:s_([t?.name,e.worktree?.branch,e.id.slice(0,8)]),href:`/builds/${sy(e.id)}`,status:e.status,updatedAt:sw(e.updatedAt)},i,e.configuration?.name??`${e.action} build`,[e.id,e.requestId],[e.action,e.status,e.commandSummary,t?.name,e.worktree?.branch,e.worktree?.folder])}).filter(e=>!e||!N.has(e.key)),t),F=sS(l.map(e=>sk({key:`agent:${e.id}`,kind:"AGENT",group:"AGENTS_JOBS",title:e.name,subtitle:e.hostname,href:`/agents/${sy(e.id)}`,status:e.disconnectedAt?"OFFLINE":null,updatedAt:sw(e.updatedAt)},i,e.name,[e.id],[e.hostname])),t),G=sS(c.map(e=>sk({key:`agent-job:${e.id}`,kind:"AGENT_JOB",group:"AGENTS_JOBS",title:e.kind,subtitle:s_([e.agent.name,e.id.slice(0,8)]),href:`/jobs/${sy(e.id)}`,status:e.status,updatedAt:sw(e.updatedAt)},i,e.kind,[e.id],[e.status,e.agent.name,e.agent.hostname])),t),K=sS(k.map(e=>{let t="PLAN"===e.kind?"PLAN":"SESSION";return sk({key:`${t.toLocaleLowerCase()}:${e.id}`,kind:t,group:"PLANS_SESSIONS",title:`${"PLAN"===t?"Plan":"Session"} #${e.displayNumber}`,subtitle:s_([e.repositoryName,e.branch,e.initialPrompt.slice(0,100)]),href:`/${"PLAN"===t?"plans":"sessions"}/${sy(e.id)}`,status:e.status,updatedAt:sw(e.updatedAt)},i,e.initialPrompt,[e.id,e.displayNumber,`#${e.displayNumber}`,e.jiraIssueKey],[e.repositoryName,e.branch,e.model,e.status])}),t),H=sS(E.map(e=>sk({key:`command:${e.id}`,kind:"COMMAND",group:"COMMANDS_RUNS",title:e.name,subtitle:e.description||null,href:`/commands/${sy(e.id)}/edit`,status:e.archivedAt?"ARCHIVED":null,updatedAt:sw(e.updatedAt)},i,e.name,[e.id],[e.description,e.script])),t),V=sS(S.map(e=>sk({key:`command-run:${e.id}`,kind:"COMMAND_RUN",group:"COMMANDS_RUNS",title:`${e.snapshotName} #${e.displayNumber}`,subtitle:s_([e.agentName,e.worktreeBranch]),href:`/commands/runs/${sy(e.id)}`,status:e.status,updatedAt:sw(e.updatedAt)},i,e.snapshotName,[e.id,e.displayNumber,`#${e.displayNumber}`],[e.snapshotDescription,e.agentName,e.worktreeBranch,e.status])),t),W=sS(I.map(e=>sk({key:`skill:${e.id}`,kind:"SKILL",group:"SKILLS",title:e.name,subtitle:e.description,href:`/skills/${sy(e.id)}`,status:null,updatedAt:sw(e.updatedAt)},i,e.name,[e.id],[e.description])),t),J=sS(A.map(e=>sk({key:`skill-group:${e.id}`,kind:"SKILL_GROUP",group:"SKILLS",title:e.name,subtitle:null,href:`/skills/groups/${sy(e.id)}`,status:null,updatedAt:sw(e.updatedAt)},i,e.name,[e.id])),t),z=sS(x.map(e=>sk({key:`device:${e.id}`,kind:"DEVICE",group:"DEVICES_PROFILES",title:e.displayName,subtitle:s_([e.product,e.osVersion]),href:`/devices/${sy(e.id)}`,status:e.status,updatedAt:sw(e.updatedAt)},i,e.displayName,[e.id,e.udid],[e.product,e.osVersion,e.status])),t),Y=sS(_.map(e=>sk({key:`profile:${e.id}`,kind:"PROVISIONING_PROFILE",group:"DEVICES_PROFILES",title:e.name,subtitle:s_([e.bundleId,e.teamName,e.agent.name]),href:`/provisioning-profiles/${sy(e.id)}`,status:e.expired?"EXPIRED":e.profileType,updatedAt:sw(e.observedAt)},i,e.name,[e.id,e.uuid],[e.bundleId,e.teamName,e.profileType,e.agent.name])),t);return{items:[...T,...O,...P,...L,...B,...U,...sS([...D,...j],t),...M,...q,...$,...sS([...F,...G],t),...K,...sS([...H,...V],t),...sS([...W,...J],t),...sS([...z,...Y],t)].map(sA)}}async attachWorktreeChildren(e,t){if(!e.length)return;let r=await (0,t1.getPrismaClient)(),i=e.map(e=>e.key.slice(9)),a=new Map(await Promise.all(i.map(async e=>{let[i,a]=await Promise.all([r.workflowRun.findMany({where:{resourceLinks:{some:{kind:"WORKTREE",resourceId:e}}},include:{workflow:!0},orderBy:{createdAt:"desc"},take:t}),r.build.findMany({where:{worktreeId:e},include:{configuration:!0},orderBy:{createdAt:"desc"},take:t})]);return[e,{runs:i,builds:a}]})));for(let r of e){let e=r.key.slice(9),i=a.get(e);r.children=[...(i?.runs??[]).slice(0,t).map(e=>({key:`workflow-run:${e.id}`,kind:"WORKFLOW_RUN",group:"WORKFLOWS",title:`${e.workflow.name} #${e.displayNumber}`,subtitle:null,href:`/workflows/runs/${sy(e.id)}`,status:e.status,updatedAt:sw(e.updatedAt),children:[]})),...(i?.builds??[]).slice(0,t).map(e=>({key:`build:${e.id}`,kind:"BUILD",group:"BUILDS",title:e.configuration?.name??`${e.action} build`,subtitle:e.id.slice(0,8),href:`/builds/${sy(e.id)}`,status:e.status,updatedAt:sw(e.updatedAt),children:[]}))]}}async attachWorkflowChildren(e,t){if(!e.length)return;let r=await (0,t1.getPrismaClient)(),i=e.map(e=>e.key.slice(9)),a=new Map(await Promise.all(i.map(async e=>[e,await r.workflowRun.findMany({where:{workflowId:e},include:{workflow:!0},orderBy:{createdAt:"desc"},take:t})])));for(let r of e){let e=r.key.slice(9);r.children=(a.get(e)??[]).slice(0,t).map(e=>({key:`workflow-run:${e.id}`,kind:"WORKFLOW_RUN",group:"WORKFLOWS",title:`${e.workflow.name} #${e.displayNumber}`,subtitle:e.triggerSubjectKey||null,href:`/workflows/runs/${sy(e.id)}`,status:e.status,updatedAt:sw(e.updatedAt),children:[]}))}}}var sR=e.i(642582),sT=e.i(524214),sD=e.i(169349);let sN="default",sO=["QUEUED","RUNNING","CANCELLING"],sP=[{id:"builtin-acli-jira",name:"Atlassian Jira",command:"acli jira auth status",builtIn:!0},{id:"builtin-acli",name:"Atlassian CLI",command:"acli auth status",builtIn:!0},{id:"builtin-claude",name:"Claude",command:"claude auth status",builtIn:!0},{id:"builtin-codex",name:"Codex",command:"codex login status",builtIn:!0},{id:"builtin-opencode",name:"OpenCode",command:"opencode auth list",builtIn:!0}],sL={id:"builtin-github",name:"GitHub",command:"gh auth status",builtIn:!0},sB={id:"builtin-gitlab",name:"GitLab",command:"glab auth status",builtIn:!0};function sU(e){try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}catch{return[]}}function sj(e){return!!(e.lastSeenAt&&Date.now()-e.lastSeenAt.getTime()<=(0,a.agentOnlineWindowMs)(e)&&null===e.disconnectedAt)}class sM{agentControl;gitHub;gitLab;startingAgents;constructor(e,t,r){this.agentControl=e,this.gitHub=t,this.gitLab=r,this.startingAgents=new Set,this.agentControl.registerCompletionObserver(async e=>{e.kind===sR.CLI_HEALTH_JOB_KIND&&this.publish(e.agentId)})}publish(e){ie.agentEventBus.publish(ie.CLI_HEALTH_CHANGED_TOPIC,{cliHealthStatusChanged:{agentId:e}})}async customChecks(){let e=await (0,t1.getPrismaClient)(),t=await e.cliHealthSettings.findUnique({where:{id:sN}});var r=t?.checksJson;try{let e=JSON.parse(r||"[]");if(!Array.isArray(e))return[];return e.filter(e=>!!(e&&"object"==typeof e&&"string"==typeof e.id&&"string"==typeof e.name&&"string"==typeof e.command&&"boolean"==typeof e.enabled))}catch{return[]}}async definitions(){let[e,t,r]=await Promise.all([this.customChecks(),this.gitHub.getSettings(),this.gitLab.getSettings()]);return{checks:[...sP,...t.tokenConfigured?[sL]:[],...r.configured?[sB]:[],...e.filter(e=>e.enabled).map(({enabled:e,...t})=>({...t,builtIn:!1}))],customChecks:e}}resultViews(e,t){let r=new Map((t?.checks??[]).map(e=>[e.id,e]));return e.map(e=>{let t=r.get(e.id);return t&&t.command===e.command?{...t,...e,state:0!==t.exitCode||t.timedOut||t.launchError?"UNHEALTHY":"HEALTHY"}:{...e,state:"NOT_RUN",exitCode:null,stdout:"",stderr:"",durationMs:null,checkedAt:null,timedOut:!1,launchError:null,outputTruncated:!1}})}async agentStatus(e,t){let r=await (0,t1.getPrismaClient)(),i=t??(await this.definitions()).checks,[a,n]=await Promise.all([r.agentJob.findFirst({where:{agentId:e.id,kind:sR.CLI_HEALTH_JOB_KIND,status:{in:sO}},orderBy:{createdAt:"desc"}}),r.agentJob.findFirst({where:{agentId:e.id,kind:sR.CLI_HEALTH_JOB_KIND,status:"SUCCEEDED"},orderBy:{finishedAt:"desc"}})]),s=sU(e.capabilitiesJson).includes(sR.CLI_HEALTH_JOB_KIND),o=this.resultViews(i,function(e){if(!e)return null;try{let t=JSON.parse(e);return Array.isArray(t.checks)?t:null}catch{return null}}(n?.resultJson??null)),l=o.filter(e=>"NOT_RUN"!==e.state),c=s?a?"RUNNING":0===l.length?"NOT_CHECKED":l.length===o.length&&l.every(e=>"HEALTHY"===e.state)?"HEALTHY":"ISSUES":"UNSUPPORTED";return{agentId:e.id,name:e.name,hostname:e.hostname,version:e.version,connectionStatus:sj(e)?"ONLINE":"OFFLINE",supported:s,activeJobId:a?.id??null,lastCheckedAt:n?.finishedAt?.toISOString()??null,overall:c,results:o}}async installationStatus(){let[{checks:e,customChecks:t},r]=await Promise.all([this.definitions(),this.agentControl.listAgents()]);return{version:process.env.AIDE_VERSION||sT.default.version,dependencies:[{name:"Next.js",version:sT.default.dependencies.next},{name:"Claude SDK",version:sD.default.dependencies["@anthropic-ai/claude-agent-sdk"]},{name:"Codex SDK",version:sD.default.dependencies["@openai/codex-sdk"]},{name:"OpenCode SDK",version:sD.default.dependencies["@opencode-ai/sdk"]}],customChecks:t,agents:await Promise.all(r.map(t=>this.agentStatus(t,e)))}}async statusForAgent(e){let t=await this.agentControl.getAgent(e);if(!t)throw Error("Agent not found");return this.agentStatus(t)}async run(e){let[{checks:t},r]=await Promise.all([this.definitions(),this.agentControl.listAgents()]),i=e?r.filter(t=>t.id===e):r;if(e&&0===i.length)throw Error("Agent not found");let a=i.filter(e=>sj(e)&&sU(e.capabilitiesJson).includes(sR.CLI_HEALTH_JOB_KIND));return await Promise.all(a.map(async e=>{if(!this.startingAgents.has(e.id)){this.startingAgents.add(e.id);try{if((await this.agentStatus(e,t)).activeJobId)return;await this.agentControl.createJob({agentId:e.id,kind:sR.CLI_HEALTH_JOB_KIND,payload:{checks:t},idempotencyKey:`cli-health:${(0,b.randomUUID)()}`,timeoutSeconds:600,visibility:"SYSTEM"}),this.publish(e.id)}finally{this.startingAgents.delete(e.id)}}})),this.installationStatus()}async saveSettings(e){let t=function(e){if(e.length>20)throw Error("At most 20 custom CLI health checks are allowed");let t=new Set,r=new Set;return e.map(e=>{let i=e.name?.trim()??"",a=e.command?.trim()??"",n=e.id?.trim()||(0,b.randomUUID)();if(!i||i.length>100||i.includes("\0"))throw Error("Check names must be between 1 and 100 characters and cannot contain NUL characters");if(!a||a.length>4096||a.includes("\0"))throw Error("Check commands must be between 1 and 4096 characters and cannot contain NUL characters");let s=i.toLocaleLowerCase();if(t.has(s))throw Error("Custom check names must be unique");if(n.length>100||n.includes("\0")||n.startsWith("builtin-")||r.has(n))throw Error("Custom check identifiers must be unique and valid");return t.add(s),r.add(n),{id:n,name:i,command:a,enabled:!1!==e.enabled}})}(e),r=await (0,t1.getPrismaClient)();return await r.cliHealthSettings.upsert({where:{id:sN},create:{id:sN,checksJson:JSON.stringify(t)},update:{checksJson:JSON.stringify(t)}}),this.publish(null),this.installationStatus()}}function sq(e,t,r){let i=e.trim().toLowerCase(),a=t.trim().toLowerCase();if(!i||!a)throw Error("Pull request repository coordinates are required");if(!Number.isInteger(r)||r<1)throw Error("Pull request number must be a positive integer");return`${i}/${a}#${r}`}function s$(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}function sF(e,t,r){return s$(e[t])[r]}function sG(e,t,r={}){if("string"!=typeof t&&"number"!=typeof t)return null;let i=String(t).trim();return i?{kind:e,resourceId:i,...r}:null}let sK=new Set(["JIRA_STATUS","JIRA_LABEL","JIRA_ASSIGNED_SELF","JIRA_SOURCE_NEW_TICKET","JIRA_MENTION","JIRA_SPRINT_STARTED","JIRA_TICKET_UPDATED","JIRA_COMMENT_ADDED","JIRA_WORKLOG_ADDED","JIRA_SPRINT_ENDED","JIRA_ISSUE_CREATED","JIRA_ISSUE_DELETED","JIRA_ISSUE_COMMAND","JIRA_ATTACHMENT_ADDED","JIRA_ISSUE_LINKED"]),sH=new Set(["RUN_STARTED","RUN_COMPLETED","RUN_QUESTION_NEEDED","RUN_QUESTION_ANSWERED","RUN_PAUSED","RUN_CONTINUED","RUN_FAILED","RUN_CANCELLED","RUN_PLAN_PLAYED","RUN_FOLLOW_UP","RUN_IMPORTED","RUN_USAGE_THRESHOLD","RUN_EVENT_MATCH"]),sV=new Set(["BUILD_RESULT","BUILD_TEST_THRESHOLD","BUILD_COVERAGE_THRESHOLD","BUILD_HOOK_FAILED"]),sW=new Set(["WORKTREE_CREATED","WORKTREE_BEHIND","WORKTREE_CONFLICT","WORKTREE_MISSING","WORKTREE_DIVERGED","WORKTREE_DIRTY_DURATION","WORKTREE_NEW_COMMIT","WORKTREE_SYNC_STATE_CHANGED","WORKTREE_AUTOMATION_RESULT","WORKTREE_CLEAN"]),sJ=new Set(["GITHUB_PR_STATE","GITHUB_REVIEW_CHANGES_REQUESTED","GITHUB_REVIEW_COMMENT","GITHUB_PR_CLOSED","GITHUB_ISSUE_COMMAND","GITHUB_PR_LABEL","GITHUB_PR_SYNCHRONIZED","GITHUB_REVIEW_APPROVED","GITLAB_MR_STATE","GITLAB_REVIEW_CHANGES_REQUESTED","GITLAB_REVIEW_COMMENT","GITLAB_MR_CLOSED","GITLAB_NOTE_COMMAND","GITLAB_MR_LABEL","GITLAB_MR_SYNCHRONIZED","GITLAB_REVIEW_APPROVED"]),sz=new Set(["GITHUB_CHECK_FAILED","GITHUB_WORKFLOW_SUCCEEDED","GITHUB_ACTIONS_RESULT","GITHUB_PIPELINE_STATUS_CHANGED","GITLAB_PIPELINE_FAILED","GITLAB_PIPELINE_SUCCEEDED","GITLAB_PIPELINE_RESULT","GITLAB_PIPELINE_STATUS_CHANGED","GITLAB_JOB_STATUS_CHANGED"]);var sY=e.i(361617),sZ=e.i(483291);let sQ=["","aa"," ","a a","a\na"," a","a "];function sX(e,t=!1){(0,sY.validateCommandOutputPattern)(e);try{let r=(0,sZ.compileRe2)(e,{flags:t?"g":"",label:"Output pattern"});for(let t of sQ){let r=(0,sZ.compileRe2)(e,{flags:"y",label:"Output pattern"});for(let e=0;e<=t.length;e+=1){r.lastIndex=e;let i=r.exec(t);if(i?.index===e&&i[0]?.length===0)throw Error("Output pattern must consume at least one character")}}return r}catch(e){if(e instanceof Error&&"Output pattern must consume at least one character"===e.message||e instanceof Error)throw e;throw Error(`Output pattern is not valid RE2 syntax: ${String(e)}`)}}function s0(e,t){let r="string"==typeof e?Number(e.trim()):e;return"number"!=typeof r||!Number.isFinite(r)||r<=0?null:Math.min(31536e3,Math.max(t,r))}function s1(e,t=null){let r=s0(e.timeoutSeconds,10)??(null===t?null:s0(t,10));return null===r?null:new Date(Date.now()+1e3*r)}function s2(e,t){return s0(e.cadenceSeconds,1)??Math.max(1,t)}function s3(e,t=1){return new Date(Date.now()+1e3*s2(e,t))}function s4(e){return e.toLowerCase().replaceAll("_"," ")}let s6=(e,t)=>{if(!e||"object"!=typeof e||Array.isArray(e))throw Error(`${t} must be an object`);return e},s8=(e,t,r=2e4)=>{if("string"!=typeof e||!e.trim())throw Error(`${t} is required`);if(e.length>r)throw Error(`${t} is too long`);return e.trim()},s5=(e,t=2e4)=>null==e||""===e?null:s8(e,"Value",t),s9=(e,t,r,i)=>s8(e.node.config[t]??(0,st.getSessionValue)(e.sessionData,r),i,500),s7=(e,t="operation")=>`${e.run.id}:${e.attempt.id}:${t}`,oe=(e,t,r=!1)=>({output:t,sessionPatch:{run:{[e.node.id]:t}},links:"string"==typeof t.id?[{kind:"AGENT_RUN",resourceId:t.id,label:"string"==typeof t.kind?t.kind:"Agent run",url:`/${"PLAN"===t.kind?"plans":"sessions"}/${t.id}`,metadata:{runKind:t.kind}}]:void 0,wait:r&&"string"==typeof t.id?{kind:"AGENT_RUN",externalKey:t.id,resumeAfter:s3(e.node.config),timeoutAt:s1(e.node.config)}:void 0}),ot=(e,t,r,i=[])=>({output:{jobId:t.id},sessionPatch:r,links:[...i,{kind:"AGENT_JOB",resourceId:t.id,label:"Agent job",url:`/jobs/${t.id}`}],wait:{kind:"AGENT_JOB",externalKey:t.id,resumeAfter:s3(e.node.config),timeoutAt:s1(e.node.config,t.timeoutSeconds??3600)}}),or=(e,t,r,i,a)=>({kind:e,resourceId:t,label:r,url:i,metadata:a}),oi=(e,t)=>or("JIRA_TICKET",e,t??e);function oa(e,t,r){let i=oc(e);return or("PULL_REQUEST",sq(i.owner,i.name,om(e)),t??"Pull request",r)}function on(e){let t=ol(e),r=oh(e);return t&&r?or("PULL_REQUEST",sq(t.owner,t.name,r),"Pull request"):null}function os(e){let t=e.node.config.workflowRunId??(0,st.getSessionValue)(e.sessionData,"pipeline.runId"),r=(0,st.getSessionValue)(e.sessionData,"pipeline.url");return("string"==typeof t||"number"==typeof t)&&"string"==typeof r&&r?or("GITHUB_WORKFLOW_RUN",String(t),"Workflow run",r):null}function oo(e){let t=(0,st.getSessionValue)(e.sessionData,"run.kind");if("PLAN"!==t&&"SESSION"!==t)return null;let r=function(e){try{return ov(e)}catch{return null}}(e);return r?or("AGENT_RUN",r,t,`/${"PLAN"===t?"plans":"sessions"}/${r}`,{runKind:t}):null}function ol(e){let t=e.node.config.owner,r=e.node.config.name;if("string"==typeof t&&t.trim()&&"string"==typeof r&&r.trim())return{owner:t.trim(),name:r.trim()};let i=e.sessionData.repo&&"object"==typeof e.sessionData.repo&&!Array.isArray(e.sessionData.repo)?e.sessionData.repo.displayOrigin:null,a="string"==typeof i?i.match(/(?:https?:\/\/)?github\.com[/:]([^/]+)\/([^/.]+)(?:\.git)?$/i):null,n=a?.[1]?.trim(),s=a?.[2]?.trim();return n&&s?{owner:n,name:s}:null}function oc(e){let t=ol(e);if(!t)throw Error("GitHub owner and repository are required");return t}function ou(e){let t=s6(e,"Jira ticket"),r=t.issueType&&"object"==typeof t.issueType?t.issueType:{},i=t.status&&"object"==typeof t.status?t.status:{};return{...t,key:t.key,title:t.summary??t.title,type:r.name??t.type,status:i.name??t.status,statusCategory:i.category??t.statusCategory}}function od(e){let t=s6(e,"Pull request"),r=Array.isArray(t.reviewThreads)?t.reviewThreads:[];return{...t,headBranch:t.headRefName,headSha:t.headRefOid,merged:"MERGED"===t.state,unresolvedThreads:r.filter(e=>e&&"object"==typeof e&&!Array.isArray(e)&&!0!==e.isResolved)}}function op(e){return s8(e.node.config.issueKey??(0,st.getSessionValue)(e.sessionData,"ticket.key"),"Jira issue key",100)}function oh(e){let t=e.node.config.number??(0,st.getSessionValue)(e.sessionData,"pr.number"),r="string"==typeof t?Number(t):t;return"number"==typeof r&&Number.isInteger(r)&&r>=1?r:null}function om(e){let t=oh(e);if(!t)throw Error("Pull request number is required");return t}function of(e){return s9(e,"worktreeId","worktree.id","Worktree ID")}function og(e){return s9(e,"codebaseId","codebase.id","Codebase ID")}function oy(e){let t=String(e.node.config.mode??"NEW").toUpperCase();if(!new Set(["NEW","EXISTING","TICKET"]).has(t))throw Error("Worktree branch mode must be NEW, EXISTING, or TICKET");return{mode:t,branchName:"TICKET"===t?null:s5(e.node.config.branchName??(0,st.getSessionValue)(e.sessionData,"worktree.branch"),500),ticketKey:"TICKET"===t?s5(e.node.config.ticketKey??(0,st.getSessionValue)(e.sessionData,"ticket.key"),100):null,baseBranch:s8(e.node.config.baseBranch??(0,st.getSessionValue)(e.sessionData,"worktree.baseBranch")??(0,st.getSessionValue)(e.sessionData,"repo.defaultBranch"),"Base branch",500)}}function ow(e){return s9(e,"buildId","build.id","Build ID")}function ob(e){return s8(e.node.config.agentId??(0,st.getSessionValue)(e.sessionData,"agent.id")??(0,st.getSessionValue)(e.sessionData,"codebase.agentId"),"Agent ID",500)}function ov(e){let t=e.node.config.runId;if("string"==typeof t&&t)return t;let r=e.node.config.sourceStepId;return"string"==typeof r?s8((0,st.getSessionValue)(e.sessionData,`run.${r}.id`),"Agent run ID",500):s8((0,st.getSessionValue)(e.sessionData,"run.id"),"Agent run ID",500)}function ok(e,t){let r,i,a=e.node.config.worktreeConcurrencyLimit;return{kind:t,worktreeId:(r=e.node.config.worktreeId,i=(0,st.getSessionValue)(e.sessionData,"worktree.id"),"string"==typeof r&&r===e.run.workflowId&&"string"==typeof i&&i!==r?s8(i,"Worktree ID",500):of(e)),jiraIssueKey:s5(e.node.config.jiraIssueKey??(0,st.getSessionValue)(e.sessionData,"ticket.key"),100),provider:s8(e.node.config.provider??"CODEX","Provider",50),model:s8(e.node.config.model,"Model",200),effort:s5(e.node.config.effort,50),webSearchEnabled:!0===e.node.config.webSearchEnabled,prompt:s8(e.node.config.prompt,"Prompt",2e5),attachmentIds:Array.isArray(e.node.config.attachmentIds)?e.node.config.attachmentIds.map(String):[],mcpPresetIds:Array.isArray(e.node.config.mcpPresetIds)?e.node.config.mcpPresetIds.map(String):[],worktreeConcurrencyLimit:"number"==typeof a?a:void 0,workflowRunId:e.run.id}}class oE{nextMaintenanceAt=0;async record(e){let t=await (0,t1.getPrismaClient)();return await t.workflowTrigger.findFirst({where:{kind:e.kind,version:{activeFor:{is:{enabled:!0,archivedAt:null}}}},select:{id:!0}})?this.recordInTransaction(t,e):null}async recordInTransaction(e,t){let r=await e.workflowTriggerEvent.findUnique({where:{dedupeKey:t.dedupeKey}});return r||e.workflowTriggerEvent.create({data:{id:(0,b.randomUUID)(),kind:t.kind,subjectKey:t.subjectKey,dedupeKey:t.dedupeKey,payloadJson:JSON.stringify(t.payload)}})}async maintain(){let e=Date.now();if(e<this.nextMaintenanceAt)return;let t=await (0,t1.getPrismaClient)(),r=await t.workflowTriggerEvent.findMany({where:{status:"FAILED",receivedAt:{lt:new Date(e-6048e5)}},select:{id:!0},orderBy:{receivedAt:"asc"},take:1e3});if(r.length){await t.workflowTriggerEvent.deleteMany({where:{id:{in:r.map(({id:e})=>e)}}}),this.nextMaintenanceAt=0;return}this.nextMaintenanceAt=e+36e5}}function oS(e){try{let t=JSON.parse(e);return t&&"object"==typeof t&&!Array.isArray(t)?t:{}}catch{return{}}}function oI(e,t){return{id:e.id,name:e.name,url:e.displayOrigin,canonicalOrigin:e.canonicalOrigin,displayOrigin:e.displayOrigin,defaultBranch:t??null}}function oA(e){return{id:e.id,name:e.name,hostname:e.hostname,connected:null===e.disconnectedAt,diskFreeBytes:e.diskFreeBytes,memoryFreeBytes:e.memoryFreeBytes}}class ox{events;agentControl;worktrees;diskSpace;domains;started;running;diskAuditTimer;diskStateFingerprints;constructor(e,t,r,i,a={}){this.events=e,this.agentControl=t,this.worktrees=r,this.diskSpace=i,this.domains=a,this.started=!1,this.running=!1,this.diskStateFingerprints=new Map}start(){!this.started&&(this.started=!0,this.running=!0,this.agentControl.registerCompletionObserver(e=>this.observeAgentJob(e)),this.consumeRuns(),this.consumeBuilds(),this.consumeWorktrees(),this.consumeCodebases(),this.consumeAgents(),this.consumePipelineStatuses(),this.consumeCommandRuns(),this.consumeCommandOutput(),this.consumeSkillSyncs(),this.consumeIosDevices(),this.consumeSigningAssets(),this.consumePushNotifications(),this.consumeBuildData(),this.consumePollingOperations(),this.consumeModelCosts(),this.consumeToolCalls(),this.diskSpace&&(this.consumeDiskSpace(),this.auditDiskSpace(!0)))}stop(){this.running=!1,this.diskAuditTimer&&clearTimeout(this.diskAuditTimer),this.diskAuditTimer=void 0}async record(e,t,r,i,a={}){await this.events.record({kind:e,subjectKey:t,dedupeKey:r,payload:{...i,...a,sessionData:i}})}async worktreeSessionData(e,t=!1){return e&&this.worktrees?this.worktrees.workflowSessionDataForWorktree(e,{includeMissing:t}):{}}async observeAgentJob(e){if(e.kind===i0.WORKTREE_AUTO_SYNC_JOB_KIND&&e.worktreeId){let t=await this.worktreeSessionData(e.worktreeId,!0);await this.record("WORKTREE_AUTOMATION_RESULT",e.worktreeId,`worktree-automation:${e.id}:${e.status}`,(0,st.mergeSessionData)(t,{worktree:{id:e.worktreeId},automation:{jobId:e.id,status:e.status,error:e.error,result:oS(e.resultJson??"{}")}}),{cursorValue:`${e.id}:${e.status}`})}if("ccusage.report"===e.kind&&"SUCCEEDED"===e.status&&e.resultJson){let t=oS(e.resultJson),r=t.report&&"object"==typeof t.report&&!Array.isArray(t.report)?t.report:{},i=r.totals&&"object"==typeof r.totals&&!Array.isArray(r.totals)?r.totals:{};await this.record("CCUSAGE_THRESHOLD",e.agentId,`ccusage:${e.ccusageCollectionId??e.id}:${e.agentId}`,{run:{usage:i},agent:{id:e.agentId}},{cursorValue:e.ccusageCollectionId??e.id});return}if(!new Set(["FAILED","TIMED_OUT"]).has(e.status))return;let t=await this.worktreeSessionData(e.worktreeId,!0);await this.record("AGENT_JOB_FAILED",e.agentId,`agent-job:${e.id}:${e.status}`,(0,st.mergeSessionData)(t,{agent:{id:e.agentId},codebase:{id:e.codebaseId,agentId:e.agentId},...e.worktreeId?{worktree:{id:e.worktreeId}}:{},steps:{trigger:{id:e.id,kind:e.kind,status:e.status,error:e.error}}}),{cursorValue:`${e.id}:${e.status}`})}async consumeRuns(){let e=ie.agentEventBus.iterate(ie.RUNS_CHANGED_TOPIC);try{for await(let t of e){if(!this.running)break;"drafts"!==t.runChanged.id&&await this.observeRun(t.runChanged.id).catch(e=>console.error("Could not record workflow run trigger:",e))}}finally{await e.return?.()}}async consumePipelineStatuses(){let e=ie.agentEventBus.iterate(ie.GITHUB_PIPELINE_STATUS_CHANGED_TOPIC);try{for await(let t of e){if(!this.running)break;let e=t.githubPipelineStatusChanged,r=e.snapshot,i=e.changedPipeline??{status:r.pipelineStatus};await this.record("GITHUB_PIPELINE_STATUS_CHANGED",`${r.repositoryGithubId}:${r.headSha}`,`github-pipeline:${r.repositoryGithubId}:${r.headSha}:${r.revision}`,{repo:{githubId:r.repositoryGithubId,nameWithOwner:r.repositoryNameWithOwner,url:r.repositoryUrl},pipeline:{...i,headSha:r.headSha,aggregateStatus:r.pipelineStatus,revision:r.revision}},{cursorValue:r.revision}).catch(e=>console.error("Could not record GitHub pipeline trigger:",e))}}finally{await e.return?.()}}async consumeCommandRuns(){let e=ie.agentEventBus.iterate(ie.COMMAND_RUNS_CHANGED_TOPIC);try{for await(let t of e){if(!this.running)break;let e=this.domains.commands;if(!e)continue;let r=await e.getRun(t.commandRunsChanged.id);if(!r||!new Set(["SUCCEEDED","FAILED","CANCELLED"]).has(r.status))continue;let i=await this.worktreeSessionData(r.worktreeId,!0),a=(0,st.mergeSessionData)(i,{command:{id:r.id,commandId:r.commandId,name:r.snapshotName,status:r.status,exitCode:r.exitCode,signal:r.signal,error:r.error,finishedAt:r.finishedAt?.toISOString()??null},agent:{id:r.agentId,name:r.agentName},...r.worktreeId?{worktree:{id:r.worktreeId}}:{}}),n=r.finishedAt?.toISOString()??"terminal";await this.record("COMMAND_RUN_RESULT",r.id,`command-result:${r.id}:${r.status}:${n}`,a,{cursorValue:`${r.status}:${n}`}).catch(e=>console.error("Could not record command result trigger:",e))}}finally{await e.return?.()}}async consumeCommandOutput(){let e=ie.agentEventBus.iterate(ie.COMMAND_RUN_OUTPUT_CHANGED_TOPIC);try{for await(let t of e){if(!this.running)break;let e=t.commandRunOutputAdded,r=Buffer.from(e.dataBase64,"base64").toString("utf8");await this.record("COMMAND_OUTPUT_MATCH",e.runId,`command-output:${e.id}`,{command:{id:e.runId},output:{data:r,stream:e.stream,attempt:e.attemptNumber,sequence:e.sequence}},{cursorValue:e.id}).catch(e=>console.error("Could not record command output trigger:",e))}}finally{await e.return?.()}}async consumeSkillSyncs(){let e=ie.agentEventBus.iterate(ie.SKILLS_CHANGED_TOPIC);try{for await(let t of e){if(!this.running)break;let e=this.domains.skills;if(!e||!t.id)continue;let r=await e.getRun(t.id);if(!r)continue;let i=r.items.filter(e=>"BLOCKED"===e.status).map(e=>({id:e.id,skillId:e.skillId,skillName:e.skill?.name??null,direction:e.direction,error:e.error})),a={skillSync:{id:r.id,kind:r.kind,status:r.status,error:r.error,conflictCount:i.length,conflicts:i,updatedAt:r.updatedAt.toISOString(),finishedAt:r.finishedAt?.toISOString()??null},...r.groupId?{skill:{groupId:r.groupId}}:{}};("NEEDS_RESOLUTION"===r.status||i.length)&&await this.record("SKILL_SYNC_CONFLICT",r.id,`skill-conflict:${r.id}:${r.updatedAt.toISOString()}`,a,{cursorValue:r.updatedAt.toISOString()}),new Set(["READY","PARTIAL","SUCCEEDED"]).has(r.status)&&await this.record("SKILL_SYNC_RESULT",r.id,`skill-result:${r.id}:${r.status}:${r.updatedAt.toISOString()}`,a,{cursorValue:`${r.status}:${r.updatedAt.toISOString()}`})}}finally{await e.return?.()}}async consumeIosDevices(){let e=ie.agentEventBus.iterate(ie.IOS_DEVICES_CHANGED_TOPIC);try{for await(let t of e){if(!this.running)break;let e=this.domains.iosDevices;if(!e||!t.id)continue;let r=await e.device(t.id);if(!r)continue;let i={device:{id:r.id,udid:r.udid,name:r.displayName,product:r.product,osVersion:r.osVersion,status:r.status,error:r.registrationError,updatedAt:r.updatedAt.toISOString()}};await this.record("IOS_DEVICE_ENROLLED",r.id,`ios-device-enrolled:${r.id}:${r.createdAt.toISOString()}`,i,{cursorValue:r.createdAt.toISOString()}),new Set(["REGISTERED","REGISTRATION_FAILED","REJECTED"]).has(r.status)&&await this.record("IOS_DEVICE_REGISTRATION_RESULT",r.id,`ios-device-registration:${r.id}:${r.status}:${r.updatedAt.toISOString()}`,i,{cursorValue:`${r.status}:${r.updatedAt.toISOString()}`})}}finally{await e.return?.()}}async consumeSigningAssets(){let e=ie.agentEventBus.iterate(ie.SIGNING_ASSETS_CHANGED_TOPIC);try{for await(let t of e){if(!this.running)break;if(!t.changed)continue;let e=this.domains.signingAssets;if(!e)continue;let[r,i]=await Promise.all([e.operations(200),e.profiles()]);for(let e of r.filter(e=>e.finishedAt)){let t={signingOperation:{id:e.id,kind:e.kind,status:e.status,assetKey:e.assetKey,error:e.error,finishedAt:e.finishedAt?.toISOString()??null},...e.assetKey?{signingProfile:{id:e.assetKey}}:{}};await this.record("SIGNING_OPERATION_RESULT",e.id,`signing-operation:${e.id}:${e.status}:${e.updatedAt.toISOString()}`,t,{cursorValue:`${e.status}:${e.updatedAt.toISOString()}`})}for(let e of i.filter(e=>e.expiresAt)){let t=e.expiresAt;await this.record("SIGNING_ASSET_EXPIRING",e.id,`signing-expiry:${e.id}:${t}`,{signingProfile:{...e,id:e.id}},{cursorValue:t,expiresInDays:Math.ceil((new Date(t).getTime()-Date.now())/864e5)})}}}finally{await e.return?.()}}async consumePushNotifications(){let e=ie.agentEventBus.iterate(ie.PUSH_NOTIFICATIONS_CHANGED_TOPIC);try{for await(let t of e){if(!this.running)break;if(!t.changed)continue;let e=this.domains.pushNotifications;if(e)for(let t of(await e.history(200)).filter(e=>!new Set(["DRAFT","QUEUED","SENDING"]).has(e.status))){let e=t.updatedAt.toISOString();await this.record("PUSH_NOTIFICATION_RESULT",t.id,`push-result:${t.id}:${t.status}:${e}`,{pushBatch:{id:t.id,status:t.status,targetMode:t.targetMode,deliveryCount:t.deliveries.length,updatedAt:e}},{cursorValue:`${t.status}:${e}`})}}}finally{await e.return?.()}}async consumeBuildData(){let e=ie.agentEventBus.iterate(ie.BUILD_DATA_CHANGED_TOPIC);try{for await(let t of e){if(!this.running)break;let e=this.domains.buildData;if(!e)continue;let r=await e.getCollection(t.buildDataCollectionChanged.id);if(!r||"COMPLETED"!==r.status)continue;let i=r.entries.reduce((e,t)=>e+(t.sizeBytes??0),0),a={buildData:{id:r.id,status:r.status,finishedAt:r.finishedAt,totalBytes:i,entryCount:r.entries.length,successfulAgentCount:r.progress.successfulCount}},n=r.finishedAt??r.deadlineAt;await this.record("BUILD_DATA_THRESHOLD",r.id,`build-data-threshold:${r.id}:${n}`,a,{cursorValue:i}),await this.record("BUILD_DATA_CLEANUP_RESULT",r.id,`build-data-result:${r.id}:${n}`,a,{cursorValue:n})}}finally{await e.return?.()}}async consumePollingOperations(){let e=ie.agentEventBus.iterate(ie.POLLING_CHANGED_TOPIC);try{for await(let t of e){if(!this.running)break;let e=this.domains.polling;if(!e)continue;let r=(await e.list()).find(e=>e.id===t.pollingOperationChanged);if(!r)continue;let i=r.lastCompletedAt??r.lastStartedAt??r.nextScheduledAt??r.status;await this.record("POLLING_OPERATION_STATE",r.id,`polling-state:${r.id}:${r.status}:${i}`,{polling:r},{cursorValue:`${r.status}:${i}`}).catch(e=>console.error("Could not record polling operation trigger:",e));let a=await this.domains.credentials?.status();if(a&&"READY"!==a.state){let e=a.warnings.map(({code:e})=>e);await this.record("CREDENTIAL_STORE_DEGRADED",a.storageType,`credential-store:${a.state}:${e.join(",")}`,{credentialStore:a},{cursorValue:{state:a.state,warningCodes:e,mismatchCount:a.mismatchCount}})}}}finally{await e.return?.()}}async consumeModelCosts(){let e=ie.agentEventBus.iterate(ie.MODEL_COST_CATALOG_CHANGED_TOPIC);try{for await(let{catalog:t}of e){if(!this.running)break;let e=t.fetchedAt??`${t.url}:${t.error??"pending"}`;await this.record("MODEL_COST_CATALOG_CHANGED",t.url,`model-costs:${t.url}:${e}`,{modelCosts:t},{cursorValue:e})}}finally{await e.return?.()}}async consumeToolCalls(){let e=ie.agentEventBus.iterate(ie.TOOL_CALL_AUDIT_CHANGED_TOPIC);try{for await(let t of e){if(!this.running)break;let e=await (0,t1.getPrismaClient)(),r=await e.toolCallAudit.findUnique({where:{id:t.toolCallAuditChanged.id}});if(!r||"RUNNING"===r.resultStatus)continue;let i=r.caller.startsWith("workflow:")?r.caller.slice(9):null,a=i?await e.workflowRun.findUnique({where:{id:i},select:{id:!0,workflowId:!0}}):null,n=a?null:await e.workflowStepAttempt.findUnique({where:{id:r.correlationId},select:{run:{select:{id:!0,workflowId:!0}}}}),s=a??n?.run??null,o=r.finishedAt?.toISOString()??"unfinished";await this.record("TOOL_CALL_RESULT",r.id,`tool-call:${r.id}:${r.resultStatus}:${o}`,{toolCall:{id:r.id,correlationId:r.correlationId,caller:r.caller,source:r.source,groupId:r.groupId,toolName:r.toolName,argumentsSha256:r.argumentsSha256,resultStatus:r.resultStatus,durationMs:r.durationMs,finishedAt:r.finishedAt?.toISOString()??null}},{cursorValue:`${r.resultStatus}:${o}`,...s?{workflowCorrelation:{workflowId:s.workflowId,runId:s.id}}:{}})}}finally{await e.return?.()}}async observeRun(e){let t=await (0,t1.getPrismaClient)(),r=await t.agentRun.findUnique({where:{id:e},include:{worktree:{include:{codebase:{include:{repository:!0}}}},agent:{select:{id:!0,name:!0,hostname:!0,disconnectedAt:!0,diskFreeBytes:!0,memoryFreeBytes:!0}},questionBatches:{orderBy:{createdAt:"desc"},take:1,include:{questions:{include:{options:!0}}}},events:{orderBy:{sequence:"desc"},take:1},toolCalls:{orderBy:{sequence:"desc"},take:1}}});if(!r)return;let i=await t.workflowRunResourceLink.findFirst({where:{kind:"AGENT_RUN",resourceId:r.id},include:{run:!0},orderBy:{createdAt:"desc"}}),a=await this.worktreeSessionData(r.worktree?.id??null),n=(0,st.mergeSessionData)(a,{run:{id:r.id,kind:r.kind,status:r.status,phase:r.phase,origin:r.origin,provider:r.provider,model:r.model,finalOutput:r.finalOutput,error:r.error,sourcePlanId:r.sourcePlanId,parentRunId:r.parentRunId,followUpMode:r.followUpMode,usage:{inputTokens:r.inputTokens,outputTokens:r.outputTokens,reasoningTokens:r.reasoningTokens,cacheReadTokens:r.cacheReadTokens,cacheWriteTokens:r.cacheWriteTokens,toolCallCount:r.toolCallCount,estimatedCost:r.estimatedCost}},...r.worktree?{worktree:{id:r.worktree.id,path:r.worktree.folder,branch:r.worktree.branch,headSha:r.worktree.headSha},codebase:{id:r.worktree.codebase.id,folder:r.worktree.codebase.folder,agentId:r.worktree.codebase.agentId},repo:oI(r.worktree.codebase.repository,r.worktree.codebase.defaultBranch)}:{},...r.agent?{agent:oA(r.agent)}:{},...r.jiraIssueKey?{ticket:{key:r.jiraIssueKey}}:{}}),s=i?{workflowId:i.run.workflowId,runId:i.runId,attemptId:i.attemptId}:null,o={cursorValue:`${r.status}:${r.phase}`,workflowCorrelation:s};r.startedAt&&await this.record("RUN_STARTED",r.id,`run-started:${r.id}:${r.startedAt.toISOString()}`,n,o);let l="COMPLETED"===r.status?"RUN_COMPLETED":"FAILED"===r.status?"RUN_FAILED":"CANCELLED"===r.status?"RUN_CANCELLED":"PAUSED"===r.status?"RUN_PAUSED":null;l&&await this.record(l,r.id,`run-status:${r.id}:${r.status}:${r.finishedAt?.toISOString()??r.updatedAt.toISOString()}`,n,o),"RUNNING"===r.phase&&r.startedAt&&r.updatedAt>r.startedAt&&await this.record("RUN_CONTINUED",r.id,`run-continued:${r.id}:${r.updatedAt.toISOString()}`,n,o),r.sourcePlanId&&await this.record("RUN_PLAN_PLAYED",r.id,`run-plan-played:${r.id}:${r.sourcePlanId}`,n,o),r.parentRunId&&"PLAN_PLAY"!==r.followUpMode&&await this.record("RUN_FOLLOW_UP",r.id,`run-follow-up:${r.id}:${r.parentRunId}`,n,o),"IMPORTED"===r.origin&&await this.record("RUN_IMPORTED",r.id,`run-imported:${r.id}:${r.updatedAt.toISOString()}`,n,o),await this.record("RUN_USAGE_THRESHOLD",r.id,`run-usage:${r.id}:${r.updatedAt.toISOString()}`,n,{...o,cursorValue:r.updatedAt.toISOString()});let c=r.questionBatches[0];if(c){let e={...n,run:{...n.run,questions:c.questions}};"PENDING"===c.status?await this.record("RUN_QUESTION_NEEDED",r.id,`run-question:${c.id}:pending`,e,o):"ANSWERED"===c.status&&await this.record("RUN_QUESTION_ANSWERED",r.id,`run-question:${c.id}:answered`,e,o)}let u=r.events[0];u&&await this.record("RUN_EVENT_MATCH",r.id,`run-event:${u.id}`,n,{...o,event:u});let d=r.toolCalls[0];d&&await this.record("RUN_EVENT_MATCH",r.id,`run-tool:${d.id}:${d.status}`,n,{...o,toolCall:d})}async consumeBuilds(){let e=ie.agentEventBus.iterate(ie.BUILDS_CHANGED_TOPIC);try{for await(let t of e){if(!this.running)break;await this.observeBuild(t.buildsChanged.id).catch(e=>console.error("Could not record workflow build trigger:",e))}}finally{await e.return?.()}}async observeBuild(e){let t=await (0,t1.getPrismaClient)(),r=await t.build.findUnique({where:{id:e},include:{codebase:{include:{repository:!0,agent:{select:{id:!0,name:!0,hostname:!0,disconnectedAt:!0,diskFreeBytes:!0,memoryFreeBytes:!0}}}},worktree:!0,reports:!0,scriptExecutions:!0}});if(!r)return;let i=await this.worktreeSessionData(r.worktree?.id??null),a=(0,st.mergeSessionData)(i,{build:{id:r.id,status:r.status,action:r.action,error:r.error},...r.codebase?{codebase:{id:r.codebase.id,folder:r.codebase.folder,agentId:r.codebase.agentId},repo:oI(r.codebase.repository,r.codebase.defaultBranch),agent:oA(r.codebase.agent)}:{},...r.worktree?{worktree:{id:r.worktree.id,path:r.worktree.folder,branch:r.worktree.branch,headSha:r.worktree.headSha}}:{}});for(let e of(new Set(["SUCCEEDED","FAILED","CANCELLED"]).has(r.status)&&await this.record("BUILD_RESULT",r.id,`build-result:${r.id}:${r.status}`,a,{cursorValue:r.status}),r.reports.filter(({status:e})=>"READY"===e))){let t=oS(e.summaryJson),i={...a,build:{...a.build,..."TEST_RESULTS"===e.kind?{testSummary:t}:{coverageSummary:t}}};await this.record("TEST_RESULTS"===e.kind?"BUILD_TEST_THRESHOLD":"BUILD_COVERAGE_THRESHOLD",r.id,`build-report:${e.id}:${e.updatedAt.toISOString()}`,i,{cursorValue:e.updatedAt.toISOString()})}for(let e of r.scriptExecutions.filter(({causedBuildFailure:e})=>e))await this.record("BUILD_HOOK_FAILED",r.id,`build-hook:${e.id}:failed`,a,{cursorValue:e.id,script:{id:e.id,name:e.nameSnapshot,phase:e.phase}})}async consumeWorktrees(){let e=ie.agentEventBus.iterate(ie.WORKTREE_CHANGED_TOPIC);try{for await(let t of e){if(!this.running)break;let e=t.worktreeOverviewChanged,r=await (0,t1.getPrismaClient)();for(let t of(await r.worktree.findMany({where:e.worktreeId?{id:e.worktreeId}:e.codebaseId?{codebaseId:e.codebaseId}:{},include:{codebase:{include:{repository:!0}}},take:e.worktreeId?1:500})))await this.observeWorktree(t).catch(e=>console.error("Could not record workflow worktree trigger:",e))}}finally{await e.return?.()}}async observeWorktree(e){let t=e.lastCheckedAt??e.updatedAt,r=e.hasStagedChanges||e.hasUnstagedChanges,i=await this.worktreeSessionData(e.id,!0),a=(0,st.mergeSessionData)(i,{repo:oI(e.codebase.repository,e.codebase.defaultBranch),codebase:{id:e.codebase.id,folder:e.codebase.folder,agentId:e.codebase.agentId},worktree:{id:e.id,path:e.folder,branch:e.branch,headSha:e.headSha,syncState:e.syncState,pushStatus:e.pushStatus,statusError:e.statusError,baseBehind:e.baseBehind,dirty:r,missingAt:e.missingAt?.toISOString()??null,dirtySince:r?e.updatedAt.toISOString():null}}),n={cursorValue:t.toISOString()};await this.record("WORKTREE_SYNC_STATE_CHANGED",e.id,`worktree-sync:${e.id}:${e.syncState}:${t.toISOString()}`,a,{cursorValue:e.syncState}),await this.record("WORKTREE_CLEAN",e.id,`worktree-clean:${e.id}:${t.toISOString()}`,a,{cursorValue:r}),(e.baseBehind??0)>0&&await this.record("WORKTREE_BEHIND",e.id,`worktree-behind:${e.id}:${t.toISOString()}`,a,n),await this.record("WORKTREE_DIRTY_DURATION",e.id,`worktree-dirty:${e.id}:${t.toISOString()}`,a,n),await this.record("WORKTREE_MISSING",e.id,`worktree-missing:${e.id}:${t.toISOString()}`,a,{cursorValue:!!e.missingAt}),await this.record("WORKTREE_DIVERGED",e.id,`worktree-diverged:${e.id}:${t.toISOString()}`,a,{cursorValue:"DIVERGED"===e.pushStatus}),e.headSha&&await this.record("WORKTREE_NEW_COMMIT",e.id,`worktree-commit:${e.id}:${e.headSha}`,a,{cursorValue:e.headSha})}async consumeCodebases(){let e=ie.agentEventBus.iterate(ie.CODEBASE_CHANGED_TOPIC);try{for await(let t of e){if(!this.running)break;let e=await (0,t1.getPrismaClient)(),r=t.codebaseOverviewChanged;for(let t of(await e.codebase.findMany({where:r.codebaseId?{id:r.codebaseId}:r.repositoryId?{repositoryId:r.repositoryId}:{},include:{repository:!0,agent:{select:{id:!0,name:!0,hostname:!0,disconnectedAt:!0,diskFreeBytes:!0,memoryFreeBytes:!0}}},take:r.codebaseId?1:500}))){let e={repo:oI(t.repository,t.defaultBranch),agent:oA(t.agent),codebase:{id:t.id,folder:t.folder,agentId:t.agentId,branch:t.defaultBranch,syncState:t.syncState,availability:t.availability,statusError:t.statusError,lastFetchError:t.lastFetchError,remoteBranches:JSON.parse(t.remoteBranchesJson)}},r=(t.lastCheckedAt??t.updatedAt).toISOString();await this.record("CODEBASE_SYNC_STATE_CHANGED",t.id,`codebase-sync:${t.id}:${t.syncState}:${r}`,e,{cursorValue:t.syncState}),(t.statusError||t.lastFetchError)&&await this.record("CODEBASE_OPERATION_FAILED",t.id,`codebase-failed:${t.id}:${r}`,e,{cursorValue:r,error:t.statusError??t.lastFetchError});let i=e.codebase.remoteBranches;if(Array.isArray(i))for(let r of i.filter(e=>"string"==typeof e))await this.record("CODEBASE_REMOTE_BRANCH",t.id,`codebase-remote-branch:${t.id}:${r}`,e,{cursorValue:r,branch:r})}}}finally{await e.return?.()}}async emitDiskSnapshot(e,t){let r=e.agent.id;t.report&&await this.record("AGENT_DISK_REPORT",r,`agent-disk-report:${r}:${e.disk.lastReportedAt??t.changeId}`,e,{cursorValue:e.disk.lastReportedAt}),t.threshold&&await this.record("AGENT_DISK_THRESHOLD",r,`agent-disk-threshold:${r}:${t.changeId}`,e);let i=ia(e);if(await this.record("AGENT_DISK_STATE_CHANGED",r,`agent-disk-state:${r}:${t.changeId}`,e,{cursorValue:i}),this.diskStateFingerprints.set(r,JSON.stringify(i)),t.cleanup){let i={...e,cleanup:t.cleanup};await this.record("AGENT_DISK_CLEANUP_RESULT",r,`agent-disk-cleanup:${t.cleanup.jobId}:${t.cleanup.status}`,i,{cleanup:t.cleanup})}}async observeDiskChange(e){if(!this.diskSpace)return;let{id:t,reason:r,cleanup:i}=e.diskSpaceChange;if("settings"===e.diskSpaceChanged){let e=await this.diskSpace.overview();for(let i of e.agents)await this.emitDiskSnapshot(ii(e.settings,i,r),{changeId:t,report:!1,threshold:!0});return}let a=await this.diskSpace.snapshot(e.diskSpaceChanged,r);await this.emitDiskSnapshot(a,{changeId:t,report:"REPORT_RECEIVED"===r,threshold:!0,cleanup:i})}async consumeDiskSpace(){if(!this.diskSpace)return;let e=this.diskSpace.subscribe();try{for await(let t of e){if(!this.running)break;await this.observeDiskChange(t).catch(e=>console.error("Could not record disk-space workflow trigger:",e))}}finally{await e.return?.()}}async auditDiskSpace(e){if(this.diskSpace&&this.running)try{let t=await this.diskSpace.overview();for(let r of t.agents){let i=ii(t.settings,r,e?"STARTUP_RECONCILE":"STATE_AUDIT"),a=JSON.stringify(ia(i));(e||this.diskStateFingerprints.get(r.agent.id)!==a)&&await this.emitDiskSnapshot(i,{changeId:(0,b.randomUUID)(),report:!1,threshold:e})}}catch(e){console.error("Could not audit disk-space workflow state:",e)}finally{this.running&&(this.diskAuditTimer=setTimeout(()=>void this.auditDiskSpace(!1),1e3*r7.DISK_SPACE_POLL_INTERVAL_SECONDS),this.diskAuditTimer.unref?.())}}async consumeAgents(){let e=ie.agentEventBus.iterate(ie.AGENT_CHANGED_TOPIC);try{for await(let t of e){if(!this.running)break;let e=await (0,t1.getPrismaClient)(),r=await e.agent.findUnique({where:{id:t.agentChanged.id}});if(!r)continue;let i=null===r.disconnectedAt,a={codebase:{agentId:r.id},agent:{id:r.id,name:r.name,connected:i,diskFreeBytes:r.diskFreeBytes,memoryFreeBytes:r.memoryFreeBytes}};await this.record("AGENT_CONNECTION",r.id,`agent-connection:${r.id}:${r.updatedAt.toISOString()}`,a,{cursorValue:i}),await this.record("AGENT_RESOURCE_THRESHOLD",r.id,`agent-resource:${r.id}:${r.updatedAt.toISOString()}`,a,{cursorValue:{diskFreeBytes:r.diskFreeBytes,memoryFreeBytes:r.memoryFreeBytes}}),await this.record("AGENT_VERSION_CHANGED",r.id,`agent-version:${r.id}:${r.version}`,{...a,agent:{...a.agent,version:r.version,osVersion:r.osVersion,architecture:r.architecture}},{cursorValue:r.version})}}finally{await e.return?.()}}}function o_(e){return null===e||["string","number","boolean"].includes(typeof e)?e:JSON.stringify(e)}function oC(e,t){if("ALL"===e.op)return e.conditions.every(e=>oC(e,t));if("ANY"===e.op)return e.conditions.some(e=>oC(e,t));if("NOT"===e.op)return!oC(e.condition,t);if(!("left"in e))return!1;let r=(0,st.resolveWorkflowValue)(e.left,t),i=(0,st.resolveWorkflowValue)(e.right,t);switch(e.op){case"EXISTS":return null!=r;case"EQ":return JSON.stringify(r)===JSON.stringify(i);case"NE":return JSON.stringify(r)!==JSON.stringify(i);case"GT":return o_(r)>o_(i);case"GTE":return o_(r)>=o_(i);case"LT":return o_(r)<o_(i);case"LTE":return o_(r)<=o_(i);case"CONTAINS":return Array.isArray(r)?r.some(e=>JSON.stringify(e)===JSON.stringify(i)):String(r??"").includes(String(i??""));case"MATCHES":return(0,sZ.compileRe2)(String(i??""),{label:"Workflow condition pattern"}).test(String(r??""))}}var oR=e.i(248626),oT=e.i(336921),oD=e.i(53803),oN=e.i(264977);async function oO(e,t){let r=e.trim();if(!r||r.length>5e4)throw Error(`Workflow script must contain 1–${5e4.toLocaleString()} characters`);let i=await (0,oD.getQuickJS)(),a=Date.now()+250;try{return i.evalCode(`"use strict"; const session = Object.freeze(${JSON.stringify(t)}); (${r})(session);`,{memoryLimitBytes:8388608,maxStackSizeBytes:524288,shouldInterrupt:(0,oN.shouldInterruptAfterDeadline)(a)})}catch(t){let e=t instanceof Error?t.message:String(t);throw Error(`Workflow script failed: ${"interrupted"===e?"execution timed out after 250ms":e}`)}}class oP{handlers=new Map;register(e,t){this.handlers.set(e,t)}has(e){return this.handlers.has(e)}execute(e){let t=this.handlers.get(e.node.kind);if(!t)throw Error(`Workflow step ${e.node.kind} is not registered`);return t(e)}}let oL="workflows:changed",oB=e=>`workflow-run:${e}`,oU=e=>`workflow-run:${e}:events`,oj=e=>`workflow-run:${e}:questions`,oM=["QUEUED","RUNNING","PAUSING","PAUSED","WAITING","BLOCKED"],oq=new Set(["SUCCEEDED","FAILED","CANCELLED"]),o$=new Set(["SUCCEEDED","FAILED","CANCELLED","SKIPPED","SUPERSEDED"]),oF=new Set(["RUNNING","WAITING"]),oG=new Set(["WORKTREE_CREATE","WORKTREE_DELETE","WORKTREE_MOVE","WORKTREE_MOVE_CONTROL"]);function oK(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}function oH(e,t){let r;if(e.exclusiveWorktree&&("string"==typeof(r=(0,st.getSessionValue)(t,"worktree.id"))&&r?r:null)!==e.worktreeId)throw Error("Exclusive workflows cannot change worktrees; start a new workflow on the target worktree instead")}let oV=e=>JSON.parse(e);function oW(e){return{agent:{id:e.id,name:e.name,hostname:e.hostname,...void 0!==e.lastSeenAt&&void 0!==e.disconnectedAt?{connected:null!==e.lastSeenAt&&null===e.disconnectedAt&&Date.now()-e.lastSeenAt.getTime()<=(0,a.agentOnlineWindowMs)(e)}:{},...void 0!==e.diskFreeBytes?{diskFreeBytes:e.diskFreeBytes}:{},...void 0!==e.memoryFreeBytes?{memoryFreeBytes:e.memoryFreeBytes}:{}}}}function oJ(e){return(0,st.mergeSessionData)(oW(e.agent),{codebase:{id:e.id,folder:e.folder,agentId:e.agentId,branch:e.branch,headSha:e.headSha},repo:{id:e.repository.id,name:e.repository.name,url:e.repository.displayOrigin,canonicalOrigin:e.repository.canonicalOrigin,displayOrigin:e.repository.displayOrigin,defaultBranch:e.defaultBranch}})}function oz(e,t,r){let i=e.trim();if(!i)throw Error(`${t} is required`);if(i.length>r)throw Error(`${t} is too long`);return i}function oY(e){let t=e?.trim().toUpperCase()||"QUEUE";if(!new Set(["QUEUE","CONCURRENT","COALESCE_LATEST"]).has(t))throw Error("Workflow overlap policy is not supported");return t}function oZ(e){let t=e?.trim().toUpperCase()||"WORKTREE";if(!new Set(["WORKTREE","GLOBAL"]).has(t))throw Error("Workflow overlap scope is not supported");return t}let oQ=["EXCLUSIVE","NON_EXCLUSIVE","EXCLUDED"];function oX(e,t){let r=e?.trim().toUpperCase()||(!0===t?"EXCLUSIVE":"NON_EXCLUSIVE");if(!oQ.includes(r))throw Error("Workflow worktree concurrency is not supported");return r}function o0(e,t){return"EXCLUSIVE"===e||(t??!1)}function o1(e,t){return"WORKTREE"===e?{worktreeId:t}:{}}function o2(e,t){let r=e??("CONCURRENT"===t?4:1);if(!Number.isInteger(r)||r<1||r>32)throw Error("Maximum concurrent runs must be between 1 and 32");return r}function o3(e){return Array.isArray(e)?`[${e.map(o3).join(",")}]`:e&&"object"==typeof e?`{${Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${JSON.stringify(e)}:${o3(t)}`).join(",")}}`:JSON.stringify(e)}function o4(e,t,r){if(Buffer.byteLength(e,"utf8")>r)throw Error(`${t} is too large`)}function o6(e,t){if(!e||"object"!=typeof e||Array.isArray(e))throw Error(`${t} must be an object`);return e}function o8(e){ie.agentEventBus.publish(oL,{workflowChanged:{id:e}})}function o5(e){ie.agentEventBus.publish(oB(e),{workflowRunChanged:{id:e}}),ie.agentEventBus.publish(oL,{workflowChanged:{id:"runs",runId:e}}),ie.agentEventBus.publish(ie.SIDEBAR_STATUS_CHANGED_TOPIC,{sidebarStatusChanged:!0})}function o9(e){return[...iC.WORKFLOW_STEP_BY_KIND.get(e.kind).requiredPaths.map(t=>t.replaceAll("<stepId>",e.id)),...e.requiredPaths,...(0,oR.requiredConfigSessionPaths)(e.kind,"step",e.config)]}function o7(e){return[...iC.WORKFLOW_STEP_BY_KIND.get(e.kind).providedPaths.map(t=>t.replaceAll("<stepId>",e.id)),...e.providedPaths,`steps.${e.id}.*`]}async function le(e){return(await e.workflowRunNumberSequence.upsert({where:{id:"default"},create:{id:"default",nextValue:2},update:{nextValue:{increment:1}}})).nextValue-1}class lt{events;executor;checkpointRestorer;credentials;agentControl;notifications;runsService;worktrees;commandsService;jiraService;runtimeTimer;commandOutputStream;ticking;workerId;activeExecutions;claimedSecretJobs;waitPollers;constructor(e,t=new oP,r,i,a,n,s,o,l,c){this.events=e,this.executor=t,this.checkpointRestorer=r,this.credentials=i,this.agentControl=a,this.notifications=n,this.runsService=s,this.worktrees=o,this.commandsService=l,this.jiraService=c,this.ticking=!1,this.workerId=(0,b.randomUUID)(),this.activeExecutions=new Map,this.claimedSecretJobs=new Set,this.waitPollers=new Map,this.runsService?.setWorktreeAdmissionPromoter(async()=>{await this.startQueuedRuns()}),this.agentControl&&(this.executor.register("TERMINAL_RUN",e=>this.startTerminalJob(e)),this.executor.register("WORKTREE_SNAPSHOT",e=>this.startCheckpointJob(e)),this.agentControl.registerCompletionHandler(oT.WORKFLOW_TERMINAL_JOB_KIND,e=>this.workflowAgentJobCompleted(e)),this.agentControl.registerCompletionObserver(e=>this.genericAgentJobCompleted(e)),this.agentControl.registerCompletionHandler(oT.WORKFLOW_GIT_CHECKPOINT_JOB_KIND,e=>this.workflowAgentJobCompleted(e)))}async controlLinkedAgentRuns(e,t){if(!this.runsService)return;let r=await (0,t1.getPrismaClient)(),i=await r.workflowRunResourceLink.findMany({where:{runId:e,kind:"AGENT_RUN",attempt:{status:{in:["RUNNING","WAITING"]}}},select:{resourceId:!0},distinct:["resourceId"]});await Promise.allSettled(i.map(async({resourceId:e})=>{let r=await this.runsService.get(e);!r||"MANAGED"!==r.origin||"PAUSE"===t&&"IN_PROGRESS"!==r.status||"CONTINUE"===t&&"PAUSED"!==r.status||"CANCEL"===t&&new Set(["COMPLETED","FAILED","CANCELLED"]).has(r.status)||await this.runsService.lifecycle(e,t)}))}async cancelWaitingCommandRuns(e){if(!this.commandsService)return;let t=await (0,t1.getPrismaClient)(),r=await t.workflowRunResourceLink.findMany({where:{runId:e,kind:"COMMAND_RUN",attempt:{status:"WAITING"}},select:{resourceId:!0},distinct:["resourceId"]});await Promise.allSettled(r.map(({resourceId:e})=>this.commandsService.terminateRun(e)))}async promoteWorktreeAdmissions(e){if(e)try{await this.runsService?.reconcileQueuedRuns(),await this.startQueuedRuns()}catch(t){console.error(`Could not promote worktree queue for ${e}:`,t instanceof Error?t.message:t)}}async runWorktree(e){let t=(0,st.getSessionValue)(oV(e),"worktree.id");return"string"==typeof t&&t?(await (0,t1.getPrismaClient)()).worktree.findUnique({where:{id:t},select:{id:!0,folder:!0,branch:!0,highlightColor:!0}}):null}async runAgent(e){let t=oV(e),r=(0,st.getSessionValue)(t,"agent.id")??(0,st.getSessionValue)(t,"codebase.agentId"),i=await (0,t1.getPrismaClient)();if("string"==typeof r&&r)return i.agent.findUnique({where:{id:r}});let a=(0,st.getSessionValue)(t,"worktree.id");if("string"!=typeof a||!a)return null;let n=await i.worktree.findUnique({where:{id:a},select:{codebase:{select:{agent:!0}}}});return n?.codebase.agent??null}async queueForWorktree(e){let t=await (0,t1.getPrismaClient)(),[r,i,a]=await Promise.all([t.workflowRun.findMany({where:{worktreeId:e,status:"QUEUED"},orderBy:[{queuedAt:"asc"},{id:"asc"}],select:{id:!0,displayNumber:!0,status:!0,phase:!0,queuedAt:!0,exclusiveWorktree:!0,worktreeConcurrency:!0,worktreeLeaseOwnerRunId:!0,workflowId:!0,workflow:{select:{name:!0}},worktree:{select:{id:!0,folder:!0,branch:!0,highlightColor:!0}}}}),t.agentRun.findMany({where:{worktreeId:e,origin:"MANAGED",status:"QUEUED",kind:{in:["PLAN","SESSION"]}},orderBy:[{createdAt:"asc"},{id:"asc"}],select:{id:!0,kind:!0,displayNumber:!0,status:!0,phase:!0,createdAt:!0,initialPrompt:!0,worktreeConcurrencyLimit:!0,worktree:{select:{id:!0,folder:!0,branch:!0,highlightColor:!0}},workflowRun:{select:{id:!0,workflowId:!0,worktreeLeaseOwnerRunId:!0}}}}),t.worktreeWorkflowLease.findUnique({where:{worktreeId:e},select:{workflowRunId:!0}})]);return[...r.map(t=>({id:t.id,kind:"WORKFLOW",displayNumber:t.displayNumber,name:t.workflow.name,status:t.status,phase:t.phase,worktreeId:e,worktree:t.worktree,workflowId:t.workflowId,workflowRunId:t.id,queuedAt:t.queuedAt,exclusiveWorktree:t.exclusiveWorktree,worktreeConcurrency:t.worktreeConcurrency,worktreeConcurrencyLimit:null,leaseOwnerRunId:t.worktreeLeaseOwnerRunId})),...i.map(t=>({id:t.id,kind:t.kind,displayNumber:t.displayNumber,name:t.initialPrompt,status:t.status,phase:t.phase,worktreeId:e,worktree:t.worktree,workflowId:t.workflowRun?.workflowId??null,workflowRunId:t.workflowRun?.id??null,queuedAt:t.createdAt,exclusiveWorktree:!1,worktreeConcurrency:"NON_EXCLUSIVE",worktreeConcurrencyLimit:t.worktreeConcurrencyLimit,leaseOwnerRunId:t.workflowRun?.worktreeLeaseOwnerRunId??null}))].sort((e,t)=>{if(a){let r=e.leaseOwnerRunId===a.workflowRunId;if(r!==(t.leaseOwnerRunId===a.workflowRunId))return r?-1:1}return e.queuedAt.getTime()-t.queuedAt.getTime()||e.id.localeCompare(t.id)}).map(({leaseOwnerRunId:e,...t},r)=>({...t,position:r+1,queuedAt:t.queuedAt.toISOString()}))}async runQueue(e){if(e.worktreeId)return this.queueForWorktree(e.worktreeId);if(!e.workflowId)throw Error("A worktree or workflow is required to read its queue");let t=await (0,t1.getPrismaClient)(),[r,i]=await Promise.all([t.workflowRun.findMany({where:{workflowId:e.workflowId,status:"QUEUED"},select:{id:!0,worktreeId:!0,displayNumber:!0,status:!0,phase:!0,queuedAt:!0,exclusiveWorktree:!0,worktreeConcurrency:!0,workflow:{select:{name:!0}}}}),t.agentRun.findMany({where:{origin:"MANAGED",status:"QUEUED",workflowRun:{workflowId:e.workflowId}},select:{id:!0,worktreeId:!0}})]),a=new Set(r.map(({id:e})=>e)),n=new Set(i.map(({id:e})=>e)),s=[...new Set([...r,...i].map(({worktreeId:e})=>e).filter(e=>!!e))];return[...(await Promise.all(s.map(e=>this.queueForWorktree(e)))).flat().filter(e=>"WORKFLOW"===e.kind?a.has(e.id):n.has(e.id)),...r.filter(({worktreeId:e})=>!e).sort((e,t)=>e.queuedAt.getTime()-t.queuedAt.getTime()||e.id.localeCompare(t.id)).map((t,r)=>({position:r+1,id:t.id,kind:"WORKFLOW",displayNumber:t.displayNumber,name:t.workflow.name,status:t.status,phase:t.phase,worktreeId:null,worktree:null,workflowId:e.workflowId,workflowRunId:t.id,queuedAt:t.queuedAt.toISOString(),exclusiveWorktree:t.exclusiveWorktree,worktreeConcurrency:t.worktreeConcurrency,worktreeConcurrencyLimit:null}))].sort((e,t)=>new Date(e.queuedAt).getTime()-new Date(t.queuedAt).getTime()||e.id.localeCompare(t.id))}async runQueueForWorkflowRun(e){let t=await (0,t1.getPrismaClient)(),r=await t.workflowRun.findUnique({where:{id:e},select:{status:!0,worktreeId:!0,workflowId:!0}});return r&&"QUEUED"===r.status?r.worktreeId?this.queueForWorktree(r.worktreeId):(await this.runQueue({workflowId:r.workflowId})).filter(({worktreeId:e})=>!e):[]}async notifyRun(e,t,r,i,a){if(!this.notifications)return;let n=await (0,t1.getPrismaClient)(),s=await n.workflowRun.findUnique({where:{id:e},select:{sessionDataJson:!0,workflow:{select:{completionNotificationsEnabled:!0}}}});if("WORKFLOW_COMPLETED"===t&&s?.workflow.completionNotificationsEnabled===!1)return;let o=s?await this.runWorktree(s.sessionDataJson):null,l=await n.$transaction(n=>this.notifications.recordInTransaction(n,{dedupeKey:`workflow:${e}:${a}`,typeKey:t,title:r,body:i,href:`/workflows/runs/${e}`,resourceKind:"WORKFLOW_RUN",resourceId:e,worktreeId:o?.id??null,highlightColor:o?.highlightColor??null}));this.notifications.created(l)}startRuntime(){this.runtimeTimer||(this.consumeCommandOutputMatches(),this.runtimeTimer=setInterval(()=>{this.tick().catch(e=>{console.error("Workflow runtime tick failed:",e)})},1e3),this.runtimeTimer.unref?.(),this.tick().catch(e=>{console.error("Workflow runtime startup failed:",e)}))}stopRuntime(){for(let e of(this.runtimeTimer&&clearInterval(this.runtimeTimer),this.runtimeTimer=void 0,this.commandOutputStream?.return?.(),this.commandOutputStream=void 0,this.activeExecutions.values()))e.abort();this.activeExecutions.clear()}catalog(){return{schemaVersion:iC.WORKFLOW_SCHEMA_VERSION,globalConcurrency:4,steps:iC.WORKFLOW_STEP_CATALOG,triggers:iC.WORKFLOW_TRIGGER_CATALOG}}registerWaitPoller(e,t){this.waitPollers.set(e,t)}async list(e={}){let t=await (0,t1.getPrismaClient)(),r=Math.min(Math.max(e.first??100,1),200),i=e.archive?.toUpperCase()??"ACTIVE",a=e.search?.trim(),n=await t.workflow.findMany({where:{..."ALL"===i?{}:"ARCHIVED"===i?{archivedAt:{not:null}}:{archivedAt:null},...null===e.enabled||void 0===e.enabled?{}:{enabled:e.enabled},...a?{OR:[{name:{contains:a}},{description:{contains:a}}]}:{}},include:{activeVersion:!0,quickActionRepositories:{include:{repository:!0}},_count:{select:{versions:!0,runs:!0}}},orderBy:[{updatedAt:"desc"},{id:"desc"}],take:r+1,...e.after?{cursor:{id:e.after},skip:1}:{}});return{items:n.slice(0,r),nextCursor:n.length>r?n[r-1].id:null,totalCount:await t.workflow.count()}}async get(e){return(await (0,t1.getPrismaClient)()).workflow.findUnique({where:{id:e},include:{activeVersion:!0,versions:{orderBy:{version:"desc"}},quickActionRepositories:{include:{repository:!0}},_count:{select:{runs:!0}}}})}async version(e){return(await (0,t1.getPrismaClient)()).workflowVersion.findUnique({where:{id:e},include:{triggers:!0}})}async create(e){let t=oz(e.name,"Workflow name",200),r=(0,iC.parseWorkflowDefinition)(e.definition??(0,iC.emptyWorkflowDefinition)(t)),i=JSON.stringify({...r,name:t,description:e.description?.trim()??r.description});o4(i,"Workflow definition",2097152);let a=oY(e.overlapPolicy),n=oX(e.worktreeConcurrency,e.exclusiveWorktree),s=await (0,t1.getPrismaClient)(),o=await s.workflow.create({data:{id:(0,b.randomUUID)(),name:t,description:e.description?.trim()??r.description,draftDefinitionJson:i,draftSchemaVersion:iC.WORKFLOW_SCHEMA_VERSION,overlapPolicy:a,overlapScope:oZ(e.overlapScope),maxConcurrentRuns:o2(e.maxConcurrentRuns,a),completionNotificationsEnabled:e.completionNotificationsEnabled??!0,exclusiveWorktree:"EXCLUSIVE"===n,worktreeConcurrency:n,blocksGitOperations:o0(n,e.blocksGitOperations)}});return o8(o.id),this.get(o.id)}async saveDraft(e){let t=(0,iC.parseWorkflowDefinition)(e.definition),r=JSON.stringify(t);o4(r,"Workflow definition",2097152);let i=await this.get(e.id);if(!i)throw Error("Workflow not found");let a=oY(e.overlapPolicy??i.overlapPolicy),n=oX(e.worktreeConcurrency??(null===e.exclusiveWorktree||void 0===e.exclusiveWorktree?i.worktreeConcurrency:null),e.exclusiveWorktree??i.exclusiveWorktree),s=await (0,t1.getPrismaClient)();return await s.workflow.update({where:{id:e.id},data:{name:t.name,description:t.description,draftDefinitionJson:r,draftSchemaVersion:t.schemaVersion,overlapPolicy:a,overlapScope:oZ(e.overlapScope??i.overlapScope),maxConcurrentRuns:o2(e.maxConcurrentRuns??i.maxConcurrentRuns,a),completionNotificationsEnabled:e.completionNotificationsEnabled??i.completionNotificationsEnabled,exclusiveWorktree:"EXCLUSIVE"===n,worktreeConcurrency:n,blocksGitOperations:o0(n,e.blocksGitOperations??i.blocksGitOperations)}}),o8(e.id),this.get(e.id)}async validateDraft(e){let t=await this.get(e);if(!t)throw Error("Workflow not found");let r=(0,iC.validateWorkflowDefinition)(oV(t.draftDefinitionJson)),i=[...r.diagnostics];if(r.definition){for(let e of r.definition.nodes){if("SAVED_COMMAND"===e.kind||"CUSTOM_COMMAND"===e.kind){let t=(0,sY.commandOutputPattern)(e.config);if(t)try{sX(t)}catch(t){i.some(({code:t,nodeId:r})=>"COMMAND_MATCH_PATTERN_INVALID"===t&&r===e.id)||i.push({severity:"ERROR",code:"COMMAND_MATCH_PATTERN_INVALID",message:t instanceof Error?t.message:String(t),nodeId:e.id})}}try{!function e(t){let r=oK(t);if("ALL"===r.op||"ANY"===r.op){if(Array.isArray(r.conditions))for(let t of r.conditions)e(t);return}if("NOT"===r.op)return void e(r.condition);if("MATCHES"!==r.op)return;let i=function(e){if("string"==typeof e)return e;let t=oK(e);return"LITERAL"===t.source&&"string"==typeof t.value?t.value:null}(r.right);null!==i&&(0,sZ.compileRe2)(i,{label:"Workflow condition pattern"})}(e.config.condition)}catch(t){i.push({severity:"ERROR",code:"WORKFLOW_REGEX_PATTERN_INVALID",message:t instanceof Error?t.message:String(t),nodeId:e.id})}}for(let e of r.definition.triggers){let t="GITHUB_ISSUE_COMMAND"===e.kind||"JIRA_ISSUE_COMMAND"===e.kind?e.config.commandPattern:"COMMAND_OUTPUT_MATCH"===e.kind?e.config.outputPattern:null;if("string"==typeof t)try{(0,sZ.compileRe2)(t,{label:"COMMAND_OUTPUT_MATCH"===e.kind?"Command output trigger pattern":"Issue command pattern"})}catch(t){i.some(({code:t,triggerId:r})=>"WORKFLOW_REGEX_PATTERN_INVALID"===t&&r===e.id)||i.push({severity:"ERROR",code:"WORKFLOW_REGEX_PATTERN_INVALID",message:t instanceof Error?t.message:String(t),triggerId:e.id})}}i.push(...await this.validateSubworkflows(t.id,r.definition))}return{valid:!(0,iC.hasWorkflowErrors)(i),diagnostics:i}}async validateSubworkflows(e,t){let r=t.nodes.filter(({kind:e})=>"CONTROL_SUBWORKFLOW"===e).map(e=>({node:e,versionId:e.config.versionId})).filter(e=>"string"==typeof e.versionId);if(!r.length)return[];let i=await (0,t1.getPrismaClient)(),a=new Map,n=new Map,s=new Set,o=new Set,l=r.map(({versionId:e})=>e);for(;l.length;){let e=[...new Set(l)].filter(e=>!o.has(e));if(!e.length)break;for(let t of(e.forEach(e=>o.add(e)),l=[],await i.workflowVersion.findMany({where:{id:{in:e}}}))){a.set(t.id,t);try{let e=(0,iC.parseWorkflowDefinition)(oV(t.definitionJson)).nodes.filter(({kind:e})=>"CONTROL_SUBWORKFLOW"===e).map(({config:e})=>e.versionId).filter(e=>"string"==typeof e);n.set(t.id,e),l.push(...e)}catch{s.add(t.id)}}}let c=(e,t)=>{let r=a.get(e);if(!r)return"MISSING";if(s.has(e))return"INVALID";if(t.has(r.workflowId))return"RECURSIVE";let i=new Set(t).add(r.workflowId);for(let t of n.get(e)??[]){let e=c(t,i);if(e)return e}return null},u=[];for(let{node:t,versionId:i}of r){let r=c(i,new Set([e]));"MISSING"===r?u.push({severity:"ERROR",code:"SUBWORKFLOW_NOT_FOUND",message:"Pinned sub-workflow chain contains a missing version",nodeId:t.id}):"INVALID"===r?u.push({severity:"ERROR",code:"SUBWORKFLOW_INVALID",message:"Pinned sub-workflow chain contains an invalid definition",nodeId:t.id}):"RECURSIVE"===r&&u.push({severity:"ERROR",code:"SUBWORKFLOW_RECURSION",message:"Pinned sub-workflow calls cannot form a recursive chain",nodeId:t.id})}return u}async publish(e){let t=await this.get(e);if(!t)throw Error("Workflow not found");let r=(0,iC.parseWorkflowDefinition)(oV(t.draftDefinitionJson)),i=await this.validateDraft(e);if(!i.valid)throw Error(`Workflow cannot be published: ${i.diagnostics.filter(({severity:e})=>"ERROR"===e).map(({message:e})=>e).slice(0,5).join("; ")}`);let a=await (0,t1.getPrismaClient)(),n=await a.$transaction(async t=>{let i=await t.workflowVersion.findFirst({where:{workflowId:e},orderBy:{version:"desc"}}),a=(0,b.randomUUID)(),n=await t.workflowVersion.create({data:{id:a,workflowId:e,version:(i?.version??0)+1,name:r.name,description:r.description,schemaVersion:r.schemaVersion,definitionJson:JSON.stringify(r),contentHash:(0,b.createHash)("sha256").update(o3(r)).digest("hex"),triggers:{create:r.triggers.map(e=>({id:(0,b.randomUUID)(),nodeId:e.id,kind:e.kind,configJson:JSON.stringify(e.config)}))}},include:{triggers:!0}});return await t.workflow.update({where:{id:e},data:{activeVersionId:a}}),n});return o8(e),n}async setEnabled(e,t){let r=await (0,t1.getPrismaClient)(),i=await r.workflow.findUnique({where:{id:e}});if(!i)throw Error("Workflow not found");if(t&&!i.activeVersionId)throw Error("Publish the workflow before enabling it");return await r.workflow.update({where:{id:e},data:{enabled:t}}),o8(e),this.get(e)}async setQuickAction(e){let t=await (0,t1.getPrismaClient)(),r=[...new Set(e.repositoryIds.map(e=>e.trim()).filter(Boolean))],[i,a]=await Promise.all([t.workflow.findUnique({where:{id:e.id},select:{id:!0}}),t.codebaseRepository.count({where:{id:{in:r}}})]);if(!i)throw Error("Workflow not found");if(a!==r.length)throw Error("One or more repositories were not found");let n=e.quickActionIconKey.trim();if(!iR.WORKFLOW_QUICK_ACTION_KINDS.includes(e.kind))throw Error("Quick action kind is invalid");if("none"!==n&&!v.BUILD_CONFIGURATION_ICON_KEYS.includes(n))throw Error("Quick action icon is invalid");let s=e.quickActionButtonVariant.trim();if(!["default","outline","secondary","destructive"].includes(s))throw Error("Quick action button style is invalid");return await t.$transaction(async t=>{await t.workflow.update({where:{id:e.id},data:{quickActionKind:e.kind,quickActionIconKey:n,quickActionButtonVariant:s}}),await t.workflowQuickActionRepository.deleteMany({where:{workflowId:e.id}}),r.length&&await t.workflowQuickActionRepository.createMany({data:r.map(t=>({workflowId:e.id,repositoryId:t}))})}),o8(e.id),this.get(e.id)}async archive(e,t){let r=await (0,t1.getPrismaClient)();return await r.workflow.update({where:{id:e},data:{archivedAt:t?new Date:null,...t?{enabled:!1}:{}}}),o8(e),this.get(e)}async delete(e){let t=await (0,t1.getPrismaClient)();if(await t.workflowRun.count({where:{workflowId:e}}))throw Error("Archive workflows that have run history instead of deleting them");return await t.workflow.delete({where:{id:e}}),o8(e),!0}export(e,t){return this.exportInternal(e,t)}async exportInternal(e,t){let r=await this.get(e);if(!r)throw Error("Workflow not found");let i=t?r.versions.find(e=>e.id===t):null;if(t&&!i)throw Error("Workflow version not found");let a=(0,iC.parseWorkflowDefinition)(oV(i?.definitionJson??r.draftDefinitionJson));return{format:"aide.workflow.export",schemaVersion:iC.WORKFLOW_SCHEMA_VERSION,exportedAt:new Date().toISOString(),workflow:{name:i?.name??r.name,description:i?.description??r.description,overlapPolicy:r.overlapPolicy,overlapScope:r.overlapScope,maxConcurrentRuns:r.maxConcurrentRuns,completionNotificationsEnabled:r.completionNotificationsEnabled,exclusiveWorktree:r.exclusiveWorktree,worktreeConcurrency:r.worktreeConcurrency,blocksGitOperations:r.blocksGitOperations,definition:(0,iC.sanitizeWorkflowExportDefinition)(a)}}}async import(e){o4("string"==typeof e.payload?e.payload:JSON.stringify(e.payload),"Workflow import",2097152);let t=o6("string"==typeof e.payload?JSON.parse(e.payload):e.payload,"Workflow import"),r="aide.workflow.export"===t.format,i=r?o6(t.workflow,"Exported workflow"):t,a=(0,iC.parseWorkflowDefinition)(r?i.definition:i);return this.create({name:e.name?.trim()||a.name,description:a.description,definition:{...a,name:e.name?.trim()||a.name},overlapPolicy:"string"==typeof i.overlapPolicy?i.overlapPolicy:"QUEUE",overlapScope:"string"==typeof i.overlapScope?i.overlapScope:!0===i.exclusiveWorktree?"WORKTREE":"GLOBAL",maxConcurrentRuns:"number"==typeof i.maxConcurrentRuns?i.maxConcurrentRuns:1,completionNotificationsEnabled:"boolean"!=typeof i.completionNotificationsEnabled||i.completionNotificationsEnabled,worktreeConcurrency:"string"==typeof i.worktreeConcurrency?i.worktreeConcurrency:!0===i.exclusiveWorktree?"EXCLUSIVE":"NON_EXCLUSIVE",blocksGitOperations:"boolean"==typeof i.blocksGitOperations?i.blocksGitOperations:!0===i.exclusiveWorktree,exclusiveWorktree:"boolean"==typeof i.exclusiveWorktree&&i.exclusiveWorktree})}async runs(e={}){let t=await (0,t1.getPrismaClient)(),r=Math.min(Math.max(e.first??100,1),200),i=Number(e.search),a=e.archive?.toUpperCase()??"ACTIVE",n="ALL"===a?{}:"ARCHIVED"===a?{archivedAt:{not:null}}:{archivedAt:null},s=await t.workflowRun.findMany({where:{...n,...e.workflowId?{workflowId:e.workflowId}:{},...e.status?{status:e.status.toUpperCase()}:{},...Number.isInteger(i)&&i>0?{displayNumber:i}:e.search?.trim()?{workflow:{name:{contains:e.search.trim()}}}:{}},include:{workflow:!0,version:!0,trigger:!0,_count:{select:{attempts:!0,events:!0}}},orderBy:[{createdAt:"desc"},{id:"desc"}],take:r+1,...e.after?{cursor:{id:e.after},skip:1}:{}});return{items:s.slice(0,r),nextCursor:s.length>r?s[r-1].id:null,totalCount:await t.workflowRun.count({where:{...n,...e.workflowId?{workflowId:e.workflowId}:{}}})}}async archiveRuns(e,t){let r=await (0,t1.getPrismaClient)(),i=[...new Set(e)],a=await r.workflowRun.updateMany({where:{id:{in:i}},data:{archivedAt:t?new Date:null}});for(let e of i)o5(e);return a.count}async deleteRuns(e){let t=await (0,t1.getPrismaClient)(),r=[...new Set(e)];if(await t.workflowRun.count({where:{id:{in:r},status:{notIn:["SUCCEEDED","FAILED","CANCELLED"]}}}))throw Error("Cancel runs that have not finished before deleting them");let i=await t.workflowRun.deleteMany({where:{id:{in:r}}});for(let e of r)o5(e);return i.count}async run(e){return(await (0,t1.getPrismaClient)()).workflowRun.findUnique({where:{id:e},include:{workflow:!0,version:!0,trigger:!0,parentRun:!0,childRuns:{orderBy:{createdAt:"asc"}},attempts:{orderBy:[{generation:"asc"},{nodeId:"asc"},{iterationKey:"asc"},{attempt:"asc"}],include:{waits:{orderBy:{createdAt:"asc"}},resourceLinks:{orderBy:{createdAt:"asc"}},questionBatches:{orderBy:{createdAt:"asc"},include:{questions:{orderBy:{position:"asc"},include:{options:{orderBy:{position:"asc"}}}},answerRevisions:{orderBy:{revision:"asc"}},checkpoint:!0}},checkpoints:{orderBy:{createdAt:"asc"}}}},waits:{orderBy:{createdAt:"asc"}},events:{orderBy:{sequence:"asc"}},resourceLinks:{orderBy:{createdAt:"asc"}}}})}async runEvents(e,t=-1,r=500){return(await (0,t1.getPrismaClient)()).workflowRunEvent.findMany({where:{runId:e,sequence:{gt:t}},orderBy:{sequence:"asc"},take:Math.min(Math.max(r,1),1e3)})}async questionBatch(e){return(await (0,t1.getPrismaClient)()).runQuestionBatch.findUnique({where:{id:e},include:{questions:{orderBy:{position:"asc"},include:{options:{orderBy:{position:"asc"}}}},answerRevisions:{orderBy:{revision:"asc"}},checkpoint:!0}})}async jobSecrets(e,t){if(!this.credentials||!this.agentControl)throw Error("Workflow credentials are unavailable");if(this.claimedSecretJobs.has(t))throw Error("Workflow job secrets were already claimed");let r=await this.agentControl.getJob(t);if(!r||r.agentId!==e||"workflow.terminal.run"!==r.kind||"RUNNING"!==r.status)throw Error("Workflow job is not eligible to claim secrets");let i=(0,oT.parseWorkflowTerminalPayload)(oV(r.payloadJson)),a=new Set(Object.values(t2.CREDENTIAL_KINDS)),n=[];for(let e of i.credentialEnvironment){if(!a.has(e.credential.kind))throw Error("Workflow references an unsupported credential kind");let t=await this.credentials.getText(e.credential);if(null===t)throw Error(`Credential ${e.credential.id} is unavailable`);n.push({name:e.name,value:t})}return this.claimedSecretJobs.add(t),n}async workflowAgentContext(e){let t=await (0,t1.getPrismaClient)(),r=(0,st.getSessionValue)(e,"worktree.id");if("string"==typeof r){let e=await t.worktree.findUnique({where:{id:r},include:{codebase:{include:{agent:!0}}}});if(!e)throw Error("Workflow worktree is unavailable");let i=JSON.parse(e.codebase.agent.capabilitiesJson);return{agentId:e.codebase.agentId,codebaseId:e.codebaseId,worktreeId:e.id,cwd:e.folder,capabilities:Array.isArray(i)?i.filter(e=>"string"==typeof e):[]}}let i=(0,st.getSessionValue)(e,"codebase.id");if("string"!=typeof i)throw Error("Workflow requires a codebase or worktree");let a=await t.codebase.findUnique({where:{id:i},include:{agent:!0}});if(!a)throw Error("Workflow codebase is unavailable");let n=JSON.parse(a.agent.capabilitiesJson);return{agentId:a.agentId,codebaseId:a.id,worktreeId:null,cwd:a.folder,capabilities:Array.isArray(n)?n.filter(e=>"string"==typeof e):[]}}async startTerminalJob(e){if(!this.agentControl)throw Error("Agent control is unavailable");let t=await this.workflowAgentContext(e.sessionData);if(!t.capabilities.includes(oT.WORKFLOW_TERMINAL_JOB_KIND))throw Error("The selected agent must be updated to run workflow terminal steps");let r={...e.node.config.environment&&"object"==typeof e.node.config.environment&&!Array.isArray(e.node.config.environment)?Object.fromEntries(Object.entries(e.node.config.environment).map(([e,t])=>[e,String(t)])):{},AIDE_TICKET_KEY:String((0,st.getSessionValue)(e.sessionData,"ticket.key")??""),AIDE_TICKET_TITLE:String((0,st.getSessionValue)(e.sessionData,"ticket.title")??""),AIDE_BRANCH:String((0,st.getSessionValue)(e.sessionData,"worktree.branch")??""),AIDE_BASE_BRANCH:String((0,st.getSessionValue)(e.sessionData,"worktree.baseBranch")??""),AIDE_WORKTREE_PATH:String((0,st.getSessionValue)(e.sessionData,"worktree.path")??t.cwd),AIDE_CODEBASE_PATH:String((0,st.getSessionValue)(e.sessionData,"codebase.folder")??t.cwd),AIDE_REPO_ORIGIN:String((0,st.getSessionValue)(e.sessionData,"repo.displayOrigin")??"")},i=Array.isArray(e.node.config.credentials)?e.node.config.credentials:[],a=await this.agentControl.createJob({agentId:t.agentId,kind:oT.WORKFLOW_TERMINAL_JOB_KIND,payload:{workflowRunId:e.run.id,stepAttemptId:e.attempt.id,stepId:e.node.id,codebaseId:t.codebaseId,worktreeId:t.worktreeId,cwd:t.cwd,script:oz(String(e.node.config.script??""),"Terminal script",1e6),interpreter:"NODE"===e.node.config.interpreter?"NODE":"SHELL",sessionData:e.sessionData,environment:r,credentialEnvironment:i},idempotencyKey:e.attempt.idempotencyKey,timeoutSeconds:Number(e.node.config.timeoutSeconds??900),codebaseId:t.codebaseId,worktreeId:t.worktreeId,visibility:"SYSTEM",blocksGitOperations:e.run.blocksGitOperations});return{output:{jobId:a.id},links:[{kind:"AGENT_JOB",resourceId:a.id,label:"Workflow terminal job",url:`/jobs/${a.id}`}],wait:{kind:"AGENT_JOB",externalKey:a.id,resumeAfter:s3(e.node.config),timeoutAt:s1(e.node.config,900)}}}async startCheckpointJob(e){if(!this.agentControl)throw Error("Agent control is unavailable");let t=await this.workflowAgentContext(e.sessionData);if(!t.capabilities.includes(oT.WORKFLOW_GIT_CHECKPOINT_JOB_KIND))throw Error("The selected agent must be updated to capture workflow checkpoints");let r=await this.agentControl.createJob({agentId:t.agentId,kind:oT.WORKFLOW_GIT_CHECKPOINT_JOB_KIND,payload:{operation:"CAPTURE",workflowRunId:e.run.id,stepAttemptId:e.attempt.id,cwd:t.cwd,kind:String(e.node.config.kind??"STEP"),checkpoint:null,stash:!1},idempotencyKey:e.attempt.idempotencyKey,timeoutSeconds:300,codebaseId:t.codebaseId,worktreeId:t.worktreeId,visibility:"SYSTEM"});return{output:{jobId:r.id},links:[{kind:"AGENT_JOB",resourceId:r.id,label:"Workflow checkpoint job",url:`/jobs/${r.id}`}],wait:{kind:"AGENT_JOB",externalKey:r.id,resumeAfter:s3(e.node.config),timeoutAt:s1(e.node.config)}}}async workflowAgentJobCompleted(e){if(e.kind===oT.WORKFLOW_TERMINAL_JOB_KIND){let t=(0,oT.parseWorkflowTerminalPayload)(oV(e.payloadJson));if("SUCCEEDED"!==e.status||!e.resultJson)return void await this.resolveExternalWait("AGENT_JOB",e.id,{jobId:e.id,status:e.status},e.error||`Workflow terminal job ${e.status.toLowerCase()}`);let r=o6(oV(e.resultJson),"Workflow terminal result");return void await this.resolveExternalWait("AGENT_JOB",e.id,{...r,jobId:e.id,stepAttemptId:t.stepAttemptId})}if(e.kind!==oT.WORKFLOW_GIT_CHECKPOINT_JOB_KIND)return;let t=(0,oT.parseWorkflowGitCheckpointPayload)(oV(e.payloadJson));if("SUCCEEDED"!==e.status||!e.resultJson)return void await this.resolveExternalWait("AGENT_JOB",e.id,{jobId:e.id,status:e.status},e.error||`Workflow checkpoint job ${e.status.toLowerCase()}`);let r=o6(oV(e.resultJson),"Workflow checkpoint result"),i=null;if(r.checkpoint&&"object"==typeof r.checkpoint){let e=r.checkpoint,a=await (0,t1.getPrismaClient)();i=(0,b.randomUUID)(),await a.$transaction([a.runCheckpoint.create({data:{id:i,workflowStepAttemptId:t.stepAttemptId,kind:String(e.kind??t.kind),headSha:"string"==typeof e.headSha?e.headSha:null,branch:"string"==typeof e.branch?e.branch:null,upstreamSha:"string"==typeof e.upstreamSha?e.upstreamSha:null,indexTree:"string"==typeof e.indexTree?e.indexTree:null,worktreeTree:"string"==typeof e.worktreeTree?e.worktreeTree:null,refName:"string"==typeof e.refName?e.refName:null,manifestJson:"string"==typeof e.manifestJson?e.manifestJson:null,diffSummary:"string"==typeof e.diffSummary?e.diffSummary:null,diffPatch:"string"==typeof e.diffPatch?e.diffPatch:null,stashRef:"string"==typeof r.stashRef?r.stashRef:"string"==typeof e.stashRef?e.stashRef:null}}),a.workflowRunResourceLink.create({data:{id:(0,b.randomUUID)(),runId:t.workflowRunId,attemptId:t.stepAttemptId,kind:"CHECKPOINT",resourceId:i,label:`${String(e.kind??t.kind)} checkpoint`}})])}await this.resolveExternalWait("AGENT_JOB",e.id,{...r,jobId:e.id,checkpointId:i})}async genericAgentJobCompleted(e){if(e.kind===oT.WORKFLOW_TERMINAL_JOB_KIND||e.kind===oT.WORKFLOW_GIT_CHECKPOINT_JOB_KIND)return;let t=e.resultJson?o6(oV(e.resultJson),"Agent job result"):{status:e.status};if("SUCCEEDED"===e.status){let r=await (0,t1.getPrismaClient)(),i=t.worktree&&"object"==typeof t.worktree&&!Array.isArray(t.worktree)?t.worktree:null,a=i&&"string"==typeof i.gitDirectory?i.gitDirectory:null,n=e.codebaseId?await r.worktree.findFirst({where:{codebaseId:e.codebaseId,...e.worktreeId?{id:e.worktreeId}:a?{gitDirectory:a}:{id:"__missing__"}},include:{codebase:{include:{repository:!0,agent:!0}}}}):null,s=n?.codebase??(e.codebaseId?await r.codebase.findUnique({where:{id:e.codebaseId},include:{repository:!0,agent:!0}}):null),o={};if(n&&this.worktrees?.workflowSessionDataForWorktree)try{o=await this.worktrees.workflowSessionDataForWorktree(n.id,{includeMissing:!0})}catch{}if(s&&!o.codebase&&(o.repo={id:s.repository.id,name:s.repository.name,url:s.repository.displayOrigin,canonicalOrigin:s.repository.canonicalOrigin,displayOrigin:s.repository.displayOrigin,defaultBranch:s.defaultBranch},o.codebase={id:s.id,folder:s.folder,agentId:s.agentId,branch:s.defaultBranch,headSha:s.headSha},o.agent={id:s.agent.id,name:s.agent.name,hostname:s.agent.hostname}),n&&!o.worktree&&(o.worktree={id:n.id,path:n.folder,branch:n.branch,baseBranch:n.baseBranchOverride??n.codebase.defaultBranch,headSha:n.headSha,pushStatus:n.pushStatus,ahead:n.ahead,behind:n.behind,baseBehind:n.baseBehind,dirty:n.hasStagedChanges||n.hasUnstagedChanges}),Object.keys(o).length){let e=t.sessionPatch&&"object"==typeof t.sessionPatch&&!Array.isArray(t.sessionPatch)?t.sessionPatch:{};t={...t,sessionPatch:(0,st.mergeSessionData)(e,o)}}}await this.resolveExternalWait("AGENT_JOB",e.id,{...t,jobId:e.id,status:e.status},"SUCCEEDED"===e.status?null:e.error||`Agent job ${e.status.toLowerCase()}`)}async restoreCheckpointWithAgent(e,t){if(!this.agentControl)throw Error("Agent control is unavailable");let r=await (0,t1.getPrismaClient)(),i=await r.runCheckpoint.findUnique({where:{id:e},include:{workflowStepAttempt:{include:{run:!0}}}}),a=i?.workflowStepAttempt;if(!i||!a)throw Error("Workflow checkpoint not found");let n=await this.workflowAgentContext((0,st.workflowSessionData)(a.run.sessionDataJson)),s=await this.agentControl.createJob({agentId:n.agentId,kind:oT.WORKFLOW_GIT_CHECKPOINT_JOB_KIND,payload:{operation:"RESTORE",workflowRunId:a.runId,stepAttemptId:a.id,cwd:n.cwd,kind:"REPLAY_RESTORE",checkpoint:{headSha:i.headSha,branch:i.branch,upstreamSha:i.upstreamSha,indexTree:i.indexTree,worktreeTree:i.worktreeTree,refName:i.refName},stash:t.stash},idempotencyKey:`workflow:restore:${e}:${(0,b.randomUUID)()}`,timeoutSeconds:300,codebaseId:n.codebaseId,worktreeId:n.worktreeId,visibility:"SYSTEM"}),o=Date.now()+3e5;for(;Date.now()<o;){let e=await this.agentControl.getJob(s.id);if(!e)throw Error("Workflow restore job disappeared");if(new Set(["SUCCEEDED","FAILED","CANCELLED","TIMED_OUT"]).has(e.status)){if("SUCCEEDED"!==e.status)throw Error(e.error||`Workflow restore job ${e.status.toLowerCase()}`);return}await new Promise(e=>setTimeout(e,250))}throw await this.agentControl.cancelJob(s.id),Error("Workflow restore job timed out")}async compareCheckpointWithAgent(e){if(!this.agentControl)throw Error("Agent control is unavailable");let t=await (0,t1.getPrismaClient)(),r=await t.runCheckpoint.findUnique({where:{id:e},include:{workflowStepAttempt:{include:{run:!0}}}}),i=r?.workflowStepAttempt;if(!r||!i)throw Error("Workflow checkpoint not found");let a=await this.workflowAgentContext((0,st.workflowSessionData)(i.run.sessionDataJson)),n=await this.agentControl.createJob({agentId:a.agentId,kind:oT.WORKFLOW_GIT_CHECKPOINT_JOB_KIND,payload:{operation:"COMPARE",workflowRunId:i.runId,stepAttemptId:i.id,cwd:a.cwd,kind:"REPLAY_PREVIEW",checkpoint:{headSha:r.headSha,branch:r.branch,upstreamSha:r.upstreamSha,indexTree:r.indexTree,worktreeTree:r.worktreeTree,refName:r.refName},stash:!1},idempotencyKey:`workflow:compare:${e}:${(0,b.randomUUID)()}`,timeoutSeconds:60,codebaseId:a.codebaseId,worktreeId:a.worktreeId,visibility:"SYSTEM"}),s=Date.now()+6e4;for(;Date.now()<s;){let e=await this.agentControl.getJob(n.id);if(!e)throw Error("Workflow comparison job disappeared");if(new Set(["SUCCEEDED","FAILED","CANCELLED","TIMED_OUT"]).has(e.status)){if("SUCCEEDED"!==e.status||!e.resultJson)throw Error(e.error||`Workflow comparison job ${e.status.toLowerCase()}`);let t=o6(oV(e.resultJson),"Workflow comparison result");return o6(t.comparison,"Git checkpoint comparison")}await new Promise(e=>setTimeout(e,250))}throw await this.agentControl.cancelJob(n.id),Error("Workflow comparison job timed out")}async runsForResource(e,t){let r=await (0,t1.getPrismaClient)(),i=await r.workflowRunResourceLink.findMany({where:{kind:e.trim().toUpperCase(),resourceId:t.trim()},select:{runId:!0},distinct:["runId"],orderBy:{createdAt:"desc"}});return r.workflowRun.findMany({where:{id:{in:i.map(({runId:e})=>e)}},include:{workflow:!0,version:!0,trigger:!0,attempts:{orderBy:[{generation:"asc"},{createdAt:"asc"}],include:{resourceLinks:{orderBy:{createdAt:"asc"}},questionBatches:{orderBy:{createdAt:"asc"},include:{questions:{orderBy:{position:"asc"},include:{options:{orderBy:{position:"asc"}}}}}}}},resourceLinks:{orderBy:{createdAt:"asc"}}},orderBy:{createdAt:"desc"}})}async acceptingResource(e){let t=e.trim().toUpperCase(),r=await (0,t1.getPrismaClient)();return(await r.workflow.findMany({where:{enabled:!0,archivedAt:null,activeVersionId:{not:null}},include:{activeVersion:!0},orderBy:{name:"asc"}})).filter(e=>!!e.activeVersion&&(0,iC.parseWorkflowDefinition)(oV(e.activeVersion.definitionJson)).triggers.some(e=>(0,iR.isResourceTriggerKind)(e.kind)&&(0,iC.workflowResourceKind)(e.config)===t))}async quickActions(e){let t=await (0,t1.getPrismaClient)();if(!iR.WORKFLOW_QUICK_ACTION_KINDS.includes(e.kind))throw Error("Quick action kind is invalid");let r=e.resourceKind.trim().toUpperCase(),i=e.repositoryId?.trim()||null;return(await t.workflow.findMany({where:{enabled:!0,archivedAt:null,activeVersionId:{not:null},quickActionKind:e.kind,OR:[{quickActionRepositories:{none:{}}},{quickActionRepositories:{some:{repositoryId:i??""}}}]},include:{activeVersion:!0},orderBy:[{name:"asc"},{id:"asc"}]})).filter(e=>!!e.activeVersion&&(0,iC.parseWorkflowDefinition)(oV(e.activeVersion.definitionJson)).triggers.some(e=>(0,iR.isResourceTriggerKind)(e.kind)&&(0,iC.workflowResourceKind)(e.config)===r))}async recordEvent(e){return this.events.record(e)}async hydrateResourceSessionData(e,t,r){let i=e?.toUpperCase()??null,a=await (0,t1.getPrismaClient)(),n={},s=null;if("CODEBASE"===i&&t){let e=await a.codebase.findUnique({where:{id:t},select:{id:!0,folder:!0,agentId:!0,branch:!0,headSha:!0,defaultBranch:!0,agent:{select:{id:!0,name:!0,hostname:!0,lastSeenAt:!0,disconnectedAt:!0,heartbeatIntervalSeconds:!0,diskFreeBytes:!0,memoryFreeBytes:!0}},repository:{select:{id:!0,name:!0,canonicalOrigin:!0,displayOrigin:!0}}}});e&&(n=oJ(e))}if("BUILD"===i&&t){let e=await a.build.findUnique({where:{id:t},select:{id:!0,status:!0,action:!0,error:!0,artifactDirectory:!0,worktreeId:!0,agent:{select:{id:!0,name:!0,hostname:!0,lastSeenAt:!0,disconnectedAt:!0,heartbeatIntervalSeconds:!0,diskFreeBytes:!0,memoryFreeBytes:!0}},codebase:{select:{id:!0,folder:!0,agentId:!0,branch:!0,headSha:!0,defaultBranch:!0,agent:{select:{id:!0,name:!0,hostname:!0,lastSeenAt:!0,disconnectedAt:!0,heartbeatIntervalSeconds:!0,diskFreeBytes:!0,memoryFreeBytes:!0}},repository:{select:{id:!0,name:!0,canonicalOrigin:!0,displayOrigin:!0}}}},artifacts:{select:{id:!0,kind:!0,relativePath:!0,sizeBytes:!0,checksum:!0}},reports:{where:{status:"READY"},select:{kind:!0,summaryJson:!0}}}});if(e){s=e.worktreeId;let t=t=>{let r=e.reports.find(e=>e.kind===t);if(r)try{return(0,st.workflowSessionData)(r.summaryJson)}catch{return}},r=t("TEST_RESULTS"),i=t("CODE_COVERAGE");n=(0,st.mergeSessionData)(e.codebase?oJ(e.codebase):e.agent?oW(e.agent):{},{build:{id:e.id,status:e.status,action:e.action,error:e.error,artifactDirectory:e.artifactDirectory,artifacts:e.artifacts,...r?{testSummary:r}:{},...i?{coverageSummary:i}:{}}})}}if("AGENT_RUN"===i&&t){let e=await a.agentRun.findUnique({where:{id:t},select:{id:!0,kind:!0,status:!0,phase:!0,origin:!0,provider:!0,model:!0,branch:!0,finalOutput:!0,error:!0,jiraIssueKey:!0,worktreeId:!0,agent:{select:{id:!0,name:!0,hostname:!0,disconnectedAt:!0,diskFreeBytes:!0,memoryFreeBytes:!0}},inputTokens:!0,outputTokens:!0,reasoningTokens:!0,cacheReadTokens:!0,cacheWriteTokens:!0,toolCallCount:!0,estimatedCost:!0}});e&&(s=e.worktreeId,n=(0,st.mergeSessionData)(e.agent?oW(e.agent):{},{run:{id:e.id,kind:e.kind,status:e.status,phase:e.phase,origin:e.origin,provider:e.provider,model:e.model,branch:e.branch,finalOutput:e.finalOutput,error:e.error,usage:{inputTokens:e.inputTokens,outputTokens:e.outputTokens,reasoningTokens:e.reasoningTokens,cacheReadTokens:e.cacheReadTokens,cacheWriteTokens:e.cacheWriteTokens,toolCallCount:e.toolCallCount,estimatedCost:e.estimatedCost}},...e.jiraIssueKey?{ticket:{key:e.jiraIssueKey}}:{}}))}if("PULL_REQUEST"===i&&t&&this.worktrees?.workflowSessionDataForPullRequest){let e=/^([^/]+)\/([^#]+)#([1-9]\d*)$/.exec(t);e&&(n=(0,st.mergeSessionData)(n,await this.worktrees.workflowSessionDataForPullRequest(e[1],e[2],Number(e[3]))))}if("JIRA_TICKET"===i&&t&&this.jiraService)try{let e=await this.jiraService.ticket(t),r=e.comments.at(-1)??null;n=(0,st.mergeSessionData)(n,{ticket:{...e,title:e.summary,type:e.issueType,url:e.jiraUrl},...r?{comment:{id:r.id,body:r.content?.rawText??"",author:r.author}}:{}})}catch{}let o=(0,st.getSessionValue)(r,"worktree.id"),l="WORKTREE"===i?t:"GITHUB_PIPELINE"===i||"GITHUB_JOB"===i?"string"==typeof o?o:null:s;if(l&&this.worktrees)if(this.worktrees.workflowSessionDataForWorktree)n=(0,st.mergeSessionData)(await this.worktrees.workflowSessionDataForWorktree(l),n);else{let e=await this.worktrees.ticketKeyForWorktree(l);e&&(n=(0,st.mergeSessionData)({ticket:{key:e}},n))}let c=(0,st.getSessionValue)(r,"pipeline.pullRequests");!(0,st.getSessionValue)(n,"pr")&&!(0,st.getSessionValue)(r,"pr")&&Array.isArray(c)&&c[0]&&"object"==typeof c[0]&&!Array.isArray(c[0])&&(n=(0,st.mergeSessionData)(n,{pr:c[0]}));let u=(0,st.getSessionValue)(r,"pr.jiraKey")??(0,st.getSessionValue)(r,"pipeline.jiraKey");return"string"!=typeof(0,st.getSessionValue)(n,"ticket.key")&&"string"==typeof u&&u.trim()&&(n=(0,st.mergeSessionData)(n,{ticket:{key:u}})),(0,st.mergeSessionData)(n,r)}async trigger(e){let t=await (0,t1.getPrismaClient)(),r=await t.workflow.findUnique({where:{id:e.workflowId},include:{activeVersion:{include:{triggers:!0}}}});if(!r?.activeVersion)throw Error("Published workflow not found");if(!r.enabled||r.archivedAt)throw Error("Workflow is paused");let i=e.resourceKind?.toUpperCase()??null,a=e.choice?.trim()||null,{triggers:n}=r.activeVersion,s=i?"RESOURCE_MANUAL":"MANUAL",o=i?"RESOURCE_MANUAL_CHOICE":"MANUAL_CHOICE",l=e=>n.find(t=>t.kind===e&&(!i||(0,iC.workflowResourceKind)(o6(oV(t.configJson),"Trigger configuration"))===i))??null,c=l(o),u=l(s),d=a?c:u;if(a&&!c)throw Error(i?`No resource trigger offers choices for ${i} resources`:"This workflow has no manual trigger with choices");if(!a&&!u&&c){let e=(0,iC.workflowTriggerChoices)(o6(oV(c.configJson),"Trigger configuration"));throw Error(`This workflow needs a choice: ${e.map(({key:e})=>e).join(", ")}`)}if(i&&!d)throw Error(`No resource trigger accepts ${e.resourceKind} resources`);if(a&&c&&!(0,iC.workflowTriggerChoices)(o6(oV(c.configJson),"Trigger configuration")).some(({key:e})=>e===a))throw Error(`Unknown choice ${a}`);let p=e.subjectKey?.trim()||(i&&e.resourceId?`${i}:${e.resourceId}`:`manual:${(0,b.randomUUID)()}`),h={sessionData:await this.hydrateResourceSessionData(e.resourceKind,e.resourceId,e.sessionData??{}),resourceKind:e.resourceKind??null,resourceId:e.resourceId??null,choice:a,manual:!0},m=await this.createRunForTrigger(r,r.activeVersion,d,null,a?o:s,p,h,`manual:${r.id}:${(0,b.randomUUID)()}`);return o5(m.id),this.run(m.id)}async createRunForTrigger(e,t,r,i,a,n,s,o,l=null,c=null){return(await (0,t1.getPrismaClient)()).$transaction(async u=>{if(c){let e=await u.workflowTriggerDelivery.findUnique({where:{id:c},include:{run:!0}});if(e)return e.run}let d=async e=>(c&&await u.workflowTriggerDelivery.create({data:{id:c,runId:e.id}}),e),p=await u.workflowRun.findUnique({where:{idempotencyKey:o}});if(p)return d(p);let h=o6(s.sessionData??{},"Session data"),m=(0,st.getSessionValue)(h,"worktree.id"),f="string"==typeof m&&m?(await u.worktree.findUnique({where:{id:m},select:{id:!0}}))?.id??null:null;if("COALESCE_LATEST"===e.overlapPolicy){let t=await u.workflowRun.findFirst({where:{workflowId:e.id,triggerSubjectKey:n,status:"QUEUED",...o1(e.overlapScope,f)},orderBy:{queuedAt:"desc"}});if(t)return d(await u.workflowRun.update({where:{id:t.id},data:{triggerId:r?.id??null,triggerEventId:i,triggerKind:a,triggerPayloadJson:JSON.stringify(s),queuedAt:new Date}}))}let g=(0,b.randomUUID)(),y=JSON.stringify((0,st.mergeSessionData)({workflow:{id:e.id,name:t.name,runId:g,startedAt:null,trigger:{id:r?.nodeId??null,kind:a,subjectKey:n,choice:"string"==typeof s.choice?s.choice:null}},steps:{}},h));o4(y,"Workflow session data",2097152);let w=l?await u.workflowRun.findUnique({where:{id:l},select:{worktreeId:!0,worktreeLeaseOwnerRunId:!0}}):null,v=(w?.worktreeId===f?w.worktreeLeaseOwnerRunId:null)??(!l&&"EXCLUSIVE"===e.worktreeConcurrency&&f?g:null),k=await u.workflowRun.create({data:{id:g,displayNumber:await le(u),workflowId:e.id,versionId:t.id,triggerId:r?.id??null,triggerEventId:i,parentRunId:l,worktreeId:f,worktreeLeaseOwnerRunId:v,exclusiveWorktree:"EXCLUSIVE"===e.worktreeConcurrency,worktreeConcurrency:e.worktreeConcurrency,blocksGitOperations:e.blocksGitOperations,idempotencyKey:o,triggerKind:a,triggerSubjectKey:n,triggerPayloadJson:JSON.stringify(s),sessionDataJson:y,phase:v?"WAITING_FOR_WORKTREE":"QUEUED"}}),E=function(e,t){let r=e.trim().toUpperCase(),i=s$(t.sessionData);if((0,iR.isResourceTriggerKind)(r)){let e=t.resourceKind,r="string"==typeof e?e.toUpperCase():null,a="GITHUB_JOB"===r?sF(i,"job","url"):"GITLAB_JOB"===r?sF(i,"job","webUrl"):"GITHUB_PIPELINE"===r?sF(i,"pipeline","url"):"GITLAB_PIPELINE"===r?sF(i,"pipeline","webUrl"):"GITLAB_MERGE_REQUEST"===r?sF(i,"pr","webUrl"):null;return"string"==typeof e?sG(e.toUpperCase(),t.resourceId,{url:"string"==typeof a?a:null,metadata:"AGENT_RUN"===e.toUpperCase()?{runKind:sF(i,"run","kind")}:null}):null}if(sK.has(r))return sG("JIRA_TICKET",sF(i,"ticket","key"));if(sH.has(r))return sG("AGENT_RUN",sF(i,"run","id"),{metadata:{runKind:sF(i,"run","kind")}});if(sV.has(r))return sG("BUILD",sF(i,"build","id"));if(sW.has(r))return sG("WORKTREE",sF(i,"worktree","id"));if("CODEBASE_REMOTE_BRANCH"===r||"CODEBASE_SYNC_STATE_CHANGED"===r||"CODEBASE_OPERATION_FAILED"===r)return sG("CODEBASE",sF(i,"codebase","id"));if("COMMAND_RUN_RESULT"===r||"COMMAND_OUTPUT_MATCH"===r)return sG("COMMAND_RUN",sF(i,"command","id"));if("SKILL_SYNC_RESULT"===r||"SKILL_SYNC_CONFLICT"===r)return sG("SKILL_SYNC",sF(i,"skillSync","id"));if("IOS_DEVICE_ENROLLED"===r||"IOS_DEVICE_REGISTRATION_RESULT"===r)return sG("IOS_DEVICE",sF(i,"device","id"));if("SIGNING_OPERATION_RESULT"===r||"SIGNING_ASSET_EXPIRING"===r)return sG("SIGNING_PROFILE",sF(i,"signingProfile","id"));if("PUSH_NOTIFICATION_RESULT"===r)return sG("PUSH_NOTIFICATION_BATCH",sF(i,"pushBatch","id"));if("BUILD_DATA_THRESHOLD"===r||"BUILD_DATA_CLEANUP_RESULT"===r)return sG("BUILD_DATA_COLLECTION",sF(i,"buildData","id"));if("AGENT_JOB_FAILED"===r)return sG("AGENT_JOB",sF(s$(i.steps),"trigger","id"));if("AGENT_CONNECTION"===r||"AGENT_DISK_REPORT"===r||"AGENT_DISK_THRESHOLD"===r||"AGENT_DISK_STATE_CHANGED"===r||"AGENT_DISK_CLEANUP_RESULT"===r||"CCUSAGE_THRESHOLD"===r)return sG("AGENT",sF(i,"agent","id")??sF(i,"codebase","agentId"));if("WORKFLOW_FINISHED"===r)return sG("WORKFLOW_RUN",sF(t,"run","id"));if(sJ.has(r)){let e=function(e){if("string"!=typeof e)return null;let t=e.trim(),r=t.match(/(?:https?:\/\/|ssh:\/\/git@|git@)?github\.com[/:]([^/]+)\/([^/#]+?)(?:\.git)?$/i)??t.match(/^([^/:]+)\/([^/#]+?)(?:\.git)?$/);return r?.[1]&&r[2]?{owner:r[1],repository:r[2]}:null}(sF(i,"repo","displayOrigin")),t=Number(sF(i,"pr","number"));return e&&Number.isInteger(t)&&t>0?sG("PULL_REQUEST",sq(e.owner,e.repository,t)):null}if(sz.has(r)){let e=sF(i,"pipeline","url");return sG("GITHUB_WORKFLOW_RUN",sF(i,"pipeline","runId"),{url:"string"==typeof e?e:null})}return"GITHUB_PUSH_DEFAULT"===r?sG("CODEBASE_REPOSITORY",sF(i,"repo","id")):null}(a,s);return E&&await u.workflowRunResourceLink.create({data:{id:(0,b.randomUUID)(),runId:k.id,kind:E.kind.toUpperCase(),resourceId:E.resourceId,label:E.label??null,url:E.url??null,metadataJson:E.metadata?JSON.stringify(E.metadata):null}}),d(k)})}async processTriggerEvents(){let e=await (0,t1.getPrismaClient)(),t=await e.workflowTriggerEvent.findMany({where:{status:"PENDING"},orderBy:{receivedAt:"asc"},take:50});if(!t.length)return;let r=await e.workflow.findMany({where:{enabled:!0,archivedAt:null,activeVersionId:{not:null}},include:{activeVersion:{include:{triggers:!0}}}});for(let s of t)try{let t=o6(oV(s.payloadJson),"Trigger payload");for(let o of r)if(o.activeVersion)for(let r of o.activeVersion.triggers.filter(({kind:e})=>e===s.kind)){var i,a,n;if(t.workflowCorrelation&&"object"==typeof t.workflowCorrelation&&t.workflowCorrelation.workflowId===o.id)continue;let l=(i=s.dedupeKey,a=o.id,n=r.nodeId,(0,b.createHash)("sha256").update(JSON.stringify([i,a,n])).digest("hex"));if(await e.workflowTriggerDelivery.findUnique({where:{id:l},select:{id:!0}})||!await this.triggerMatches(r,s.subjectKey,t))continue;let c=await this.createRunForTrigger({...o,activeVersion:o.activeVersion},o.activeVersion,r,s.id,s.kind,s.subjectKey,t,l,null,l);o5(c.id)}await e.workflowTriggerEvent.update({where:{id:s.id},data:{status:"PROCESSED",processedAt:new Date,error:null}})}catch(t){await e.workflowTriggerEvent.update({where:{id:s.id},data:{status:"FAILED",processedAt:new Date,error:t instanceof Error?t.message:String(t)}})}}async triggerMatches(e,t,r){let i,a=(0,st.resolveWorkflowValue)(o6(oV(e.configJson),"Trigger configuration"),r),n=null;if(void 0!==r.cursorValue&&("string"!=typeof a.thresholdPath||"string"!=typeof a.thresholdOperator)){let a=await (0,t1.getPrismaClient)(),s=await a.workflowTriggerState.findUnique({where:{triggerId_subjectKey:{triggerId:e.id,subjectKey:t}}});if(n=o3(i=s?.cursorJson?o6(oV(s.cursorJson),"Trigger cursor").value:void 0)!==o3(r.cursorValue),"WORKTREE_CLEAN"===e.kind&&(n=!0===i&&!1===r.cursorValue),"JIRA_SPRINT_STARTED"===e.kind||"JIRA_SPRINT_ENDED"===e.kind){let e=Array.isArray(i)?i:null,t=Array.isArray(r.cursorValue)?r.cursorValue:null;n=null!==e&&null!==t&&t.some(t=>!e.some(e=>o3(e)===o3(t)))}await a.workflowTriggerState.upsert({where:{triggerId_subjectKey:{triggerId:e.id,subjectKey:t}},create:{id:(0,b.randomUUID)(),triggerId:e.id,subjectKey:t,cursorJson:JSON.stringify({value:r.cursorValue}),lastMatched:n,...n?{lastFiredAt:new Date}:{}},update:{cursorJson:JSON.stringify({value:r.cursorValue}),lastMatched:n,...n?{lastFiredAt:new Date}:{}}})}if("GITHUB_ISSUE_COMMAND"===e.kind){let e=(0,st.getSessionValue)(r,"comment.author.login"),t=(0,st.getSessionValue)(r,"comment.body"),i=Array.isArray(a.allowedLogins)?a.allowedLogins:[];if("string"!=typeof e||!i.includes(e)||"string"!=typeof t||"string"!=typeof a.commandPattern||!(0,sZ.compileRe2)(a.commandPattern,{label:"GitHub issue command pattern"}).test(t))return!1}if("GITLAB_NOTE_COMMAND"===e.kind){let e=(0,st.getSessionValue)(r,"comment.author.username"),t=(0,st.getSessionValue)(r,"comment.body"),i=Array.isArray(a.allowedUsernames)?a.allowedUsernames:[];if("string"!=typeof e||!i.includes(e)||"string"!=typeof t||"string"!=typeof a.commandPattern||!(0,sZ.compileRe2)(a.commandPattern,{label:"GitLab note command pattern"}).test(t))return!1}if("JIRA_ISSUE_COMMAND"===e.kind){let e=(0,st.getSessionValue)(r,"comment.author.accountId"),t=(0,st.getSessionValue)(r,"comment.body"),i=Array.isArray(a.allowedAccountIds)?a.allowedAccountIds:[];if("string"!=typeof e||!i.includes(e)||"string"!=typeof t||"string"!=typeof a.commandPattern||!(0,sZ.compileRe2)(a.commandPattern,{label:"Jira issue command pattern"}).test(t))return!1}if("COMMAND_OUTPUT_MATCH"===e.kind){let e=(0,st.getSessionValue)(r,"output.data");if("string"!=typeof e||"string"!=typeof a.outputPattern||!(0,sZ.compileRe2)(a.outputPattern,{label:"Command output trigger pattern"}).test(e))return!1}if("WORKTREE_CONFLICT"===e.kind&&!0!==(0,st.getSessionValue)(r,"worktree.conflicted")||"WORKTREE_MISSING"===e.kind&&null==(0,st.getSessionValue)(r,"worktree.missingAt")||"WORKTREE_DIVERGED"===e.kind&&"DIVERGED"!==(0,st.getSessionValue)(r,"worktree.pushStatus"))return!1;if(a.filters&&"object"==typeof a.filters)for(let[e,t]of Object.entries(a.filters)){let i=(0,st.getSessionValue)(r,e);if(Array.isArray(t)){if(!t.some(e=>o3(e)===o3(i)))return!1}else if(o3(t)!==o3(i))return!1}if("string"==typeof a.thresholdPath&&"string"==typeof a.thresholdOperator){let i=oC({op:a.thresholdOperator,left:{source:"SESSION",path:a.thresholdPath},right:a.thresholdValue},r),n=await (0,t1.getPrismaClient)(),s=await n.workflowTriggerState.findUnique({where:{triggerId_subjectKey:{triggerId:e.id,subjectKey:t}}});return await n.workflowTriggerState.upsert({where:{triggerId_subjectKey:{triggerId:e.id,subjectKey:t}},create:{id:(0,b.randomUUID)(),triggerId:e.id,subjectKey:t,lastMatched:i,cursorJson:JSON.stringify({value:(0,st.getSessionValue)(r,a.thresholdPath)}),...i?{lastFiredAt:new Date}:{}},update:{lastMatched:i,cursorJson:JSON.stringify({value:(0,st.getSessionValue)(r,a.thresholdPath)}),...i&&!s?.lastMatched?{lastFiredAt:new Date}:{}}}),i&&!s?.lastMatched}return n??!0}async processSchedules(){let e=await (0,t1.getPrismaClient)(),t=await e.workflow.findMany({where:{enabled:!0,archivedAt:null,activeVersionId:{not:null}},include:{activeVersion:{include:{triggers:{where:{kind:"SCHEDULE"},include:{states:!0}}}}}}),r=new Date;for(let i of t)for(let t of i.activeVersion?.triggers??[]){let a=o6(oV(t.configJson),"Schedule configuration"),n=Number(a.cadenceSeconds);if(!Number.isInteger(n)||n<1)continue;let s=i.id,o=t.states.find(e=>e.subjectKey===s);if(!o){let i="string"==typeof a.firstRunAt?new Date(a.firstRunAt):null,l=i&&Number.isFinite(i.getTime())?i:new Date(r.getTime()+1e3*n);o=await e.workflowTriggerState.create({data:{id:(0,b.randomUUID)(),triggerId:t.id,subjectKey:s,nextScheduledAt:l}})}if(!o.nextScheduledAt||o.nextScheduledAt>r)continue;let l=o.nextScheduledAt,c=new Date(Math.max(r.getTime(),l.getTime())+1e3*n);await e.workflowTriggerState.update({where:{id:o.id},data:{lastFiredAt:r,nextScheduledAt:c}}),await this.events.record({kind:"SCHEDULE",subjectKey:s,dedupeKey:`schedule:${t.id}:${l.toISOString()}`,payload:{sessionData:{},scheduledFor:l.toISOString(),cadenceSeconds:n}})}}async lifecycle(e,t){let r=await (0,t1.getPrismaClient)(),i=await r.workflowRun.findUnique({where:{id:e}});if(!i)throw Error("Workflow run not found");if("PAUSE"===t){if(!new Set(["RUNNING","WAITING","BLOCKED"]).has(i.status))throw Error("Only an active workflow run can be paused");if(!await r.$transaction(async t=>!!(await t.workflowRun.updateMany({where:{id:e,status:{in:["RUNNING","WAITING","BLOCKED"]}},data:{status:"PAUSING",phase:"DRAINING"}})).count&&(await t.workflowStepAttempt.updateMany({where:{runId:e,status:"READY"},data:{status:"PENDING",phase:"PAUSED_PENDING"}}),!0)))return this.run(e);await this.controlLinkedAgentRuns(e,"PAUSE"),await this.appendEvent(e,null,"RUN_PAUSING","Workflow pause requested")}else if("RESUME"===t){if("PAUSED"!==i.status)throw Error("Only a paused workflow run can be resumed");if(!(await r.workflowRun.updateMany({where:{id:e,status:"PAUSED"},data:{status:"RUNNING",phase:"SCHEDULING",pausedAt:null}})).count)return this.run(e);await this.controlLinkedAgentRuns(e,"CONTINUE"),await this.appendEvent(e,null,"RUN_RESUMED","Workflow resumed")}else{if(oq.has(i.status))return this.run(e);for(let[t,i]of(await this.controlLinkedAgentRuns(e,"CANCEL"),await this.cancelWaitingCommandRuns(e),this.activeExecutions)){let a=await r.workflowStepAttempt.findUnique({where:{id:t},select:{runId:!0}});a?.runId===e&&i.abort()}if(!await r.$transaction(async t=>!!(await t.workflowRun.updateMany({where:{id:e,status:{notIn:[...oq]}},data:{status:"CANCELLED",phase:"CANCELLED",finishedAt:new Date}})).count&&(await t.workflowStepAttempt.updateMany({where:{runId:e,status:{notIn:[...o$]}},data:{status:"CANCELLED",phase:"CANCELLED",finishedAt:new Date,claimOwner:null,claimExpiresAt:null}}),await t.workflowWait.updateMany({where:{runId:e,status:"PENDING"},data:{status:"CANCELLED",resolvedAt:new Date}}),await t.workflowResourceLease.deleteMany({where:{runId:e}}),await t.worktreeWorkflowLease.deleteMany({where:{workflowRunId:e}}),!0)))return this.run(e);await this.appendEvent(e,null,"RUN_CANCELLED","Workflow cancelled"),await this.promoteWorktreeAdmissions(i.worktreeId)}return o5(e),this.run(e)}async repairRunData(e,t){let r=o6(t,"Session data patch"),i=await (0,t1.getPrismaClient)(),a=await i.workflowRun.findUnique({where:{id:e}});if(!a)throw Error("Workflow run not found");if(!new Set(["BLOCKED","PAUSED"]).has(a.status))throw Error("Only blocked or paused workflows accept repair data");let n=(0,st.workflowSessionData)(a.sessionDataJson),s=(0,st.getSessionValue)(n,"workflow"),o=(0,st.mergeSessionData)(n,r);s&&"object"==typeof s&&(o=(0,st.setSessionValue)(o,"workflow",s)),oH(a,o);let l=JSON.stringify(o);return o4(l,"Workflow session data",2097152),await i.$transaction([i.workflowRun.update({where:{id:e},data:{sessionDataJson:l,sessionRevision:{increment:1},status:"PAUSED"===a.status?"PAUSED":"RUNNING",phase:"PAUSED"===a.status?"PAUSED":"SCHEDULING",blockedReason:null}}),i.workflowStepAttempt.updateMany({where:{runId:e,status:"BLOCKED"},data:{status:"PENDING",phase:"PENDING",error:null}})]),await this.appendEvent(e,null,"RUN_DATA_REPAIRED","Workflow session data repaired"),o5(e),this.run(e)}async answerQuestion(e,t){let r=await (0,t1.getPrismaClient)(),i=await r.$transaction(async r=>{let i=await r.runQuestionBatch.findUnique({where:{id:e},include:{workflowStepAttempt:!0,answerRevisions:!0}}),a=i?.workflowStepAttempt;if(!i||!a)throw Error("Workflow question not found");if("PENDING"!==i.status)throw Error("Question was already answered");return await r.runAnswerRevision.create({data:{id:(0,b.randomUUID)(),batchId:e,revision:i.answerRevisions.length,answersJson:JSON.stringify(t)}}),await r.runQuestionBatch.update({where:{id:e},data:{status:"ANSWERED",answeredAt:new Date}}),await r.workflowWait.updateMany({where:{attemptId:a.id,status:"PENDING",kind:"HUMAN"},data:{status:"RESOLVED",resultJson:JSON.stringify({answers:t}),resolvedAt:new Date}}),a});return await this.completeWaitingAttempt(i.id,{answers:t},"HUMAN"),ie.agentEventBus.publish(oj(i.runId),{workflowQuestionChanged:{id:e,runId:i.runId}}),this.run(i.runId)}async consumeCommandOutputMatches(){if(this.commandOutputStream||!this.commandsService)return;let e=ie.agentEventBus.iterate(ie.COMMAND_RUN_OUTPUT_CHANGED_TOPIC);this.commandOutputStream=e;try{for await(let t of e){if(this.commandOutputStream!==e)break;await this.reconcileCommandOutputMatches(t.commandRunOutputAdded.runId).catch(e=>console.error("Could not process workflow command output:",e))}}finally{this.commandOutputStream===e&&(this.commandOutputStream=void 0),await e.return?.()}}async commandOutputRows(e,t,r){if(!this.commandsService)return[];let i=[],a=t,n=r;for(;;){let t=await this.commandsService.listOutput(e,a,n,5e3);if(i.push(...t),t.length<5e3)return i;let r=t.at(-1);a=r.attempt.attempt,n=r.sequence}}commandMatchBranchNodes(e,t){let r=new Map;for(let t of e.edges)r.set(t.source,[...r.get(t.source)??[],t]);let i=(r.get(t)??[]).filter(({sourceHandle:e})=>"match"===e).map(({target:e})=>e),a=new Set;for(;i.length;){let e=i.shift();a.has(e)||(a.add(e),i.push(...(r.get(e)??[]).map(({target:e})=>e)))}return e.nodes.filter(({id:e})=>a.has(e))}async persistCommandMatches(e,t,r){var i;let a=await (0,t1.getPrismaClient)(),n=(i=e.predicateJson,JSON.stringify({...i?oK(oV(i)):{},outputMatch:t}));if(!r.length)return!!(await a.workflowWait.updateMany({where:{id:e.id,status:"PENDING",predicateJson:e.predicateJson},data:{predicateJson:n}})).count;let s=(0,iC.parseWorkflowDefinition)(oV(e.attempt.run.version.definitionJson)),o=s.nodes.find(({id:t})=>t===e.attempt.nodeId);if(!o)throw Error("Workflow command step is missing");let l=this.commandMatchBranchNodes(s,o.id);if(!await a.$transaction(async t=>{if(!(await t.workflowWait.updateMany({where:{id:e.id,status:"PENDING",predicateJson:e.predicateJson},data:{predicateJson:n}})).count)return!1;let i=await t.workflowRun.findUnique({where:{id:e.runId}});if(!i||!oF.has(i.status))return!1;let a=(0,st.workflowSessionData)(i.sessionDataJson??"{}"),s=`steps.${o.id}`,c=oK((0,st.getSessionValue)(a,s)),u=Array.isArray(c.matches)?c.matches:[],d=[...u,...r];oH(i,a=(0,st.setSessionValue)(a,s,{...c,matches:d,latestMatch:r.at(-1)}));let p=JSON.stringify(a);o4(p,"Workflow session data",2097152);let h=l.length?r.flatMap((t,i)=>{let a=`match.${e.attempt.id}.${t.ordinal}`,n=(0,st.setSessionValue)({},s,{...c,matches:[...u,...r.slice(0,i+1)],latestMatch:t}),d={runId:e.runId,generation:e.attempt.generation,iterationKey:a,attempt:0};return[{id:(0,b.randomUUID)(),...d,nodeId:o.id,kind:o.kind,status:"SUCCEEDED",phase:"MATCH_EMITTED",inputJson:JSON.stringify(n),outputJson:JSON.stringify({value:t,selectedHandles:["match"],sessionPatch:n}),requiredPathsJson:JSON.stringify(o9(o)),providedPathsJson:JSON.stringify(o7(o)),idempotencyKey:`${e.runId}:${o.id}:${e.attempt.generation}:${a}:0`,startedAt:new Date,finishedAt:new Date},...l.map(t=>({id:(0,b.randomUUID)(),...d,nodeId:t.id,kind:t.kind,status:"PENDING",phase:"MATCH_PENDING",inputJson:JSON.stringify(n),requiredPathsJson:JSON.stringify(o9(t)),providedPathsJson:JSON.stringify(o7(t)),idempotencyKey:`${e.runId}:${t.id}:${e.attempt.generation}:${a}:0`}))]}):[];return h.length&&await t.workflowStepAttempt.createMany({data:h}),await t.workflowRun.update({where:{id:e.runId},data:{sessionDataJson:p,sessionRevision:{increment:1}}}),!0}))return!1;for(let t of r)await this.appendEvent(e.runId,e.attemptId,"STEP_OUTPUT_MATCHED",`Step ${o.name??o.id} matched command output`,{nodeId:o.id,match:t});return o5(e.runId),await this.progressRun(e.runId),await this.dispatchReadyAttempts(),!0}async failCommandMatchWait(e,t){let r=await (0,t1.getPrismaClient)();if(!(await r.workflowWait.updateMany({where:{id:e.id,status:"PENDING",predicateJson:e.predicateJson},data:{status:"FAILED",resolvedAt:new Date}})).count)return;await this.commandsService?.terminateRun(e.externalKey);let i=(0,iC.parseWorkflowDefinition)(oV(e.attempt.run.version.definitionJson)).nodes.find(({id:t})=>t===e.attempt.nodeId);await this.failAttempt(e.attempt,i??null,t)}async processCommandMatchWait(e){if(!e.externalKey||!this.commandsService)return;let t=function(e){if(!e)return null;let t=oK(oV(e)),r=oK(t.outputMatch);return"string"==typeof r.pattern&&r.pattern?{pattern:r.pattern,mode:(0,sY.commandOutputMatchMode)({outputMatchMode:r.mode}),matchCount:Number.isInteger(r.matchCount)?Number(r.matchCount):0,matched:!0===r.matched,scanAttempt:Number.isInteger(r.scanAttempt)&&Number(r.scanAttempt)>0?Number(r.scanAttempt):1,scanCharacterOffset:Number.isInteger(r.scanCharacterOffset)&&Number(r.scanCharacterOffset)>=0?Number(r.scanCharacterOffset):0,observedAttempt:Number.isInteger(r.observedAttempt)&&Number(r.observedAttempt)>=0?Number(r.observedAttempt):0,observedSequence:Number.isInteger(r.observedSequence)?Number(r.observedSequence):-1}:null}(e.predicateJson);if(t)try{let r=await this.commandOutputRows(e.externalKey,t.observedAttempt,t.observedSequence);if(!r.length)return;let i=r.at(-1);if(t.observedAttempt=i.attempt.attempt,t.observedSequence=i.sequence,"ONCE"===t.mode&&t.matched)return void await this.persistCommandMatches(e,t,[]);let a=await this.commandOutputRows(e.externalKey,t.scanAttempt-1,-1),n=new Map;for(let e of a){let r=e.attempt.attempt;r<t.scanAttempt||n.set(r,[...n.get(r)??[],e])}let s=[...n.keys()].sort((e,t)=>e-t),o=[],l=sX(t.pattern,!0);for(let r=0;r<s.length;r+=1){let i,a=s[r],c=n.get(a),u="",d=new Map,p=[];for(let e of c){if("STDOUT"!==e.stream&&"STDERR"!==e.stream)continue;let t=d.get(e.stream)??new TextDecoder("utf-8",{fatal:!1});d.set(e.stream,t);let r=t.decode(Buffer.from(e.dataBase64,"base64"),{stream:!0}),i=u.length;u+=r,p.push({sequence:e.sequence,start:i,end:u.length})}let h=a===t.scanAttempt?Math.min(t.scanCharacterOffset,u.length):0,m=u.slice(h);if(Buffer.byteLength(m,"utf8")>sY.COMMAND_OUTPUT_MATCH_BUFFER_BYTES)throw Error("Command output matcher exceeded its 16 MiB unmatched-output limit");for(l.lastIndex=h;i=l.exec(u);){let r=i[0];if(!r.length)throw Error("Command output patterns must consume at least one character");let n=i.index,s=n+r.length,l=(e,t)=>{let r=p.find(({start:r,end:i})=>t?e>r&&e<=i:e>=r&&e<i)??p.at(-1);return{sequence:r.sequence,offset:Math.max(0,e-r.start)}};t.matchCount+=1;let c={ordinal:t.matchCount,text:r,captures:i.slice(1).map(e=>e??null),namedCaptures:Object.fromEntries(Object.entries(i.groups??{}).map(([e,t])=>[e,t??null])),commandRunId:e.externalKey,commandAttempt:a,start:l(n,!1),end:l(s,!0)};if(o.push(c),t.scanAttempt=a,t.scanCharacterOffset=s,"ONCE"===t.mode){t.matched=!0;break}}if(t.matched)break;let f=s[r+1];void 0!==f?(t.scanAttempt=f,t.scanCharacterOffset=0):a>t.scanAttempt&&(t.scanAttempt=a,t.scanCharacterOffset=0)}await this.persistCommandMatches(e,t,o)}catch(t){await this.failCommandMatchWait(e,t instanceof Error?t:Error(String(t)))}}async reconcileCommandOutputMatches(e){if(!this.commandsService)return;let t=await (0,t1.getPrismaClient)();for(let r of(await t.workflowWait.findMany({where:{kind:"COMMAND_RUN",status:"PENDING",predicateJson:{not:null},...e?{externalKey:e}:{},run:{status:{in:[...oF]}}},include:{attempt:{include:{run:{include:{version:!0}}}}},orderBy:{createdAt:"asc"},take:100})))await this.processCommandMatchWait(r)}async tick(){if(!this.ticking){this.ticking=!0;try{await this.recoverExpiredClaims(),await this.processSchedules(),await this.processTriggerEvents(),await this.events.maintain(),await this.reconcileCommandOutputMatches(),await this.resolveDueWaits(),await this.startQueuedRuns();let e=await (0,t1.getPrismaClient)();for(let{id:t}of(await e.workflowRun.findMany({where:{status:{in:["RUNNING","WAITING","PAUSING"]}},select:{id:!0},orderBy:{updatedAt:"asc"},take:100})))await this.progressRun(t);await this.dispatchReadyAttempts()}finally{this.ticking=!1}}}async recoverExpiredClaims(){let e=await (0,t1.getPrismaClient)();for(let t of(await e.workflowStepAttempt.findMany({where:{status:"RUNNING",claimExpiresAt:{lt:new Date}},include:{run:!0},take:100})))await e.$transaction([e.workflowStepAttempt.update({where:{id:t.id},data:{status:"BLOCKED",phase:"RECOVERY_BLOCKED",error:"The workflow worker stopped while this step was running; verify external state before retrying.",claimOwner:null,claimExpiresAt:null}}),e.workflowRun.update({where:{id:t.runId},data:{status:"BLOCKED",phase:"RECOVERY_BLOCKED",blockedReason:`Step ${t.nodeId} needs recovery review`}}),e.workflowResourceLease.deleteMany({where:{attemptId:t.id}})]),await this.appendEvent(t.runId,t.id,"STEP_RECOVERY_BLOCKED","Step needs recovery review after its worker lease expired"),await this.notifyRun(t.runId,"WORKFLOW_RECOVERY_PAUSED","Workflow paused during recovery","An interrupted step requires external-state verification before replay.",`recovery:${t.id}`),o5(t.runId)}async startQueuedRuns(){let e=await (0,t1.getPrismaClient)();for(let t of(await e.workflowRun.findMany({where:{status:"QUEUED"},include:{workflow:!0,version:!0},orderBy:[{queuedAt:"asc"},{id:"asc"}],take:200}))){let r=(0,iC.parseWorkflowDefinition)(oV(t.version.definitionJson)),i=new Date,a=(0,st.setSessionValue)((0,st.workflowSessionData)(t.sessionDataJson),"workflow.startedAt",i.toISOString());await e.$transaction(async e=>{let n="CONCURRENT"===t.workflow.overlapPolicy?t.workflow.maxConcurrentRuns:1;if(await e.workflowRun.count({where:{workflowId:t.workflowId,id:{not:t.id},...o1(t.workflow.overlapScope,t.worktreeId),status:{in:oM.filter(e=>"QUEUED"!==e)}}})>=n)return!1;if(t.worktreeId&&"EXCLUDED"!==t.worktreeConcurrency){await e.worktreeAdmissionLane.upsert({where:{worktreeId:t.worktreeId},create:{worktreeId:t.worktreeId},update:{updatedAt:i}}),await e.worktreeWorkflowLease.deleteMany({where:{worktreeId:t.worktreeId,workflowRun:{status:{in:[...oq]}}}}),await e.worktreeRunLease.deleteMany({where:{worktreeId:t.worktreeId,purpose:{not:"ANSWER_REVISION"},run:{status:{in:["COMPLETED","FAILED","CANCELLED"]}}}});let r=await e.worktreeWorkflowLease.findUnique({where:{worktreeId:t.worktreeId}});if(r&&t.worktreeLeaseOwnerRunId!==r.workflowRunId)return await e.workflowRun.updateMany({where:{id:t.id,status:"QUEUED"},data:{phase:"WAITING_FOR_WORKTREE"}}),!1;if(!r){let r=await e.workflowRun.findFirst({where:{worktreeId:t.worktreeId,status:"QUEUED",parentRunId:null,worktreeConcurrency:"EXCLUSIVE"},orderBy:[{queuedAt:"asc"},{id:"asc"}],select:{id:!0,queuedAt:!0}});if(r&&r.id!==t.id&&function(e,t,r,i){let a=e.getTime()-r.getTime();return a<0||0===a&&t<i}(r.queuedAt,r.id,t.queuedAt,t.id))return await e.workflowRun.updateMany({where:{id:t.id,status:"QUEUED"},data:{phase:"WAITING_FOR_WORKTREE"}}),!1;if(t.worktreeLeaseOwnerRunId===t.id){let[r,i,a,n]=await Promise.all([e.worktreeRunLease.count({where:{worktreeId:t.worktreeId}}),e.workflowRun.count({where:{worktreeId:t.worktreeId,id:{not:t.id},worktreeConcurrency:{not:"EXCLUDED"},status:{in:oM.filter(e=>"QUEUED"!==e)}}}),e.agentRun.findFirst({where:{worktreeId:t.worktreeId,origin:"MANAGED",status:"QUEUED",OR:[{createdAt:{lt:t.queuedAt}},{createdAt:t.queuedAt,id:{lt:t.id}}]},select:{id:!0}}),e.workflowRun.findFirst({where:{worktreeId:t.worktreeId,status:"QUEUED",id:{not:t.id},worktreeConcurrency:{not:"EXCLUDED"},OR:[{queuedAt:{lt:t.queuedAt}},{queuedAt:t.queuedAt,id:{lt:t.id}}]},select:{id:!0}})]);if(r||i||a||n)return await e.workflowRun.updateMany({where:{id:t.id,status:"QUEUED"},data:{phase:"WAITING_FOR_WORKTREE"}}),!1;await e.worktreeWorkflowLease.create({data:{worktreeId:t.worktreeId,workflowRunId:t.id}})}}}return!!(await e.workflowRun.updateMany({where:{id:t.id,status:"QUEUED"},data:{status:"RUNNING",phase:"SCHEDULING",startedAt:i,sessionDataJson:JSON.stringify(a),sessionRevision:{increment:1}}})).count&&(await e.workflowStepAttempt.count({where:{runId:t.id,generation:t.generation}})||await e.workflowStepAttempt.createMany({data:r.nodes.map(e=>({id:(0,b.randomUUID)(),runId:t.id,nodeId:e.id,kind:e.kind,generation:t.generation,iterationKey:"",attempt:0,requiredPathsJson:JSON.stringify(o9(e)),providedPathsJson:JSON.stringify(o7(e)),idempotencyKey:`${t.id}:${e.id}:${t.generation}::0`}))}),!0)})&&(t.startedAt||await this.appendEvent(t.id,null,"RUN_STARTED","Workflow started"),o5(t.id))}}selectedTrigger(e,t){let r=e.trigger?.nodeId??t.triggers.find(({kind:t})=>t===e.triggerKind)?.id??null;if(!(0,iR.isChoiceTriggerKind)(e.triggerKind))return{id:r,choice:null};let i=o6(oV(e.triggerPayloadJson),"Trigger payload");return{id:r,choice:"string"==typeof i.choice?i.choice:null}}attemptOutput(e){if(!e.outputJson)return{};let t=oV(e.outputJson);return t&&"object"==typeof t&&!Array.isArray(t)?t:{value:t}}edgeState(e,t,r,i){if(!i.has(e.source))return e.source!==t.id||t.choice&&e.sourceHandle!==t.choice?"INACTIVE":"ACTIVE";let a=r.get(e.source);if(!a||!o$.has(a.status))return"PENDING";if(new Set(["SKIPPED","CANCELLED","SUPERSEDED"]).has(a.status))return"INACTIVE";let n=i.get(e.source);if("FAILED"===a.status)return"failure"===e.sourceHandle||"catch"===e.sourceHandle||"CONTINUE"===n.failurePolicy&&"success"===e.sourceHandle?"ACTIVE":"INACTIVE";let s=this.attemptOutput(a).selectedHandles;return s?.length?s.includes(e.sourceHandle)?"ACTIVE":"INACTIVE":"success"===e.sourceHandle||"output"===e.sourceHandle?"ACTIVE":"INACTIVE"}async progressRun(e){let t=await (0,t1.getPrismaClient)(),r=await t.workflowRun.findUnique({where:{id:e},include:{version:!0,trigger:!0,attempts:!0,waits:!0}});if(!r||oq.has(r.status))return;if("PAUSING"===r.status){await t.workflowStepAttempt.updateMany({where:{runId:e,status:"READY"},data:{status:"PENDING",phase:"PAUSED_PENDING"}});let i=new Set(["AGENT_JOB","BUILD","SKILL_RUN","WORKTREE_MOVE","GITHUB_CHECKS"]),a=new Set(r.waits.filter(({status:e,kind:t})=>"PENDING"===e&&i.has(t)).map(({attemptId:e})=>e));!r.attempts.some(({id:e,status:t})=>"RUNNING"===t||"WAITING"===t&&a.has(e))&&(await t.workflowRun.updateMany({where:{id:e,status:"PAUSING"},data:{status:"PAUSED",phase:"PAUSED",pausedAt:new Date}})).count&&(await this.appendEvent(e,null,"RUN_PAUSED","Workflow paused"),o5(e));return}if(!new Set(["RUNNING","WAITING"]).has(r.status))return;let i=(0,iC.parseWorkflowDefinition)(oV(r.version.definitionJson)),a=new Map(i.nodes.map(e=>[e.id,e])),n=new Map;for(let e of i.edges)n.set(e.target,[...n.get(e.target)??[],e]);let s=!0;for(;s;){if(s=!1,!(r=await t.workflowRun.findUnique({where:{id:e},include:{version:!0,trigger:!0,attempts:!0,waits:!0}})))return;let o=r.attempts.filter(({generation:e,supersededAt:t})=>e===r.generation&&!t),l=new Map;for(let e of o){let t=`${e.nodeId}:${e.iterationKey}`,r=l.get(t);(!r||r.attempt<e.attempt)&&l.set(t,e)}let c=new Map([...l.values()].filter(({iterationKey:e})=>!e).map(e=>[e.nodeId,e])),u=this.selectedTrigger(r,i);for(let e of i.nodes){let r=c.get(e.id);if(!r||"PENDING"!==r.status)continue;let o=i.nodes.find(t=>"CONTROL_FOR_EACH"===t.kind&&t.config.joinNodeId===e.id);if(o){let e=c.get(o.id);if(!e||!o$.has(e.status)||[...l.values()].filter(({iterationKey:e})=>!!e).some(({status:e})=>!o$.has(e)))continue;await t.workflowStepAttempt.update({where:{id:r.id},data:{status:"READY",phase:"ITERATIONS_JOINED"}}),s=!0;continue}let d=n.get(e.id)??[];if(!d.length)continue;let p=d.map(e=>this.edgeState(e,u,c,a)),h=p.filter(e=>"ACTIVE"===e).length,m=p.filter(e=>"PENDING"===e).length;("ANY"==("CONTROL_JOIN"===e.kind&&"ANY"===e.config.mode?"ANY":"ALL")?h>0:0===m&&h>0)?(await t.workflowStepAttempt.update({where:{id:r.id},data:{status:"READY",phase:"READY"}}),s=!0):0===m&&0===h&&(await t.workflowStepAttempt.update({where:{id:r.id},data:{status:"SKIPPED",phase:"INACTIVE_BRANCH",finishedAt:new Date}}),s=!0)}await this.progressIterationAttempts(i,r,u,a,n,l,c)&&(s=!0)}if(!(r=await t.workflowRun.findUnique({where:{id:e},include:{version:!0,trigger:!0,attempts:!0,waits:!0}})))return;let o=new Map;for(let e of r.attempts.filter(({generation:e,supersededAt:t})=>e===r.generation&&!t)){let t=`${e.nodeId}:${e.iterationKey}`,r=o.get(t);(!r||r.attempt<e.attempt)&&o.set(t,e)}let l=[...o.values()],c=r.waits.some(({status:e})=>"PENDING"===e),u=l.some(({status:e})=>!o$.has(e));if(c||u){let i=c?"WAITING":"RUNNING";r.status!==i&&(await t.workflowRun.updateMany({where:{id:e,status:{in:[...oF]}},data:{status:i,phase:c?"WAITING":"SCHEDULING"}})).count&&o5(e);return}let d=(0,iC.parseWorkflowDefinition)(oV(r.version.definitionJson)),p=l.find(e=>{if("FAILED"!==e.status)return!1;let t=d.nodes.find(({id:t})=>t===e.nodeId);return!!t&&"CONTINUE"!==t.failurePolicy&&!d.edges.some(e=>e.source===t.id&&new Set(["failure","catch"]).has(e.sourceHandle))});await this.finishRun(r,p?"FAILED":"SUCCEEDED",p?.error??null)}async finishRun(e,t,r){let i=await (0,t1.getPrismaClient)();await i.$transaction(async i=>!!(await i.workflowRun.updateMany({where:{id:e.id,status:{in:[...oF]}},data:{status:t,phase:t,error:r,finishedAt:new Date}})).count&&(await i.workflowResourceLease.deleteMany({where:{runId:e.id}}),await i.worktreeWorkflowLease.deleteMany({where:{workflowRunId:e.id}}),!0))&&(await this.appendEvent(e.id,null,`RUN_${t}`,"SUCCEEDED"===t?"Workflow completed":"Workflow failed",r?{error:r}:null),await this.resolveExternalWait("WORKFLOW_RUN",e.id,{status:t,runId:e.id},"FAILED"===t?r||"Sub-workflow failed":null),await this.events.record({kind:"WORKFLOW_FINISHED",subjectKey:e.workflowId,dedupeKey:`workflow-finished:${e.id}`,payload:{sessionData:(0,st.workflowSessionData)(e.sessionDataJson),run:{id:e.id,status:t},workflowCorrelation:{workflowId:e.workflowId,runId:e.id}}}),await this.notifyRun(e.id,"SUCCEEDED"===t?"WORKFLOW_COMPLETED":"WORKFLOW_FAILED","SUCCEEDED"===t?"Workflow completed":"Workflow failed",r||`Workflow run ${e.displayNumber} ${t.toLowerCase()}`,t.toLowerCase()),await this.promoteWorktreeAdmissions(e.worktreeId),o5(e.id))}async dispatchReadyAttempts(){let e=await (0,t1.getPrismaClient)(),t=Math.max(0,4-await e.workflowStepAttempt.count({where:{status:"RUNNING"}}));if(t)for(let r of(await e.workflowStepAttempt.findMany({where:{status:"READY",run:{status:{in:[...oF]}}},orderBy:{createdAt:"asc"},take:2*t}))){if(t<=0)break;if(!(await e.workflowStepAttempt.updateMany({where:{id:r.id,status:"READY",run:{status:{in:[...oF]}}},data:{status:"RUNNING",phase:"RUNNING",claimOwner:this.workerId,claimExpiresAt:new Date(Date.now()+3e5),startedAt:r.startedAt??new Date}})).count)continue;t-=1;let i=new AbortController;this.activeExecutions.set(r.id,i),this.executeAttempt(r.id,i.signal).catch(e=>{console.error(`Workflow attempt ${r.id} failed unexpectedly:`,e)}).finally(()=>{this.activeExecutions.delete(r.id)})}}async acquireResourceLease(e,t,r){let i=iC.WORKFLOW_STEP_BY_KIND.get(t.kind),a=null;if(i.mutatesWorktree){let e=(0,st.getSessionValue)(r,"worktree.id")??(0,st.getSessionValue)(r,"worktree.path")??(0,st.getSessionValue)(r,"codebase.id");e&&(a=`git:${String(e)}`)}else if(t.kind.startsWith("BUILD_")){let e=(0,st.getSessionValue)(r,"build.id");e&&(a=`build:${String(e)}`)}if(!a)return!0;let n=await (0,t1.getPrismaClient)();await n.workflowResourceLease.deleteMany({where:{key:a,expiresAt:{lt:new Date}}});try{return await n.workflowResourceLease.create({data:{key:a,runId:e.runId,attemptId:e.id,expiresAt:new Date(Date.now()+3e5)}}),await n.workflowStepAttempt.update({where:{id:e.id},data:{resourceLockKey:a}}),!0}catch{return await n.workflowStepAttempt.update({where:{id:e.id},data:{status:"READY",phase:"WAITING_FOR_RESOURCE",claimOwner:null,claimExpiresAt:null}}),!1}}async executeAttempt(e,t){let r=await (0,t1.getPrismaClient)(),i=await r.workflowStepAttempt.findUnique({where:{id:e},include:{run:{include:{version:!0}}}});if(!i||"RUNNING"!==i.status)return;let a=(0,iC.parseWorkflowDefinition)(oV(i.run.version.definitionJson)),n=a.nodes.find(({id:e})=>e===i.nodeId);if(!n)return void await this.failAttempt(i,null,Error("Workflow step definition is missing"));let s=(0,st.workflowSessionData)(i.run.sessionDataJson);i.iterationKey&&(s=await this.iterationSessionData(i.run,i,s));let o=o9(n).filter(e=>!(0,st.hasSessionValue)(s,e));if(o.length){await r.$transaction([r.workflowStepAttempt.update({where:{id:i.id},data:{status:"BLOCKED",phase:"MISSING_REQUIREMENTS",error:`Missing required session data: ${o.join(", ")}`,claimOwner:null,claimExpiresAt:null}}),r.workflowRun.update({where:{id:i.runId},data:{status:"BLOCKED",phase:"MISSING_REQUIREMENTS",blockedReason:`Step ${n.name??n.id} needs ${o.join(", ")}`}}),r.workflowResourceLease.deleteMany({where:{attemptId:e}})]),await this.appendEvent(i.runId,i.id,"STEP_BLOCKED",`Step blocked by missing requirements: ${o.join(", ")}`),await this.notifyRun(i.runId,"WORKFLOW_NEEDS_ATTENTION","Workflow needs data",`Step ${n.name??n.id} needs ${o.join(", ")}`,`blocked:${i.id}`),o5(i.runId);return}if(i.run.exclusiveWorktree&&oG.has(n.kind))return void await this.failAttempt(i,n,Error("Exclusive workflows cannot run steps that create, delete, or move their worktree"));if(await r.workflowStepAttempt.update({where:{id:i.id},data:{inputJson:JSON.stringify(s)}}),await this.acquireResourceLease(i,n,s))try{let e,r={...n,config:(0,st.resolveWorkflowValue)(n.config,s)};if(e=n.kind.startsWith("CONTROL_")||"HUMAN_CONFIRM"===n.kind||"HUMAN_CHOICE"===n.kind?await this.executeControl(i.run,i,r,s,a):await this.executor.execute({run:i.run,attempt:i,node:r,sessionData:s,signal:t}),t.aborted)throw Error("Workflow step was cancelled");e.wait?await this.parkAttempt(i,n,e):await this.completeAttempt(i,n,e)}catch(t){let e=t instanceof Error?t:Error(String(t));if(await this.holdForBusyCodebase(i,e))return;await this.failAttempt(i,n,e)}}async holdForBusyCodebase(e,t){if(!(0,nK.isCodebaseBusyError)(t))return!1;let r=e.startedAt??e.createdAt;if(Date.now()-r.getTime()>6e5)return!1;let i=await (0,t1.getPrismaClient)();return!!(await i.workflowStepAttempt.updateMany({where:{id:e.id,status:"RUNNING",claimOwner:this.workerId},data:{status:"READY",phase:"WAITING_FOR_RESOURCE",error:t.message,claimOwner:null,claimExpiresAt:null}})).count&&(await i.workflowResourceLease.deleteMany({where:{attemptId:e.id}}),await i.workflowRunEvent.findFirst({where:{attemptId:e.id,type:"STEP_WAITING_FOR_RESOURCE"},select:{id:!0}})||await this.appendEvent(e.runId,e.id,"STEP_WAITING_FOR_RESOURCE","Step is waiting for the codebase to become available",{error:t.message}),o5(e.runId),!0)}async iterationSessionData(e,t,r){let i=await (0,t1.getPrismaClient)(),a=await i.workflowStepAttempt.findMany({where:{runId:e.id,generation:t.generation,iterationKey:t.iterationKey,status:"SUCCEEDED"},orderBy:{finishedAt:"asc"}}),n=r;for(let e of(t.inputJson&&(n=(0,st.mergeSessionData)(n,o6(oV(t.inputJson),"Iteration input"))),a)){let t=this.attemptOutput(e);t.sessionPatch&&(n=(0,st.mergeSessionData)(n,t.sessionPatch))}return n}async executeControl(e,t,r,i,a){switch(r.kind){case"CONTROL_IF":{let e=r.config.condition;if(!e)throw Error("If steps require a condition");let t=oC(e,i);return{output:{matched:t},selectedHandles:[t?"true":"false"]}}case"CONTROL_JOIN":{let i=a.nodes.find(e=>"CONTROL_FOR_EACH"===e.kind&&e.config.joinNodeId===r.id);if(i){let r=await (0,t1.getPrismaClient)(),a=await r.workflowStepAttempt.findMany({where:{runId:e.id,generation:t.generation,iterationKey:{not:""},status:"FAILED"}});if(a.length&&"COLLECT_ERRORS"!==i.config.errorMode)throw Error(`${a.length} for-each iteration step(s) failed`);return{output:{iterations:await r.workflowStepAttempt.count({where:{runId:e.id,generation:t.generation,iterationKey:{not:""}}}),failures:a.map(({nodeId:e,iterationKey:t,error:r})=>({nodeId:e,iterationKey:t,error:r}))}}}return{output:{joined:!0}}}case"CONTROL_TRY":return{output:{started:!0}};case"CONTROL_DELAY":{let e=Number(r.config.seconds??0);if(!Number.isFinite(e)||e<0||e>31536e3)throw Error("Delay must be between zero and 31,536,000 seconds");return{wait:{kind:"DELAY",resumeAfter:new Date(Date.now()+1e3*e)}}}case"CONTROL_WAIT_UNTIL":{let e=r.config.condition;if(!e)throw Error("Wait-until steps require a condition");if(oC(e,i))return{output:{matched:!0}};let t=s2(r.config,15);return{wait:{kind:"PREDICATE",predicate:{condition:e,cadenceSeconds:t},resumeAfter:new Date(Date.now()+1e3*t),timeoutAt:s1(r.config)}}}case"CONTROL_SET_VARIABLE":{if("string"!=typeof r.config.path)throw Error("Set-variable steps require an output path");let e="string"==typeof r.config.script?await oO(r.config.script,i):r.config.value;return{output:e,sessionPatch:(0,st.setSessionValue)({},r.config.path,e)}}case"CONTROL_FOR_EACH":{let n=Array.isArray(r.config.items)?r.config.items:"string"==typeof r.config.listPath?(0,st.getSessionValue)(i,r.config.listPath):null;if(!Array.isArray(n))throw Error("For-each source must be an array");if(n.length>1e3)throw Error("For-each is limited to 1,000 items");return await this.spawnForEach(e,t,r,a,n),{output:{itemCount:n.length},selectedHandles:n.length?["body"]:["empty"],sessionPatch:(0,st.setSessionValue)({},`steps.${r.id}.items`,n)}}case"CONTROL_SUBWORKFLOW":return this.startSubworkflow(e,t,r,i);case"HUMAN_CONFIRM":case"HUMAN_CHOICE":return this.createHumanQuestion(e,t,r);default:throw Error(`Unsupported control step ${r.kind}`)}}async progressIterationAttempts(e,t,r,i,a,n,s){let o=await (0,t1.getPrismaClient)(),l=!1;for(let e of new Set([...n.values()].map(({iterationKey:e})=>e).filter(Boolean))){let t=new Map(s);for(let r of n.values())r.iterationKey===e&&t.set(r.nodeId,r);for(let n of t.values()){if(n.iterationKey!==e||"PENDING"!==n.status)continue;let s=i.get(n.nodeId);if(!s)continue;let c=(a.get(s.id)??[]).map(e=>this.edgeState(e,r,t,i)),u=c.filter(e=>"ACTIVE"===e).length,d=c.filter(e=>"PENDING"===e).length;("ANY"==("CONTROL_JOIN"===s.kind&&"ANY"===s.config.mode?"ANY":"ALL")?u>0:0===d&&u>0)?(await o.workflowStepAttempt.update({where:{id:n.id},data:{status:"READY",phase:"ITERATION_READY"}}),l=!0):0===d&&0===u&&(await o.workflowStepAttempt.update({where:{id:n.id},data:{status:"SKIPPED",phase:"INACTIVE_ITERATION_BRANCH",finishedAt:new Date}}),l=!0)}}return l}async spawnForEach(e,t,r,i,a){let n="string"==typeof r.config.joinNodeId?r.config.joinNodeId:null,s=i.nodes.find(({id:e})=>e===n);if(!s||"CONTROL_JOIN"!==s.kind)throw Error("For-each steps require an explicit joinNodeId");let o=new Map;for(let e of i.edges)o.set(e.source,[...o.get(e.source)??[],e]);let l=(o.get(r.id)??[]).filter(({sourceHandle:e})=>"body"===e).map(({target:e})=>e),c=new Set;for(;l.length;){let e=l.shift();e===n||c.has(e)||(c.add(e),l.push(...(o.get(e)??[]).map(({target:e})=>e)))}if(a.length&&!c.size)throw Error("For-each body is not connected to its body handle");let u=i.nodes.filter(({id:e})=>c.has(e)),d=await (0,t1.getPrismaClient)();await d.$transaction(async i=>{await i.workflowStepAttempt.updateMany({where:{runId:e.id,generation:t.generation,iterationKey:t.iterationKey,nodeId:{in:[...c]},status:"PENDING"},data:{status:"SKIPPED",phase:"ITERATION_TEMPLATE",finishedAt:new Date}}),a.length&&u.length&&await i.workflowStepAttempt.createMany({data:a.flatMap((i,a)=>{let n=t.iterationKey?`${t.iterationKey}.${a}`:String(a),s=JSON.stringify({loop:{current:{forEachNodeId:r.id,index:a,item:i},[r.id]:{index:a,item:i}}});return u.map(r=>({id:(0,b.randomUUID)(),runId:e.id,nodeId:r.id,kind:r.kind,generation:t.generation,iterationKey:n,attempt:0,status:"PENDING",phase:"ITERATION_PENDING",inputJson:s,requiredPathsJson:JSON.stringify(o9(r)),providedPathsJson:JSON.stringify(o7(r)),idempotencyKey:`${e.id}:${r.id}:${t.generation}:${n}:0`}))})})})}async startSubworkflow(e,t,r,i){let a="string"==typeof r.config.versionId?r.config.versionId:null;if(!a)throw Error("Sub-workflow version is required");let n=await (0,t1.getPrismaClient)(),s=await n.workflowVersion.findUnique({where:{id:a},include:{workflow:{include:{activeVersion:!0}}}});if(!s)throw Error("Sub-workflow version not found");if(!s.workflow.enabled||s.workflow.archivedAt)throw Error("Sub-workflow is paused");let o=e,l=0;for(;o;){if(o.workflowId===s.workflowId)throw Error("Recursive sub-workflow invocation is not allowed");if((l+=1)>=10)throw Error("Sub-workflow depth is limited to 10");o=o.parentRunId?await n.workflowRun.findUnique({where:{id:o.parentRunId}}):null}let c={};if(r.config.inputMapping&&"object"==typeof r.config.inputMapping)for(let[e,t]of Object.entries(r.config.inputMapping))c=(0,st.setSessionValue)(c,e,(0,st.resolveWorkflowValue)(t,i));let u=await this.createRunForTrigger({...s.workflow,activeVersion:s},s,null,null,"SUBWORKFLOW",e.id,{sessionData:c,parentRunId:e.id},`${t.id}:subworkflow:${s.id}`,e.id);return o5(u.id),{output:{childRunId:u.id},links:[{kind:"WORKFLOW_RUN",resourceId:u.id,label:`Workflow run #${u.displayNumber}`,url:`/workflows/runs/${u.id}`}],wait:{kind:"WORKFLOW_RUN",externalKey:u.id,resumeAfter:s3(r.config),timeoutAt:s1(r.config)}}}async createHumanQuestion(e,t,r){let i=Array.isArray(r.config.questions)?r.config.questions:[{header:r.name??null,prompt:"string"==typeof r.config.prompt?r.config.prompt:"HUMAN_CONFIRM"===r.kind?"Continue this workflow?":"Choose an option",multiSelect:!!r.config.multiSelect,allowCustom:"HUMAN_CONFIRM"!==r.kind&&!1!==r.config.allowCustom,options:"HUMAN_CONFIRM"===r.kind?[{label:"Confirm",description:null},{label:"Cancel",description:null}]:Array.isArray(r.config.options)?r.config.options:[]}];if(!i.length||i.length>10)throw Error("Workflow questions must contain between one and ten questions");let a=await (0,t1.getPrismaClient)(),n=(0,b.randomUUID)();return await a.runQuestionBatch.create({data:{id:n,workflowStepAttemptId:t.id,nativeRequestId:`workflow:${t.id}`,questions:{create:i.map((e,t)=>{let r=o6(e,"Workflow question"),i=Array.isArray(r.options)?r.options:[];return{id:(0,b.randomUUID)(),position:t,header:"string"==typeof r.header?r.header:null,prompt:oz(String(r.prompt??""),"Question prompt",1e4),multiSelect:!!r.multiSelect,allowCustom:!1!==r.allowCustom,options:{create:i.map((e,t)=>{let r=o6(e,"Question option");return{id:(0,b.randomUUID)(),position:t,label:oz(String(r.label??""),"Option label",500),description:"string"==typeof r.description?r.description.slice(0,2e3):null}})}}})}}}),ie.agentEventBus.publish(oj(e.id),{workflowQuestionChanged:{id:n,runId:e.id}}),{output:{questionBatchId:n},wait:{kind:"HUMAN",externalKey:n,timeoutAt:s1(r.config)}}}async parkAttempt(e,t,r){let i=r.wait;if(!i)throw Error("Workflow wait is missing");let a=await (0,t1.getPrismaClient)(),n=(0,b.randomUUID)();if(await a.$transaction(async a=>{let s=await a.workflowRun.findUnique({where:{id:e.runId}});if(!s||oq.has(s.status))return!1;let o=(0,st.workflowSessionData)(s.sessionDataJson??"{}"),l=!e.iterationKey&&("SAVED_COMMAND"===t.kind||"CUSTOM_COMMAND"===t.kind);l&&r.sessionPatch&&(o=(0,st.mergeSessionData)(o,r.sessionPatch)),oH(s,o);let c=JSON.stringify(o);return o4(c,"Workflow session data",2097152),!!(await a.workflowStepAttempt.updateMany({where:{id:e.id,status:"RUNNING"},data:{status:"WAITING",phase:i.kind,outputJson:JSON.stringify({value:r.output,selectedHandles:r.selectedHandles,sessionPatch:l?void 0:r.sessionPatch}),claimOwner:null,claimExpiresAt:null}})).count&&(await a.workflowWait.create({data:{id:n,runId:e.runId,attemptId:e.id,kind:i.kind,predicateJson:i.predicate?JSON.stringify(i.predicate):null,externalKey:i.externalKey??null,resumeAfter:i.resumeAfter??null,timeoutAt:i.timeoutAt??null}}),r.links?.length&&await a.workflowRunResourceLink.createMany({data:r.links.map(t=>({id:(0,b.randomUUID)(),runId:e.runId,attemptId:e.id,kind:t.kind.toUpperCase(),resourceId:t.resourceId,label:t.label??null,url:t.url??null,metadataJson:t.metadata?JSON.stringify(t.metadata):null}))}),await a.workflowRun.updateMany({where:{id:e.runId,status:{in:[...oF]}},data:{status:"WAITING",phase:i.kind,sessionDataJson:c,sessionRevision:{increment:1}}}),await a.workflowResourceLease.deleteMany({where:{attemptId:e.id}}),!0)})){let r,a;await this.appendEvent(e.runId,e.id,"STEP_WAITING",(r=t.name??t.id,a=s4(i.kind),"DELAY"===i.kind&&i.resumeAfter?`Step ${r} is waiting for ${a} until ${i.resumeAfter.toISOString()}`:`Step ${r} is waiting for ${a}`),{waitId:n,kind:i.kind,nodeId:t.id,externalKey:i.externalKey??null,resumeAfter:i.resumeAfter?.toISOString()??null,timeoutAt:i.timeoutAt?.toISOString()??null}),o5(e.runId)}}async completeAttempt(e,t,r,i){let a=await (0,t1.getPrismaClient)();if(await a.$transaction(async i=>{let a=await i.workflowRun.findUnique({where:{id:e.runId}});if(!a)throw Error("Workflow run disappeared");if(oq.has(a.status))return!1;let n=(0,st.workflowSessionData)(a.sessionDataJson);if(e.iterationKey)n=(0,st.setSessionValue)(n,`steps.${t.id}.iterations.${e.iterationKey.replaceAll(".","_")}`,{status:"SUCCEEDED",output:r.output??null,data:r.sessionPatch??null});else{r.sessionPatch&&(n=(0,st.mergeSessionData)(n,r.sessionPatch));let e=`steps.${t.id}`,i=oK((0,st.getSessionValue)(n,e));n=(0,st.setSessionValue)(n,e,{...i,status:"SUCCEEDED",output:r.output??null,snapshotId:r.links?.find(({kind:e})=>"CHECKPOINT"===e)?.resourceId??null})}oH(a,n);let s=JSON.stringify(n);return o4(s,"Workflow session data",2097152),!!(await i.workflowStepAttempt.updateMany({where:{id:e.id,status:{in:["RUNNING","WAITING"]}},data:{status:"SUCCEEDED",phase:"SUCCEEDED",outputJson:JSON.stringify({value:r.output,selectedHandles:r.selectedHandles,sessionPatch:r.sessionPatch}),error:null,finishedAt:new Date,claimOwner:null,claimExpiresAt:null}})).count&&(r.links?.length&&await i.workflowRunResourceLink.createMany({data:r.links.map(t=>({id:(0,b.randomUUID)(),runId:e.runId,attemptId:e.id,kind:t.kind.toUpperCase(),resourceId:t.resourceId,label:t.label??null,url:t.url??null,metadataJson:t.metadata?JSON.stringify(t.metadata):null}))}),await i.workflowRun.update({where:{id:e.runId},data:{sessionDataJson:s,sessionRevision:{increment:1}}}),await i.workflowRun.updateMany({where:{id:e.runId,status:{in:[...oF]}},data:{status:"RUNNING",phase:"SCHEDULING"}}),await i.workflowResourceLease.deleteMany({where:{attemptId:e.id}}),!0)})){if(i)try{await i()}catch(t){console.error(`Failed to append completion diagnostics for workflow attempt ${e.id}:`,t)}await this.appendEvent(e.runId,e.id,"STEP_SUCCEEDED",`Step ${t.name??t.id} completed`),o5(e.runId)}}async failAttempt(e,t,r,i={}){let a=await (0,t1.getPrismaClient)(),n=t??(await a.workflowRun.findUnique({where:{id:e.runId},include:{version:!0}}))?.version.definitionJson,s="string"==typeof n?(0,iC.parseWorkflowDefinition)(oV(n)).nodes.find(({id:t})=>t===e.nodeId)??null:n,o=s?.retry,l=!!(o&&e.attempt+1<o.maxAttempts),c=o?Math.min(86400,"EXPONENTIAL"===o.strategy?o.delaySeconds*2**e.attempt:o.delaySeconds):0;await a.$transaction(async t=>{let a=await t.workflowRun.findUnique({where:{id:e.runId}});if(!a||oq.has(a.status))return!1;let n=(0,st.workflowSessionData)(a.sessionDataJson);if(!e.iterationKey){i.sessionPatch&&(n=(0,st.mergeSessionData)(n,i.sessionPatch));let t=`steps.${e.nodeId}`,a=oK((0,st.getSessionValue)(n,t));n=(0,st.setSessionValue)(n,t,{...a,status:"FAILED",error:r.message,...void 0!==i.output?{output:i.output}:{}})}oH(a,n);let s=JSON.stringify(n);return o4(s,"Workflow session data",2097152),!!(await t.workflowStepAttempt.updateMany({where:{id:e.id,status:{in:["RUNNING","WAITING"]}},data:{status:"FAILED",phase:l?"RETRY_SCHEDULED":"FAILED",error:r.message.slice(0,2e4),finishedAt:new Date,claimOwner:null,claimExpiresAt:null}})).count&&(l&&await t.workflowWait.create({data:{id:(0,b.randomUUID)(),runId:e.runId,attemptId:e.id,kind:"RETRY",resumeAfter:new Date(Date.now()+1e3*c)}}),await t.workflowRun.update({where:{id:e.runId},data:{sessionDataJson:s,sessionRevision:{increment:1}}}),await t.workflowRun.updateMany({where:{id:e.runId,status:{in:[...oF]}},data:{status:l?"WAITING":"RUNNING",phase:l?"RETRY_WAIT":"SCHEDULING"}}),await t.workflowResourceLease.deleteMany({where:{attemptId:e.id}}),!0)})&&(await this.appendEvent(e.runId,e.id,l?"STEP_RETRY_SCHEDULED":"STEP_FAILED",l?`Step failed and will retry in ${c} seconds`:`Step failed: ${r.message}`,{error:r.message,retry:l}),o5(e.runId))}async resolveDueWaits(){let e=await (0,t1.getPrismaClient)(),t=new Date,r=(t,r)=>e.workflowWait.updateMany({where:{id:t,status:"PENDING",run:{status:{in:[...oF]}}},data:r});for(let i of(await e.workflowWait.findMany({where:{status:"PENDING",run:{status:{in:[...oF]}},OR:[{resumeAfter:{lte:t}},{timeoutAt:{lte:t}}]},include:{attempt:{include:{run:{include:{version:!0}}}}},orderBy:{createdAt:"asc"},take:100}))){if(i.timeoutAt&&i.timeoutAt<=t&&"RETRY"!==i.kind&&"DELAY"!==i.kind){if(!(await r(i.id,{status:"TIMED_OUT",resolvedAt:t})).count)continue;await this.failAttempt(i.attempt,(0,iC.parseWorkflowDefinition)(oV(i.attempt.run.version.definitionJson)).nodes.find(({id:e})=>e===i.attempt.nodeId)??null,Error("Workflow wait timed out"));continue}if("RETRY"===i.kind){let r=i.attempt.attempt+1;await e.$transaction(async e=>{if(!(await e.workflowWait.updateMany({where:{id:i.id,status:"PENDING",run:{status:{in:[...oF]}}},data:{status:"RESOLVED",resolvedAt:t}})).count)return!1;if(await e.workflowStepAttempt.create({data:{id:(0,b.randomUUID)(),runId:i.runId,nodeId:i.attempt.nodeId,kind:i.attempt.kind,generation:i.attempt.generation,iterationKey:i.attempt.iterationKey,attempt:r,status:"PENDING",phase:"RETRY_PENDING",inputJson:i.attempt.inputJson,requiredPathsJson:i.attempt.requiredPathsJson,providedPathsJson:i.attempt.providedPathsJson,idempotencyKey:`${i.runId}:${i.attempt.nodeId}:${i.attempt.generation}:${i.attempt.iterationKey}:${r}`,replayedFromId:i.attempt.id}}),!(await e.workflowRun.updateMany({where:{id:i.runId,status:{in:[...oF]}},data:{status:"RUNNING",phase:"SCHEDULING"}})).count)throw Error("Workflow lifecycle changed while resuming retry");return!0})&&o5(i.runId)}else if("DELAY"===i.kind){if(!(await r(i.id,{status:"RESOLVED",resolvedAt:t})).count)continue;await this.completeWaitingAttempt(i.attemptId,{delayed:!0},"TIMER")}else if("PREDICATE"===i.kind){let e=i.predicateJson?o6(oV(i.predicateJson),"Wait predicate"):{},a=e.condition,n=(0,st.workflowSessionData)(i.attempt.run.sessionDataJson);if(a&&oC(a,n)){if(!(await r(i.id,{status:"RESOLVED",resultJson:JSON.stringify({matched:!0}),resolvedAt:t})).count)continue;await this.completeWaitingAttempt(i.attemptId,{matched:!0},"POLL")}else{let t=Math.max(1,Number(e.cadenceSeconds??15));await r(i.id,{resumeAfter:new Date(Date.now()+1e3*t)})}}else if(i.externalKey&&this.waitPollers.has(i.kind)){let e=await this.waitPollers.get(i.kind)(i.externalKey);if("COMMAND_RUN"!==i.kind||e.pending||await this.reconcileCommandOutputMatches(i.externalKey),e.pending){let t=(0,iC.parseWorkflowDefinition)(oV(i.attempt.run.version.definitionJson)).nodes.find(({id:e})=>e===i.attempt.nodeId)?.config??{};await r(i.id,{resumeAfter:new Date(Date.now()+1e3*s2(t,e.pollAfterSeconds??15))})}else{if(!(await r(i.id,{status:e.error?"FAILED":"RESOLVED",resultJson:JSON.stringify(e.result??{}),resolvedAt:new Date})).count)continue;if(e.error){let t=(0,iC.parseWorkflowDefinition)(oV(i.attempt.run.version.definitionJson)).nodes.find(({id:e})=>e===i.attempt.nodeId),r=this.attemptOutput(i.attempt),a=oK(e.result),n=a.sessionPatch&&"object"==typeof a.sessionPatch&&!Array.isArray(a.sessionPatch)?(0,st.mergeSessionData)(r.sessionPatch??{},a.sessionPatch):r.sessionPatch;await this.failAttempt(i.attempt,t??null,Error(e.error),{output:e.result??r.value,sessionPatch:n})}else await this.completeWaitingAttempt(i.attemptId,e.result??{},"POLL")}}}}async completeWaitingAttempt(e,t,r="PUSH"){let i=await (0,t1.getPrismaClient)(),a=await i.workflowStepAttempt.findUnique({where:{id:e},include:{run:{include:{version:!0}}}});if(!a||"WAITING"!==a.status)return;let n=(0,iC.parseWorkflowDefinition)(oV(a.run.version.definitionJson)).nodes.find(({id:e})=>e===a.nodeId);if(!n)throw Error("Workflow step definition is missing");let s=this.attemptOutput(a),o=s.sessionPatch;if("TERMINAL_RUN"===n.kind&&t&&"object"==typeof t&&!Array.isArray(t)&&t.sessionData&&"object"==typeof t.sessionData&&!Array.isArray(t.sessionData)){let e=structuredClone(t.sessionData),r=(0,st.getSessionValue)((0,st.workflowSessionData)(a.run.sessionDataJson),"workflow");o=r?(0,st.setSessionValue)(e,"workflow",r):e}t&&"object"==typeof t&&!Array.isArray(t)&&t.sessionPatch&&"object"==typeof t.sessionPatch&&!Array.isArray(t.sessionPatch)&&(o=(0,st.mergeSessionData)(o??{},t.sessionPatch)),n.kind.startsWith("RUN_")&&t&&"object"==typeof t&&!Array.isArray(t)&&(o=(0,st.mergeSessionData)(o??{},(0,st.setSessionValue)({},`run.${n.id}`,t))),"BUILD_START"===n.kind&&t&&"object"==typeof t&&!Array.isArray(t)&&(o=(0,st.mergeSessionData)(o??{},(0,st.setSessionValue)({},"build",t))),"WORKTREE_WAIT_PUSH_READY"===n.kind&&t&&"object"==typeof t&&!Array.isArray(t)&&(o=(0,st.mergeSessionData)(o??{},(0,st.setSessionValue)({},"worktree",{id:t.id,pushStatus:t.pushStatus}))),"SKILL_APPLY"===n.kind&&t&&"object"==typeof t&&!Array.isArray(t)&&(o=(0,st.mergeSessionData)(o??{},(0,st.setSessionValue)({},`steps.${n.id}`,t))),("HUMAN_CONFIRM"===n.kind||"HUMAN_CHOICE"===n.kind)&&(o=(0,st.mergeSessionData)(o??{},(0,st.setSessionValue)({},`steps.${n.id}.answer`,t)));try{await this.completeAttempt(a,n,{output:t??s.value,selectedHandles:s.selectedHandles,sessionPatch:o},()=>this.appendWaitResolvedEvent(a,n,r))}catch(e){await this.failAttempt(a,n,e instanceof Error?e:Error(String(e)))}}async resolveExternalWait(e,t,r,i=null){let a=await (0,t1.getPrismaClient)(),n=await a.workflowWait.findMany({where:{kind:e,externalKey:t,status:"PENDING"},include:{attempt:{include:{run:{include:{version:!0}}}}}});for(let e of n)if(await a.workflowWait.update({where:{id:e.id},data:{status:i?"FAILED":"RESOLVED",resultJson:JSON.stringify(r),resolvedAt:new Date}}),i){let t=(0,iC.parseWorkflowDefinition)(oV(e.attempt.run.version.definitionJson)).nodes.find(({id:t})=>t===e.attempt.nodeId);await this.failAttempt(e.attempt,t??null,Error(i))}else await this.completeWaitingAttempt(e.attemptId,r,"PUSH");return n.length}descendants(e,t){let r=new Map;for(let t of e.edges)r.set(t.source,[...r.get(t.source)??[],t.target]);let i=new Set([t]),a=[t];for(;a.length;){let e=a.shift();for(let t of r.get(e)??[])i.has(t)||(i.add(t),a.push(t))}return[...i]}async prepareReplay(e,t){let r=await (0,t1.getPrismaClient)(),i=await r.workflowRun.findUnique({where:{id:e},include:{version:!0,attempts:{include:{checkpoints:!0,resourceLinks:!0}}}});if(!i)throw Error("Workflow run not found");if(!new Set(["PAUSED","BLOCKED","FAILED","SUCCEEDED","CANCELLED"]).has(i.status))throw Error("Pause the workflow before replaying a step");let a=(0,iC.parseWorkflowDefinition)(oV(i.version.definitionJson));if(!a.nodes.some(({id:e})=>e===t))throw Error("Workflow step not found");let n=this.descendants(a,t),s=i.attempts.filter(({generation:e,nodeId:t})=>e===i.generation&&n.includes(t)),o=s.filter(e=>e.nodeId===t).sort((e,t)=>t.attempt-e.attempt)[0],l=o?.checkpoints.slice().sort((e,t)=>e.createdAt.getTime()-t.createdAt.getTime())[0],c=s.flatMap(e=>e.resourceLinks.filter(({kind:e})=>"CHECKPOINT"!==e).map(({kind:e,resourceId:t,label:r,url:i})=>({kind:e,resourceId:t,label:r,url:i}))),u=null,d=null;if(l&&this.agentControl)try{u=await this.compareCheckpointWithAgent(l.id)}catch(e){d=`Git comparison unavailable: ${e instanceof Error?e.message:String(e)}`}return{runId:e,nodeId:t,affectedNodeIds:n,affectedAttemptIds:s.map(({id:e})=>e),externalEffects:c,checkpointId:l?.id??null,gitComparison:u,warning:[c.length?"External Jira, GitHub, build, deployment, and notification effects will not be undone.":null,d].filter(Boolean).join(" ")||null}}async replay(e,t,r={}){let i=await this.prepareReplay(e,t);if(r.restore){if(!i.checkpointId)throw Error("No restorable Git checkpoint is available for this step");this.checkpointRestorer?await this.checkpointRestorer(i.checkpointId,{stash:!!r.stash}):await this.restoreCheckpointWithAgent(i.checkpointId,{stash:!!r.stash})}let a=await (0,t1.getPrismaClient)(),n=await a.workflowRun.findUnique({where:{id:e},include:{version:!0,attempts:!0}});if(!n)throw Error("Workflow run not found");let s=(0,iC.parseWorkflowDefinition)(oV(n.version.definitionJson)),o=n.attempts.filter(e=>e.generation===n.generation&&e.nodeId===t).sort((e,t)=>t.attempt-e.attempt)[0];if(!o)throw Error("Selected step has no execution history");let l=o.inputJson?o6(oV(o.inputJson),"Step input snapshot"):(0,st.workflowSessionData)(n.sessionDataJson),c=n.generation+1,u=new Map;for(let e of n.attempts.filter(({generation:e,iterationKey:t})=>e===n.generation&&!t)){let t=u.get(e.nodeId);(!t||t.attempt<e.attempt)&&u.set(e.nodeId,e)}let d=(0,st.setSessionValue)(l,"workflow.replay",{generation:c,fromNodeId:t,replayedAt:new Date().toISOString()});return oH(n,d),await a.$transaction(async t=>{await t.workflowStepAttempt.updateMany({where:{runId:e,generation:n.generation,nodeId:{in:i.affectedNodeIds},supersededAt:null},data:{supersededAt:new Date}}),await t.workflowStepAttempt.createMany({data:s.nodes.map(t=>{let r=i.affectedNodeIds.includes(t.id),a=u.get(t.id);return{id:(0,b.randomUUID)(),runId:e,nodeId:t.id,kind:t.kind,generation:c,iterationKey:"",attempt:0,status:r?"PENDING":a?.status==="SKIPPED"?"SKIPPED":"SUCCEEDED",phase:r?"REPLAY_PENDING":"REUSED_FROM_PRIOR_GENERATION",inputJson:r?null:a?.inputJson,outputJson:r?null:a?.outputJson,error:null,startedAt:r?null:a?.startedAt,finishedAt:r?null:new Date,requiredPathsJson:JSON.stringify(o9(t)),providedPathsJson:JSON.stringify(o7(t)),idempotencyKey:`${e}:${t.id}:${c}::0`,replayedFromId:a?.id??null}})}),await t.workflowWait.updateMany({where:{runId:e,status:"PENDING"},data:{status:"SUPERSEDED",resolvedAt:new Date}}),await t.workflowRun.update({where:{id:e},data:{generation:c,sessionDataJson:JSON.stringify(d),sessionRevision:{increment:1},status:n.worktreeId?"QUEUED":"RUNNING",phase:n.worktreeId?"WAITING_FOR_WORKTREE":"REPLAYING",queuedAt:n.worktreeId?new Date:n.queuedAt,blockedReason:null,error:null,pausedAt:null,finishedAt:null}})}),await this.appendEvent(e,null,"RUN_REPLAYED",`Replaying from step ${t}`,{generation:c,affectedNodeIds:i.affectedNodeIds}),n.worktreeId&&await this.startQueuedRuns(),o5(e),this.run(e)}async appendWaitResolvedEvent(e,t,r){let i,a,n,s=await (0,t1.getPrismaClient)(),o=await s.workflowWait.findFirst({where:{attemptId:e.id},orderBy:{createdAt:"desc"}});if(!o)return;let l=Math.max(0,(o.resolvedAt??new Date).getTime()-o.createdAt.getTime());await this.appendEvent(e.runId,e.id,"STEP_WAIT_RESOLVED",`Step ${t.name??t.id} resumed after waiting ${(a=Math.floor((i=Math.max(0,Math.round(l/1e3)))/3600),n=Math.floor(i%3600/60),a?`${a}h ${n}m`:n?`${n}m ${i%60}s`:`${i}s`)} for ${s4(o.kind)}`,{waitId:o.id,kind:o.kind,nodeId:t.id,externalKey:o.externalKey,waitedMs:l,resolvedBy:r})}async appendEvent(e,t,r,i,a=null){let n=await (0,t1.getPrismaClient)(),s=await n.$transaction(async n=>{let s=await n.workflowRunEvent.findFirst({where:{runId:e},orderBy:{sequence:"desc"},select:{sequence:!0}});return n.workflowRunEvent.create({data:{id:(0,b.randomUUID)(),runId:e,attemptId:t,sequence:(s?.sequence??-1)+1,type:r,message:i.slice(0,2e4),detailJson:a?JSON.stringify(a):null}})});return ie.agentEventBus.publish(oU(e),{workflowRunEventAdded:s}),s}subscribeWorkflows(){return ie.agentEventBus.iterate(oL)}subscribeRun(e){return ie.agentEventBus.iterate(oB(e))}subscribeRunEvents(e){return ie.agentEventBus.iterate(oU(e))}subscribeRunQuestions(e){return ie.agentEventBus.iterate(oj(e))}}let lr=globalThis;e.s(["getServerServices",0,function(){var e,t,r,i,b,k,E,S,I,A,x,_,C,R,T,D,N;let O,P,L,B,U,j,M,q,$,F,G,K,H,V,W,J,z,Y,Z,Q,X,ee,et,er,ei,ea,en,es,eo,el,ec,eu,ed,ep,eh,em,ef,eg,ey;return lr.serverServices??(O=new w.PrismaService,P=new t3.CredentialService,L=new oE,B=new a.AgentControlService,U=new n_(P),j=new nD,M=new il(B),(q=new n5(B,U)).startRuntime(),$=new n.CcusageService(B),F=new s.BuildDataService(B),G=new nr.TelemetryService,K=new nl(B,void 0,P),H=new n$,V=new nc.PushNotificationsService(void 0,P,j),(W=new nF.RunsService(U,B,M)).startReaper(),J=new o.BuildsService(B,G,U,M),z=new nt(B),Y=new l.CodebasesService(B,z),Z=new c.CodebaseToolsService(Y),Q=new f.JiraService(P,L),X=new g.JiraWebhookService(Q,P,L),ee=new y.IosDevicesService(void 0,P),et=new d.GitHubPipelineStatusService,er=new u.GitHubActionsNotificationsService(P,U,j,!0,L,void 0,et),ei=new p.GitHubService(!0,P,j,()=>er.configurationChanged(),et),en=new sM(B,ei,ea=new h.GitLabService(P,L,j,U)),es=new m.CacheServerService(P),eo=new it.WorktreesService(B,Q,ei,z,L,et,ea),el=new se($,M,j),ec=new sp,eu=new sg,ed=new sC,ep=new aw(Z,J,{codebases:Y,telemetry:G,pushNotifications:V,agents:B,diskSpace:M,worktrees:eo,runs:W,commands:q,jira:Q,jiraWebhooks:X,github:ei,gitlab:ea,buildData:F,cacheServer:es,ccusage:$,credentials:P,iosDevices:ee,modelCosts:H,notifications:U,polling:j,signingAssets:K,skills:z,systemStatus:el,workflows:()=>em,worktreeAutomations:()=>ef},P),W.setMcpPresetResolver((e,t)=>ep.resolveRunMcpPresets(e,t)),em=new lt(L,eh=new oP,void 0,P,B,U,W,eo,q,Q),ef=new az(eo,ei,Q,em,B,j),t=em,r=e={agentControl:B,jira:Q,github:ei,gitlab:ea,worktrees:eo,worktreeAutomations:ef,codebases:Y,builds:J,skills:z,runs:W,commands:q,notifications:U,pushNotifications:V,tools:ep,diskSpace:M,buildData:F,ccusage:$,iosDevices:ee,modelCosts:H,signingAssets:K},t.registerWaitPoller("AGENT_JOB",async e=>{let t=await r.agentControl.getJob(e);return t?new Set(["QUEUED","RUNNING"]).has(t.status)?{pending:!0,pollAfterSeconds:2}:{pending:!1,result:t.resultJson?{...s6(JSON.parse(t.resultJson),"Agent job result"),jobId:e}:{jobId:e,status:t.status},error:"SUCCEEDED"===t.status?null:t.error||`Agent job ${t.status.toLowerCase()}`}:{pending:!1,error:"Agent job disappeared"}}),t.registerWaitPoller("AGENT_JOBS",async e=>{let t=s6(JSON.parse(e),"Agent jobs wait"),i=Array.isArray(t.ids)?t.ids.map(e=>s8(e,"Agent job ID",500)):[];if(!i.length)return{pending:!1,result:{jobs:[]}};let a=await Promise.all(i.map(e=>r.agentControl.getJob(e)));if(a.some(e=>!e))return{pending:!1,error:"Agent job disappeared"};let n=a.filter(e=>!!e);if(n.some(e=>new Set(["QUEUED","RUNNING"]).has(e.status)))return{pending:!0,pollAfterSeconds:2};let s=n.map(e=>({id:e.id,status:e.status,error:e.error})),o=s.filter(({status:e})=>"SUCCEEDED"!==e);return{pending:!1,result:{jobs:s,sessionPatch:{signing:{jobs:s}}},error:o.length?o.map(({id:e,status:t,error:r})=>r?`${e}: ${r}`:`${e}: ${t.toLowerCase()}`).join("; "):null}}),t.registerWaitPoller("AGENT_RUN",async e=>{let t=await r.runs.get(e);return t?new Set(["QUEUED","IN_PROGRESS","PAUSED"]).has(t.status)?{pending:!0,pollAfterSeconds:3}:{pending:!1,result:{id:t.id,kind:t.kind,status:t.status,phase:t.phase,finalOutput:t.finalOutput,error:t.error,usage:{inputTokens:t.inputTokens,outputTokens:t.outputTokens,reasoningTokens:t.reasoningTokens,estimatedCost:t.estimatedCost}},error:"COMPLETED"===t.status?null:t.error||`Run ${t.status.toLowerCase()}`}:{pending:!1,error:"Plan or session disappeared"}}),t.registerWaitPoller("COMMAND_RUN",async e=>{let t=await r.commands.getRun(e);return t?new Set(["QUEUED","RUNNING","RESTARTING","CANCELLING"]).has(t.status)?{pending:!0,pollAfterSeconds:1}:{pending:!1,result:{id:t.id,displayNumber:t.displayNumber,status:t.status,exitCode:t.exitCode,signal:t.signal,error:t.error,sessionPatch:{command:{id:t.id,commandId:t.commandId,name:t.snapshotName,status:t.status,exitCode:t.exitCode,signal:t.signal,error:t.error,finishedAt:t.finishedAt?.toISOString()??null}}},error:"SUCCEEDED"===t.status?null:t.error||`Command run ${t.status.toLowerCase()}`}:{pending:!1,error:"Command run disappeared"}}),t.registerWaitPoller("BUILD",async e=>{let t=await r.builds.getBuild(e);return t?new Set(["QUEUED","PREPARING","RUNNING"]).has(t.status)?{pending:!0,pollAfterSeconds:3}:{pending:!1,result:{id:t.id,status:t.status,action:t.action,sessionPatch:{build:{id:t.id,status:t.status,action:t.action,error:t.error}}},error:"SUCCEEDED"===t.status?null:t.error||`Build ${t.status.toLowerCase()}`}:{pending:!1,error:"Build disappeared"}}),t.registerWaitPoller("BUILD_DATA_COLLECTION",async e=>{let t=await r.buildData.getCollection(e);return t?"COMPLETED"!==t.status?{pending:!0,pollAfterSeconds:2}:{pending:!1,result:{...t,sessionPatch:{buildData:t}}}:{pending:!1,error:"Build-data collection disappeared"}}),t.registerWaitPoller("SIGNING_OPERATIONS",async e=>{let t=s6(JSON.parse(e),"Signing operations wait"),i=Array.isArray(t.ids)?t.ids.map(e=>s8(e,"Signing operation ID",500)):[];if(!i.length)return{pending:!1,result:{operations:[]}};let a=(await r.signingAssets.operations(200)).filter(({id:e})=>i.includes(e));if(a.length!==i.length)return{pending:!1,error:"Signing operation disappeared"};let n=new Set(["SUCCEEDED","FAILED","CANCELLED","TIMED_OUT"]);if(a.some(({status:e})=>!n.has(e)))return{pending:!0,pollAfterSeconds:2};let s=a.filter(({status:e})=>"SUCCEEDED"!==e);return{pending:!1,result:{operations:a,sessionPatch:{signing:{operations:a}}},error:s.length?s.map(({id:e,error:t,status:r})=>t?`${e}: ${t}`:`${e}: ${r.toLowerCase()}`).join("; "):null}}),t.registerWaitPoller("SKILL_RUN",async e=>{let t=await r.skills.getRun(e);return t?("READY"===t.status&&(t=await r.skills.applyRun(e)),new Set(["PREPARING","READY","APPLYING"]).has(t?.status??""))?{pending:!0,pollAfterSeconds:3}:{pending:!1,result:{id:e,status:t?.status},error:t?.status==="SUCCEEDED"?null:t?.error||`Skill run ${t?.status?.toLowerCase()}`}:{pending:!1,error:"Skill run disappeared"}}),t.registerWaitPoller("WORKTREE_MOVE",async e=>{let t=await r.worktrees.getMove(e);if(!t)return{pending:!1,error:"Worktree move disappeared"};if(new Set(["PUSHING","CHECKING_OUT","DELETING_SOURCE"]).has(t.status))return{pending:!0,pollAfterSeconds:3};let i=t.targetWorktreeId?await r.worktrees.workflowSessionDataForWorktree(t.targetWorktreeId,{includeMissing:!0}):{};return{pending:!1,result:{id:t.id,status:t.status,targetWorktreeId:t.targetWorktreeId,sessionPatch:i},error:"SUCCEEDED"===t.status?null:t.error||`Worktree move ${t.status.toLowerCase()}`}}),t.registerWaitPoller("WORKTREE_PUSH_READY",async e=>{let t=await (0,t1.getPrismaClient)(),i=await t.worktree.findUnique({where:{id:e}});if(!i)return{pending:!1,error:"Worktree disappeared"};if("READY"!==i.pushStatus)return{pending:!0,pollAfterSeconds:5};let a=await r.worktrees.workflowSessionDataForWorktree(i.id,{includeMissing:!0});return{pending:!1,result:{id:i.id,pushStatus:i.pushStatus,sessionPatch:a}}}),t.registerWaitPoller("WORKFLOW_RUN",async e=>{let r=await t.run(e);return r?new Set(["SUCCEEDED","FAILED","CANCELLED"]).has(r.status)?{pending:!1,result:{id:r.id,status:r.status,sessionData:JSON.parse(r.sessionDataJson)},error:"SUCCEEDED"===r.status?null:r.error||`Sub-workflow ${r.status.toLowerCase()}`}:{pending:!0,pollAfterSeconds:3}:{pending:!1,error:"Sub-workflow disappeared"}}),t.registerWaitPoller("RUN_ANSWER_REVISION",async e=>{let t=s6(JSON.parse(e),"Answer revision wait"),i=s8(t.batchId,"Question batch ID",500),a=await r.runs.questionBatch(i);if(!a)return{pending:!1,error:"Question batch disappeared"};if(!a.revisionPreparedAt)return{pending:!0,pollAfterSeconds:2};let n=await r.runs.reviseAnswer(i,t.answers??{},!0===t.stash,!1!==t.rollback);return n?{pending:!1,result:{id:n.id,kind:n.kind,status:n.status,phase:n.phase,parentRunId:n.parentRunId,followUpMode:n.followUpMode}}:{pending:!1,error:"Answer revision failed"}}),t.registerWaitPoller("GITHUB_CHECKS",async e=>{let t=s6(JSON.parse(e),"GitHub checks wait"),i=await r.github.autoRetryRun(s8(t.repositoryId,"Repository ID"),s8(t.workflowRunId,"Workflow run ID"),!0,"WORKFLOW_AUTOMATION");return new Set(["SUCCESS","FAILURE","CANCELLED","SKIPPED","TIMED_OUT","ACTION_REQUIRED","ERROR","NEUTRAL","STALE","STARTUP_FAILURE"]).has(i.status)?{pending:!1,result:{runId:i.id,status:i.status,jobs:i.jobs,sessionPatch:{pipeline:{runId:i.id,status:i.status,conclusion:i.status,jobs:i.jobs}}},error:"SUCCESS"===i.status?null:`GitHub checks concluded ${i.status.toLowerCase()}`}:{pending:!0,pollAfterSeconds:10}}),t.registerWaitPoller("GITLAB_PIPELINE",async e=>{let t=s6(JSON.parse(e),"GitLab pipeline wait"),i=await r.gitlab.pipeline(s8(t.projectId,"GitLab project ID",500),s8(t.pipelineId,"GitLab pipeline ID",500));return new Set(["SUCCESS","FAILED","CANCELED","SKIPPED","MANUAL"]).has(i.status)?{pending:!1,result:{id:i.id,projectId:i.projectId,status:i.status,webUrl:i.webUrl,sessionPatch:{pipeline:{id:i.id,projectId:i.projectId,status:i.status,webUrl:i.webUrl}}},error:"SUCCESS"===i.status?null:`GitLab pipeline concluded ${i.status.toLowerCase()}`}:{pending:!0,pollAfterSeconds:10}}),t.registerWaitPoller("DISK_SPACE_REPORT",async e=>{let t=s6(JSON.parse(e),"Disk-space report wait"),i=s8(t.agentId,"Agent ID",500),a=await r.diskSpace.snapshot(i);if(!a.disk.enabled)return{pending:!1,error:"Disk-space monitoring was disabled while awaiting a report"};let n=a.disk.lastReportedAt,s="string"==typeof t.previousReportedAt?t.previousReportedAt:null;return(s8(t.requestedAt,"Requested timestamp",100),n&&(!s||Date.parse(n)>Date.parse(s)))?{pending:!1,result:{...a,sessionPatch:a}}:{pending:!0,pollAfterSeconds:2}}),i=eh,b=e,i.register("JIRA_LOAD_TICKET",async e=>{let t=ou(await b.jira.ticket(op(e),!0===e.node.config.force));return{output:t,sessionPatch:{ticket:t},links:[oi(String(t.key),String(t.title??t.key))]}}),i.register("JIRA_TRANSITION",async e=>{let t=ou(await b.jira.transitionTicket(op(e),s8(e.node.config.transitionId,"Jira transition ID",200)));return{output:t,sessionPatch:{ticket:t},links:[oi(String(t.key),String(t.title??t.key))]}}),i.register("JIRA_COMMENT",async e=>{let t=ou(await b.jira.addComment(op(e),{value:s8(e.node.config.content,"Jira comment",1e5),format:"JIRA_WIKI"===e.node.config.format?"JIRA_WIKI":"MARKDOWN"}));return{output:t,sessionPatch:{ticket:t},links:[oi(String(t.key),String(t.title??t.key))]}}),i.register("JIRA_ASSIGN",async e=>{let t=null===e.node.config.accountId?null:s8(e.node.config.accountId,"Jira account ID",500),r=ou(await b.jira.assignTicket(op(e),t));return{output:r,sessionPatch:{ticket:r},links:[oi(String(r.key),String(r.title??r.key))]}}),i.register("JIRA_UPDATE_FIELDS",async e=>{let t=s6(e.node.config.fields??{},"Jira fields"),r=ou(await b.jira.updateTicket({issueKey:op(e),...t}));return{output:r,sessionPatch:{ticket:r},links:[oi(String(r.key),String(r.title??r.key))]}}),i.register("JIRA_RESOLVE_BRANCH",async e=>{let t=await b.worktrees.previewTicketBranch({codebaseId:s8(e.node.config.codebaseId??(0,st.getSessionValue)(e.sessionData,"codebase.id"),"Codebase ID",200),worktreeId:"string"==typeof(0,st.getSessionValue)(e.sessionData,"worktree.id")?String((0,st.getSessionValue)(e.sessionData,"worktree.id")):null,ticketKey:op(e)});return{output:t,sessionPatch:{worktree:{branch:t.branchName},ticket:{key:t.ticketKey,title:t.ticketTitle,type:t.ticketType}},links:[oi(t.ticketKey,t.ticketTitle)]}}),k=eh,E=e,k.register("GITHUB_LOAD_PR",async e=>{let t=oc(e),r=await E.github.pullRequest(t.owner,t.name,om(e),"WORKFLOW_AUTOMATION");if(!r)throw Error("Pull request was not found");let i=od(r);return{output:i,sessionPatch:{pr:i},links:[or("PULL_REQUEST",sq(t.owner,t.name,r.number),r.title,r.url)]}}),k.register("GITHUB_MERGE_PR",async e=>{let t=oc(e),r=om(e),i=await E.github.pullRequestMergeOptions(t.owner,t.name,r,"WORKFLOW_AUTOMATION");if(!i.canMerge)throw Error(i.blockedReason||"Pull request cannot be merged");let a=await E.github.mergePullRequest({...t,number:r,method:"MERGE"===e.node.config.method||"REBASE"===e.node.config.method?e.node.config.method:"SQUASH",commitHeadline:"string"==typeof e.node.config.commitHeadline?e.node.config.commitHeadline:i.defaultCommitHeadline,commitBody:"string"==typeof e.node.config.commitBody?e.node.config.commitBody:i.defaultCommitBody,authorEmail:"string"==typeof e.node.config.authorEmail?e.node.config.authorEmail:null},"WORKFLOW_AUTOMATION");return{output:a,sessionPatch:{pr:{state:a.state}},links:[oa(e)]}}),k.register("GITHUB_COLLECT_REVIEW_THREADS",async e=>{let t=oc(e),r=await E.github.pullRequest(t.owner,t.name,om(e),"WORKFLOW_AUTOMATION");if(!r)throw Error("Pull request was not found");let i=r.reviewThreads.filter(({isResolved:e})=>!e);return{output:i,sessionPatch:{pr:{unresolvedThreads:i}},links:[oa(e,r.title,r.url)]}}),k.register("GITHUB_REPLY_REVIEW_THREAD",async e=>{let t=await E.github.replyToReviewThread(s8(e.node.config.threadId,"Review thread ID",500),s8(e.node.config.body,"Review reply",1e5),"WORKFLOW_AUTOMATION"),r=on(e);return{output:t,links:r?[r]:void 0}}),k.register("GITHUB_SET_REVIEW_THREAD_RESOLVED",async e=>{let t=await E.github.setReviewThreadResolved(s8(e.node.config.threadId,"Review thread ID",500),!1!==e.node.config.resolved,"WORKFLOW_AUTOMATION"),r=on(e);return{output:t,links:r?[r]:void 0}}),k.register("GITHUB_CREATE_PR",async e=>{let t=oc(e),r=await E.github.createPullRequest({...t,baseRefName:s8(e.node.config.baseRefName??(0,st.getSessionValue)(e.sessionData,"worktree.baseBranch"),"Base branch",500),headRefName:s8(e.node.config.headRefName??(0,st.getSessionValue)(e.sessionData,"worktree.branch"),"Head branch",500),title:s8(e.node.config.title??(0,st.getSessionValue)(e.sessionData,"ticket.title"),"Pull request title",500),body:"string"==typeof e.node.config.body?e.node.config.body:null,draft:!0===e.node.config.draft});await E.worktrees.attachPullRequestForBranch(`github.com/${t.owner}/${t.name}`,r.headRefName,r);let i=od(r);return{output:i,sessionPatch:{pr:i},links:[or("PULL_REQUEST",sq(t.owner,t.name,r.number),r.title,r.url)]}}),k.register("GITHUB_SET_PR_LABELS",async e=>{let t=oc(e),r=Array.isArray(e.node.config.labels)?e.node.config.labels.map(String):[],i=await E.github.setPullRequestLabels({...t,number:om(e),labels:r});return{output:i.labels,sessionPatch:{pr:{labels:i.labels}},links:[oa(e)]}}),k.register("GITHUB_RETRY_PIPELINE",async e=>{let t=await E.github.retryPipeline(s8(e.node.config.repositoryId??(0,st.getSessionValue)(e.sessionData,"pr.repositoryGithubId"),"GitHub repository ID",500),s8(e.node.config.checkSuiteId??(0,st.getSessionValue)(e.sessionData,"pipeline.checkSuiteId"),"Check suite ID",500),"WORKFLOW_AUTOMATION",{actor:"workflow",ipAddress:null}),r=os(e);return{output:t,sessionPatch:{pipeline:{status:t.status}},links:r?[r]:void 0}}),k.register("GITHUB_RETRY_JOB",async e=>{let t=await E.github.retryWorkflowJob(s8(e.node.config.repositoryId,"GitHub repository ID",500),s8(e.node.config.checkSuiteId,"Check suite ID",500),s8(e.node.config.jobId,"Workflow job ID",500),"WORKFLOW_AUTOMATION",{actor:"workflow",ipAddress:null}),r=os(e);return{output:t,links:r?[r]:void 0}}),k.register("GITHUB_CANCEL_WORKFLOW_RUN",async e=>{let t=await E.github.cancelActionsWorkflowRun(s8(e.node.config.codebaseRepositoryId??(0,st.getSessionValue)(e.sessionData,"repo.id"),"Codebase repository ID",500),s8(e.node.config.workflowRunId??(0,st.getSessionValue)(e.sessionData,"pipeline.runId"),"Workflow run ID",500),!0===e.node.config.force,"WORKFLOW_AUTOMATION",{actor:"workflow",ipAddress:null}),r=os(e);return{output:t,sessionPatch:{pipeline:{status:"CANCELLED"}},links:r?[r]:void 0}}),k.register("GITHUB_SAVE_AUTO_RETRY",async e=>({output:await E.github.saveAutoRetryRule(s6(e.node.config.input,"Auto-retry rule"))})),k.register("GITHUB_WAIT_CHECKS",async e=>{let t=s8(e.node.config.repositoryId??(0,st.getSessionValue)(e.sessionData,"repo.id"),"Repository ID",500),r=s8(e.node.config.workflowRunId??(0,st.getSessionValue)(e.sessionData,"pipeline.runId"),"Workflow run ID",500),i=os(e);return{links:i?[i]:void 0,wait:{kind:"GITHUB_CHECKS",externalKey:JSON.stringify({repositoryId:t,workflowRunId:r}),resumeAfter:s3(e.node.config),timeoutAt:s1(e.node.config)}}}),S=eh,I=e,S.register("WORKTREE_CREATE",async e=>{let t=oy(e),r=await I.worktrees.createWorktree({codebaseId:og(e),selection:t,requestId:s7(e,"create")});return ot(e,r,{worktree:{branch:t.branchName,baseBranch:t.baseBranch}})}),S.register("WORKTREE_CHANGE_BRANCH",async e=>{let t=of(e),r=oy(e),i=await I.worktrees.changeWorktreeBranch({worktreeId:t,selection:r,requestId:s7(e,"change-branch"),stashOnFailure:!0===e.node.config.stashOnFailure});return ot(e,i,{worktree:{branch:r.branchName,baseBranch:r.baseBranch}},[or("WORKTREE",t,"Worktree")])}),S.register("WORKTREE_COMMIT",async e=>{let t=of(e),r=!1!==e.node.config.stageAll,i=e.node.config.paths,a=Array.isArray(i)?i.map(e=>s8(e,"Selected path",2e3)):[],n=await I.worktrees.commitWorktree({worktreeId:t,message:s8(e.node.config.message,"Commit message",5e4),signed:"boolean"==typeof e.node.config.signed?e.node.config.signed:null,stageAll:r,paths:a,requestId:s7(e,"commit")});return ot(e,n,void 0,[or("WORKTREE",t,"Worktree")])}),S.register("WORKTREE_REFRESH_PULL_REQUEST",async e=>{let t=of(e),r=(await I.worktrees.refreshPullRequest(t)).pullRequest,i=r?od(r):null,a=[or("WORKTREE",t,"Worktree")];if(r){let[e,t]=r.repositoryNameWithOwner.split("/");e&&t&&a.push(or("PULL_REQUEST",sq(e,t,r.number),r.title,r.url))}return{output:{found:!!r,pullRequest:r},sessionPatch:{pr:i},links:a}}),S.register("WORKTREE_OPERATION",async e=>{let t=String(e.node.config.operation??"SYNC").toUpperCase();if("OPEN_EDITOR"===t||!i0.WORKTREE_OPERATIONS.includes(t))throw Error("Worktree operation is invalid for workflow execution");let r=of(e),i=await I.worktrees.runOperation(r,t,s7(e,t.toLowerCase()),!0===e.node.config.forcePreparations);return ot(e,i,void 0,[or("WORKTREE",r,"Worktree")])}),S.register("WORKTREE_PREPARATION",async e=>{let t=of(e),r=String(e.node.config.action??"INSPECT").toUpperCase();if(!i0.WORKTREE_PREPARATION_ACTIONS.includes(r))throw Error("Worktree preparation action is invalid");let i=await I.worktrees.runPreparations([t],r,s7(e,`preparation-${r.toLowerCase()}`)),a=i.jobs[0];if(!a)throw Error(i.skipped[0]?.reason??"Worktree preparation was not dispatched");return ot(e,a,void 0,[or("WORKTREE",t,"Worktree")])}),S.register("WORKTREE_SET_AUTO_SYNC",async e=>{let t=of(e),r=String(e.node.config.action??"ENABLE").toUpperCase();if("FORCE"===r){let r=await I.worktreeAutomations.forceAutoSync(t,s7(e,"force-auto-sync"));return ot(e,r,void 0,[or("WORKTREE",t,"Worktree")])}let i="CANCEL"===r?{cancelled:await I.worktreeAutomations.cancelAutoSync(t)}:"RETRY"===r?await I.worktreeAutomations.retryAutoSync(t):"ENABLE"===r?await I.worktreeAutomations.configureAutoSync({worktreeId:t,conflictWorkflowId:s5(e.node.config.conflictWorkflowId,500),conflictWorkflowChoice:s5(e.node.config.conflictWorkflowChoice,500)}):null;if(!i)throw Error("Unknown Auto Sync action");return{output:i,sessionPatch:{worktree:{autoSync:i}},links:[or("WORKTREE",t,"Worktree")]}}),S.register("WORKTREE_SET_AUTO_MERGE",async e=>{let t,r=of(e),i=String(e.node.config.action??"ENABLE").toUpperCase();if("CANCEL"===i)t={cancelled:await I.worktreeAutomations.cancelAutoMerge(r)};else if("RETRY"===i)t=await I.worktreeAutomations.retryAutoMerge(r);else if("ENABLE"===i){let i=Number(e.node.config.pullRequestNumber??(0,st.getSessionValue)(e.sessionData,"pr.number"));if(!Number.isInteger(i)||i<1)throw Error("Pull request number must be a positive integer");let a=String(e.node.config.method??"SQUASH").toUpperCase();if(!["MERGE","REBASE","SQUASH"].includes(a))throw Error("Merge method is invalid");t=await I.worktreeAutomations.configureAutoMerge({worktreeId:r,repositoryNameWithOwner:s8(e.node.config.repositoryNameWithOwner??(0,st.getSessionValue)(e.sessionData,"repo.nameWithOwner"),"Repository",500),pullRequestNumber:i,method:a,commitHeadline:s8(e.node.config.commitHeadline??(0,st.getSessionValue)(e.sessionData,"pr.title"),"Commit headline",1e3),commitBody:String(e.node.config.commitBody??""),authorEmail:s5(e.node.config.authorEmail,500),deleteWorktree:!0===e.node.config.deleteWorktree,moveTicketToDone:!0===e.node.config.moveTicketToDone})}else throw Error("Unknown Auto Merge action");return{output:t,sessionPatch:{worktree:{autoMerge:t}},links:[or("WORKTREE",r,"Worktree")]}}),S.register("WORKTREE_DELETE",async e=>{let t=await I.worktrees.deleteWorktree({worktreeId:of(e),deleteRemoteBranch:!0===e.node.config.deleteRemoteBranch,requestId:s7(e,"delete")});return ot(e,t)}),S.register("WORKTREE_MOVE",async e=>{let t=await I.worktrees.moveWorktree({sourceWorktreeId:of(e),targetCodebaseId:s8(e.node.config.targetCodebaseId,"Target codebase ID",500),targetWorktreeId:s5(e.node.config.targetWorktreeId,500),deleteSource:!0===e.node.config.deleteSource,requestId:s7(e,"move")}),r=t.targetWorktreeId??(!0===e.node.config.deleteSource?null:of(e));return{output:t,links:[...r?[or("WORKTREE",r,"Worktree")]:[],{kind:"WORKTREE_MOVE",resourceId:t.id,label:"Worktree move"}],wait:{kind:"WORKTREE_MOVE",externalKey:t.id,resumeAfter:s3(e.node.config),timeoutAt:s1(e.node.config)}}}),S.register("WORKTREE_INSPECT",async e=>{let t=of(e),r=await I.worktrees.inspect(t,s7(e,"inspect"));return{output:r,sessionPatch:{worktree:{commits:r.commits,changes:r.changes,branchChanges:r.branchChanges}},links:[or("WORKTREE",t,"Worktree")]}}),S.register("WORKTREE_INSPECT_GIT",async e=>{let t=of(e),r=await I.worktrees.inspectGitState(t,s7(e,"inspect-git"));return{output:r,sessionPatch:{worktree:{...r}},links:[or("WORKTREE",t,"Worktree")]}}),S.register("WORKTREE_GIT_OPERATION",async e=>{let t=String(e.node.config.operation??"PULL_BRANCH").toUpperCase();if(!i0.WORKTREE_GIT_OPERATIONS.includes(t))throw Error("Worktree Git operation is invalid");let r=of(e),i=await I.worktrees.runGitOperation({worktreeId:r,operation:t,branch:s5(e.node.config.branch,500),stashOid:s5(e.node.config.stashOid,200),stashChanges:!0===e.node.config.stashChanges,requestId:s7(e,t.toLowerCase())});return ot(e,i,void 0,[or("WORKTREE",r,"Worktree")])}),S.register("WORKTREE_WAIT_PUSH_READY",async e=>{let t=of(e);return{links:[or("WORKTREE",t,"Worktree")],wait:{kind:"WORKTREE_PUSH_READY",externalKey:t,resumeAfter:s3(e.node.config),timeoutAt:s1(e.node.config)}}}),A=eh,x=e,A.register("CODEBASE_FETCH_REFRESH",async e=>{let t=og(e),r="REFRESH"===e.node.config.operation?rg.CODEBASE_REFRESH_JOB_KIND:rg.CODEBASE_FETCH_JOB_KIND,i=await x.codebases.runOperation(r,[t],s7(e,r)),a=i.jobs[0];if(!a)throw Error(i.skipped[0]?.reason??"Codebase operation was skipped");return ot(e,a,void 0,[or("CODEBASE",t,"Codebase")])}),A.register("CODEBASE_INSPECT_GIT",async e=>{let t=og(e),r=await x.codebases.inspectGitState(t,s7(e,"inspect-git"));return{output:r,sessionPatch:{codebase:{...r}},links:[or("CODEBASE",t,"Codebase")]}}),A.register("CODEBASE_GIT_OPERATION",async e=>{let t=String(e.node.config.operation??"PULL_BRANCH").toUpperCase();if(!rg.CODEBASE_GIT_OPERATIONS.includes(t))throw Error("Codebase Git operation is invalid");let r=og(e),i=await x.codebases.runGitOperation({codebaseId:r,operation:t,branch:s5(e.node.config.branch,500),stashOid:s5(e.node.config.stashOid,200),stashChanges:!0===e.node.config.stashChanges,requestId:s7(e,t.toLowerCase())});return ot(e,i,void 0,[or("CODEBASE",r,"Codebase")])}),_=eh,C=e,_.register("BUILD_START",async e=>{let t=String(e.node.config.action??"BUILD").toUpperCase();if(!v.BUILD_ACTIONS.includes(t))throw Error("Build action is invalid");let r=await C.builds.startBuild({worktreeId:of(e),configurationId:s8(e.node.config.configurationId,"Build configuration ID",500),destination:e.node.config.destination,scriptIds:Array.isArray(e.node.config.scriptIds)?e.node.config.scriptIds.map(String):[],action:t,advancedSettings:e.node.config.advancedSettings,exportWhenComplete:!0===e.node.config.exportWhenComplete,exportSettings:e.node.config.exportSettings,worktreeCoverage:!0===e.node.config.worktreeCoverage,requestId:s7(e,"build"),telemetryRequestOrigin:"workflow"});return{output:r,sessionPatch:{build:{id:r.id,status:r.status,action:r.action}},links:[{kind:"BUILD",resourceId:r.id,label:`${r.action} build`,url:`/builds/${r.id}`}],wait:{kind:"BUILD",externalKey:r.id,resumeAfter:s3(e.node.config),timeoutAt:s1(e.node.config)}}}),_.register("BUILD_READ_TEST_RESULTS",async e=>{let t,r=ow(e),i=(await C.builds.reportsForBuild(r)).filter(({kind:e,status:t})=>"TEST_RESULTS"===e&&"READY"===t).at(-1);if(!i)throw Error("Test results are not ready");let a=s6(JSON.parse(i.summaryJson),"Test summary"),n=s6(JSON.parse(i.dataJson),"Test results");return{output:{summary:a,tests:n.tests??[]},sessionPatch:{build:{testSummary:a,tests:n.tests??[]}},links:[or("BUILD",r,"Build",t)]}}),_.register("BUILD_READ_COVERAGE",async e=>{let t=ow(e),r=(await C.builds.reportsForBuild(t)).filter(({kind:e,status:t})=>"CODE_COVERAGE"===e&&"READY"===t).at(-1);if(!r)throw Error("Coverage results are not ready");let i=s6(JSON.parse(r.summaryJson),"Coverage summary"),a=s6(JSON.parse(r.dataJson),"Coverage results");return{output:{summary:i,files:a.files??[],changedFiles:a.changedFiles??[]},sessionPatch:{build:{coverageSummary:i,coverageFiles:a.files??[],changedCoverageFiles:a.changedFiles??[]}},links:[or("BUILD",t,"Build",`/builds/${t}/coverage`)]}}),_.register("BUILD_IMPORT_COVERAGE",async e=>{let t=of(e),r=await C.builds.importCoverageReport({worktreeId:t,buildName:s5(e.node.config.buildName,200)??s5((0,st.getSessionValue)(e.sessionData,"workflow.name"),200)??"Coverage report",reportPath:s8(e.node.config.reportPath??"coverage/lcov.info","Coverage file",4e3),format:s5(e.node.config.format)??"AUTO",requestId:s7(e,"coverage-import")}),i=[or("WORKTREE",t,"Worktree"),or("BUILD",r.id,"Build",`/builds/${r.id}`)];return"jobId"in r&&"string"==typeof r.jobId?ot(e,{id:r.jobId,timeoutSeconds:300},{build:{id:r.id}},i):{output:r,sessionPatch:{build:{id:r.id}},links:i}}),_.register("BUILD_EXPORT",async e=>{let t,r,i=ow(e),a=await C.builds.exportArchive({buildId:i,requestId:s7(e,"export"),settings:s6(e.node.config.settings,"Export settings")});return a.jobId?ot(e,{id:a.jobId,timeoutSeconds:3600},{build:{exportId:a.id}},[or("BUILD",i,"Build",t)]):{output:a,links:[or("BUILD",i,"Build",r)]}}),_.register("BUILD_DEPLOY",async e=>{let t,r,i=ow(e),a=await C.builds.runBuild({buildId:i,destinations:Array.isArray(e.node.config.destinations)?e.node.config.destinations:[],requestId:s7(e,"deploy")}),n=a.find(({jobId:e})=>!!e)?.jobId;return n?ot(e,{id:n,timeoutSeconds:3600},void 0,[or("BUILD",i,"Build",t)]):{output:a,links:[or("BUILD",i,"Build",r)]}}),_.register("BUILD_CANCEL",async e=>{let t,r=ow(e),i=await C.builds.cancelBuild(r);return{output:i,sessionPatch:{build:{id:i?.id,status:i?.status}},links:[or("BUILD",r,"Build",t)]}}),R=eh,T=e,ey=async e=>{let t=await T.diskSpace.snapshot(e);return{output:t,sessionPatch:t,links:[or("AGENT",e,t.agent.name,`/agents/${encodeURIComponent(e)}`)]}},R.register("DISK_SPACE_LOAD",async e=>ey(ob(e))),R.register("DISK_SPACE_REFRESH",async e=>{let t=ob(e),r=await T.diskSpace.requestRefresh(t);return{output:r,links:[or("AGENT",t,"Agent",`/agents/${encodeURIComponent(t)}`)],wait:{kind:"DISK_SPACE_REPORT",externalKey:JSON.stringify(r),resumeAfter:s3(e.node.config,2),timeoutAt:s1(e.node.config,180)}}}),R.register("DISK_SPACE_UPDATE_THRESHOLDS",async e=>{let t=await T.diskSpace.updateSettings({normalThresholdGiB:Number(e.node.config.normalThresholdGiB),pressureThresholdGiB:Number(e.node.config.pressureThresholdGiB)});return{output:t,sessionPatch:{disk:t}}}),R.register("DISK_SPACE_SET_MONITORING",async e=>{let t=ob(e);return await T.diskSpace.setMonitoring(t,!0===e.node.config.enabled),ey(t)}),R.register("DISK_SPACE_SET_PRESSURE_MODE",async e=>{let t=ob(e);return await T.diskSpace.setManualPressureMode(t,!0===e.node.config.enabled),ey(t)}),function(e,t){for(let[r,i]of(e.register("RUN_CREATE_PLAN",async e=>{let r=await t.runs.create(ok(e,"PLAN"));if(!r)throw Error("Plan could not be created");return oe(e,r,!0)}),e.register("RUN_CREATE_SESSION",async e=>{let r=await t.runs.create(ok(e,"SESSION"));if(!r)throw Error("Session could not be created");return oe(e,r,!0)}),e.register("RUN_PLAY_PLAN",async e=>{let r=e.node.config.worktreeConcurrencyLimit,i=await t.runs.playPlan(ov(e),Array.isArray(e.node.config.mcpPresetIds)?e.node.config.mcpPresetIds.map(String):[],"number"==typeof r?r:void 0,e.run.id);if(!i)throw Error("Plan could not be played");return oe(e,i,!0)}),e.register("RUN_FOLLOW_UP",async e=>{let r=ok(e,"SESSION"),i=await t.runs.followUp(ov(e),{...r,followUpMode:s8(e.node.config.followUpMode??"RESUME","Follow-up mode",50),contextMode:s5(e.node.config.contextMode,50)});if(!i)throw Error("Follow-up could not be created");return oe(e,i,!0)}),e.register("RUN_STEER",async e=>{let r=await t.runs.steer(ov(e),s8(e.node.config.prompt,"Steering prompt",2e5),Array.isArray(e.node.config.attachmentIds)?e.node.config.attachmentIds.map(String):[]);if(!r)throw Error("Run could not be steered");return oe(e,r)}),e.register("RUN_ANSWER",async e=>{let r=await t.runs.answerQuestion(s8(e.node.config.batchId,"Question batch ID",500),e.node.config.answers??{});if(!r)throw Error("Question could not be answered");return oe(e,r)}),[["RUN_PAUSE","PAUSE"],["RUN_CONTINUE","CONTINUE"],["RUN_CANCEL","CANCEL"]]))e.register(r,async e=>{let r=await t.runs.lifecycle(ov(e),i);if(!r)throw Error("Run lifecycle operation failed");return oe(e,r)});e.register("RUN_REVISE_ANSWER",async e=>{let r=s8(e.node.config.batchId,"Question batch ID",500),i=await t.runs.questionBatch(r);if(!i)throw Error("Question batch was not found");if(i.revisionPreparedAt){let i=await t.runs.reviseAnswer(r,e.node.config.answers??{},!0===e.node.config.stash,!1!==e.node.config.rollback);if(!i)throw Error("Answer revision failed");return oe(e,i)}await t.runs.prepareAnswerRevision(r);let a=oo(e);return{links:a?[a]:void 0,wait:{kind:"RUN_ANSWER_REVISION",externalKey:JSON.stringify({batchId:r,answers:e.node.config.answers??{},stash:!0===e.node.config.stash,rollback:!1!==e.node.config.rollback}),resumeAfter:s3(e.node.config),timeoutAt:s1(e.node.config)}}}),e.register("RUN_READ_RESULT",async e=>{let r=await t.runs.get(ov(e));if(!r)throw Error("Run was not found");let[i,a,n,s]=await Promise.all([t.runs.events({runId:r.id,first:500}),t.runs.questions({runId:r.id,first:200}),t.runs.usage(r.id),t.runs.linkedItems(r.id)]);return oe(e,{...r,events:i,questions:a,usage:n,links:s})}),e.register("RUN_CAPTURE_CHECKPOINT",async e=>{let t=await (0,t1.getPrismaClient)(),r=await t.runCheckpoint.findFirst({where:{runId:ov(e)},orderBy:{createdAt:"desc"}});if(!r)throw Error("Run has no captured checkpoint");let i=oo(e);return{output:r,sessionPatch:{steps:{[e.node.id]:{snapshotId:r.id}}},links:[...i?[i]:[],{kind:"CHECKPOINT",resourceId:r.id,label:`${r.kind} checkpoint`}]}}),e.register("RUN_ARCHIVE_DELETE",async e=>{let r=ov(e),i=!0===e.node.config.delete,a=i?await t.runs.deleteRuns([r]):await t.runs.archive([r],!1!==e.node.config.archived),n=i?null:oo(e);return{output:{id:r,affected:a},links:n?[n]:void 0}})}(eh,e),D=eh,N=e,D.register("SAVED_COMMAND",async e=>{let t=s8(e.node.config.commandId,"Saved command",500),r=await N.commands.getDefinition(t);if(!r||r.archivedAt)throw Error("Saved command is unavailable");let i="FIRE_AND_FORGET"===e.node.config.completionMode?"FIRE_AND_FORGET":"WAIT_FOR_EXIT",a=(0,sY.commandOutputPattern)(e.node.config),n=(0,sY.commandOutputMatchMode)(e.node.config),s=Array.isArray((0,st.getSessionValue)(e.sessionData,`steps.${e.node.id}.matches`))?(0,st.getSessionValue)(e.sessionData,`steps.${e.node.id}.matches`):[];if(a&&(sX(a),"WAIT_FOR_EXIT"!==i))throw Error("Output matching requires Wait for exit completion");if("WAIT_FOR_EXIT"===i&&"ALWAYS"===r.restartPolicy)throw Error("Always-restart commands require fire and forget");let o=String(e.node.config.targetMode??"CONTEXT"),l=null,c=null,u=new Set(["ANY_AGENT_HOME","SPECIFIC_AGENT_HOME"]).has(r.targetKind);if("FIXED_AGENT"===o)l=s8(e.node.config.agentId,"Fixed agent",500);else if("FIXED_WORKTREE"===o)c=s8(e.node.config.worktreeId,"Fixed worktree",500);else if(u){let t=(0,st.getSessionValue)(e.sessionData,"agent.id")??(0,st.getSessionValue)(e.sessionData,"codebase.agentId");if("string"==typeof t&&(l=t),!l){let t=(0,st.getSessionValue)(e.sessionData,"worktree.id");if("string"==typeof t){let e=await (0,t1.getPrismaClient)(),r=await e.worktree.findUnique({where:{id:t},select:{codebase:{select:{agentId:!0}}}});l=r?.codebase.agentId??null}}}else{let t=(0,st.getSessionValue)(e.sessionData,"worktree.id");"string"==typeof t&&(c=t)}let d=await N.commands.startRun({commandId:t,agentId:l,worktreeId:c,origin:"WORKFLOW",idempotencyKey:e.attempt.idempotencyKey,blocksGitOperations:e.run.blocksGitOperations});if(!d)throw Error("Command run could not be created");return{output:{id:d.id,displayNumber:d.displayNumber,status:d.status},sessionPatch:{steps:{[e.node.id]:{commandRunId:d.id,displayNumber:d.displayNumber,matches:s,latestMatch:s.at(-1)??null}}},links:[{kind:"COMMAND_RUN",resourceId:d.id,label:`Command #${d.displayNumber}`,url:`/commands/runs/${d.id}`}],wait:"WAIT_FOR_EXIT"===i?{kind:"COMMAND_RUN",externalKey:d.id,predicate:a?{outputMatch:{pattern:a,mode:n,matchCount:s.length,matched:"ONCE"===n&&s.length>0,scanAttempt:1,scanCharacterOffset:0,observedAttempt:0,observedSequence:-1}}:void 0,resumeAfter:s3(e.node.config),timeoutAt:s1(e.node.config)}:void 0}}),D.register("CUSTOM_COMMAND",async e=>{let t=s8(e.node.config.script,"Custom command",1e6),r="FIRE_AND_FORGET"===e.node.config.completionMode?"FIRE_AND_FORGET":"WAIT_FOR_EXIT",i=(0,sY.commandOutputPattern)(e.node.config),a=(0,sY.commandOutputMatchMode)(e.node.config),n=Array.isArray((0,st.getSessionValue)(e.sessionData,`steps.${e.node.id}.matches`))?(0,st.getSessionValue)(e.sessionData,`steps.${e.node.id}.matches`):[];if(i&&(sX(i),"WAIT_FOR_EXIT"!==r))throw Error("Output matching requires Wait for exit completion");let s=String(e.node.config.targetMode??"CONTEXT"),o=null,l=null;if("FIXED_AGENT"===s)o=s8(e.node.config.agentId,"Fixed agent",500);else if("FIXED_WORKTREE"===s)l=s8(e.node.config.worktreeId,"Fixed worktree",500);else{let t=(0,st.getSessionValue)(e.sessionData,"worktree.id");if("string"==typeof t)l=t;else{let t=(0,st.getSessionValue)(e.sessionData,"agent.id")??(0,st.getSessionValue)(e.sessionData,"codebase.agentId");"string"==typeof t&&(o=t)}}if(!o&&!l)throw Error("Custom command context has no agent or worktree target");let c=await N.commands.startCustomRun({script:t,agentId:o,worktreeId:l,origin:"WORKFLOW",idempotencyKey:e.attempt.idempotencyKey,blocksGitOperations:e.run.blocksGitOperations});if(!c)throw Error("Custom command run could not be created");return{output:{id:c.id,displayNumber:c.displayNumber,status:c.status},sessionPatch:{steps:{[e.node.id]:{commandRunId:c.id,displayNumber:c.displayNumber,matches:n,latestMatch:n.at(-1)??null}}},links:[{kind:"COMMAND_RUN",resourceId:c.id,label:`Command #${c.displayNumber}`,url:`/commands/runs/${c.id}`}],wait:"WAIT_FOR_EXIT"===r?{kind:"COMMAND_RUN",externalKey:c.id,predicate:i?{outputMatch:{pattern:i,mode:a,matchCount:n.length,matched:"ONCE"===a&&n.length>0,scanAttempt:1,scanCharacterOffset:0,observedAttempt:0,observedSequence:-1}}:void 0,resumeAfter:s3(e.node.config),timeoutAt:s1(e.node.config)}:void 0}}),D.register("SKILL_APPLY",async e=>{let t=await N.skills.prepareSync(e.node.config.groupId?"GROUP":"ALL",s5(e.node.config.groupId,500),!1);if(!t)throw Error("Skill sync could not be prepared");return{output:t,links:[{kind:"SKILL_RUN",resourceId:t.id,label:"Skill sync",url:`/skills/sync/${t.id}`}],wait:{kind:"SKILL_RUN",externalKey:t.id,resumeAfter:s3(e.node.config),timeoutAt:s1(e.node.config)}}}),D.register("NOTIFICATION_SEND",async e=>{let t=await (0,t1.getPrismaClient)(),r=await t.$transaction(t=>N.notifications.recordInTransaction(t,{dedupeKey:`${e.run.id}:${e.node.id}:${e.attempt.generation}`,typeKey:"WORKFLOW_MESSAGE",title:s8(e.node.config.title,"Notification title",240),body:s8(e.node.config.body,"Notification body",1e3),href:"string"==typeof e.node.config.href?e.node.config.href:`/workflows/runs/${e.run.id}`,resourceKind:"WORKFLOW_RUN",resourceId:e.run.id,worktreeId:"string"==typeof(0,st.getSessionValue)(e.sessionData,"worktree.id")?String((0,st.getSessionValue)(e.sessionData,"worktree.id")):null}));return N.notifications.created(r),{output:r}}),D.register("IOS_PUSH_SEND",async e=>({output:await N.pushNotifications.send({requestId:s7(e,"ios-push"),editor:e.node.config.editor,targetMode:s8(e.node.config.targetMode??"ALL","Push target mode",50),registrationIds:Array.isArray(e.node.config.registrationIds)?e.node.config.registrationIds.map(String):[],channelId:s5(e.node.config.channelId,500),directToken:s5(e.node.config.directToken,2e4),directTokenEncoding:"BASE64"===e.node.config.directTokenEncoding?"BASE64":"HEX",directEnvironment:"PRODUCTION"===e.node.config.directEnvironment?"PRODUCTION":"SANDBOX"})})),D.register("MCP_CALL",async e=>{let t=await N.tools.callTool({groupId:s8(e.node.config.groupId,"MCP tool group",500),name:s8(e.node.config.name,"MCP tool name",500),arguments:s6(e.node.config.arguments??{},"MCP arguments")},{caller:`workflow:${e.run.id}`,correlationId:e.attempt.id,source:"WORKFLOW"});return{output:t,sessionPatch:{steps:{[e.node.id]:{output:t}}}}}),function(e,t){let r=async(e,r,i,a,n={})=>{let s=s6(await t.tools.callTool({groupId:r,name:i,arguments:a},{caller:`workflow:${e.run.id}`,correlationId:e.attempt.id,source:"WORKFLOW"}),`${i} tool result`),o=s6(s.structuredContent,`${i} structured content`),l=n.sessionPatch?await n.sessionPatch(o):{};return{output:o,sessionPatch:{steps:{[e.node.id]:{output:o}},...l},wait:n.wait?.(o)}},i=(e,t,r,i)=>({kind:t,externalKey:r,resumeAfter:s3(e.node.config),timeoutAt:s1(e.node.config,i)}),a=(e,t,r,i)=>s9(e,t,r,i),n=e=>({projectId:a(e,"projectId","pr.projectId","GitLab project ID"),iid:Number(e.node.config.iid??(0,st.getSessionValue)(e.sessionData,"pr.iid")??(0,st.getSessionValue)(e.sessionData,"pr.number"))}),s=e=>({pr:s6(e.mergeRequest,"GitLab merge request output")});for(let[o,l]of(e.register("COMMAND_RERUN",async e=>{let t=a(e,"commandRunId","command.id","Command run ID");return r(e,"builtin:commands","rerun_command",{id:t},{sessionPatch:e=>({command:s6(e.run,"Command run output")}),wait:t=>i(e,"COMMAND_RUN",s8(s6(t.run,"Command run output").id,"Command run ID",500))})}),e.register("COMMAND_TERMINATE",async e=>{let t=a(e,"commandRunId","command.id","Command run ID");return r(e,"builtin:commands","terminate_command_run",{id:t},{sessionPatch:e=>({command:s6(e.run,"Command run output")})})}),e.register("COMMAND_READ_OUTPUT",async e=>{let t=a(e,"commandRunId","command.id","Command run ID");return r(e,"builtin:commands","get_command_run_output",{runId:t,first:Number(e.node.config.first??1e3)},{sessionPatch:e=>({command:{id:t,output:e.chunks}})})}),e.register("WORKTREE_INSPECT_DIFF",async e=>{let t=a(e,"worktreeId","worktree.id","Worktree ID");return r(e,"builtin:worktrees","inspect_worktree_diff",{worktreeId:t,scope:s8(e.node.config.scope,"Diff scope",100),path:e.node.config.path,previousPath:e.node.config.previousPath,commitSha:e.node.config.commitSha,requestId:s7(e,"diff")},{sessionPatch:e=>({worktree:{id:t,diff:e.inspection}})})}),e.register("WORKTREE_UPDATE_METADATA",async e=>{let i=a(e,"worktreeId","worktree.id","Worktree ID");return r(e,"builtin:worktrees","update_worktree_metadata",{id:i,baseBranch:e.node.config.baseBranch,highlightColor:e.node.config.highlightColor},{sessionPatch:async e=>(0,st.mergeSessionData)(await t.worktrees.workflowSessionDataForWorktree(i,{includeMissing:!0}),{worktree:s6(e.worktree,"Worktree output")})})}),e.register("WORKTREE_MOVE_CONTROL",e=>r(e,"builtin:worktrees","CANCEL"===e.node.config.operation?"cancel_worktree_move":"retry_worktree_move_with_stash",{id:s8(e.node.config.moveId,"Move ID",500)},{sessionPatch:async e=>{let r=s6(e.move,"Worktree move output"),i="string"==typeof r.targetWorktreeId&&r.targetWorktreeId||"string"==typeof r.sourceWorktreeId&&r.sourceWorktreeId||null,a=i?await t.worktrees.workflowSessionDataForWorktree(i,{includeMissing:!0}):{};return(0,st.mergeSessionData)(a,{worktree:{move:r}})}})),e.register("BUILD_REBUILD",async e=>{let t=a(e,"buildId","build.id","Build ID");return r(e,"builtin:builds","rebuild_build",{buildId:t,requestId:s7(e,"rebuild")},{sessionPatch:e=>({build:s6(e.build,"Build output")}),wait:t=>i(e,"BUILD",s8(s6(t.build,"Build output").id,"Build ID",500))})}),e.register("BUILD_GENERATE_REPORT",async e=>{let t=a(e,"buildId","build.id","Build ID");return r(e,"builtin:builds","generate_build_report",{buildId:t,kind:"TEST_RESULTS"===e.node.config.reportKind?"TEST_RESULTS":"CODE_COVERAGE",requestId:s7(e,"report")},{sessionPatch:e=>({build:{id:t,report:e.report}})})}),e.register("BUILD_DELETE",e=>{let t=Array.isArray(e.node.config.buildIds)?e.node.config.buildIds.map(String):[a(e,"buildId","build.id","Build ID")];return r(e,"builtin:builds","delete_builds",{ids:t},{sessionPatch:e=>({build:{ids:t,deletedCount:e.count}})})}),e.register("SKILL_PREPARE_SYNC",e=>r(e,"builtin:skills","prepare_skill_sync",{kind:String(e.node.config.syncKind??"ALL"),groupId:e.node.config.groupId},{sessionPatch:e=>({skillSync:s6(e.run,"Skill sync output")})})),e.register("SKILL_RESOLVE_SYNC",e=>r(e,"builtin:skills","resolve_skill_sync_conflict",{input:{runId:a(e,"runId","skillSync.id","Skill sync run ID"),itemId:s8(e.node.config.itemId,"Conflict item ID",500),resolution:String(e.node.config.resolution??"SKIP")}},{sessionPatch:e=>({skillSync:s6(e.run,"Skill sync output")})})),e.register("SKILL_SKIP_SYNC",e=>r(e,"builtin:skills","skip_skill_sync",{runId:a(e,"runId","skillSync.id","Skill sync run ID")},{sessionPatch:e=>({skillSync:s6(e.run,"Skill sync output")})})),e.register("BUILD_DATA_REFRESH",e=>r(e,"builtin:build-data","refresh_build_data",{requestId:s7(e,"build-data")},{sessionPatch:e=>({buildData:s6(e.collection,"Build-data collection output")}),wait:t=>{let r=s6(t.collection,"Build-data collection output");return"COMPLETED"===r.status?void 0:i(e,"BUILD_DATA_COLLECTION",s8(r.id,"Build-data collection ID",500),90)}})),e.register("BUILD_DATA_DELETE",e=>r(e,"builtin:build-data","delete_build_data_entries",{collectionId:a(e,"collectionId","buildData.id","Build-data collection ID"),entryIds:Array.isArray(e.node.config.entryIds)?e.node.config.entryIds.map(String):[],requestId:s7(e,"build-data-delete"),overrideProtection:!0===e.node.config.overrideProtection},{sessionPatch:e=>({buildData:s6(e.collection,"Build-data collection output")})})),e.register("BUILD_DATA_SET_LOCK",e=>{let t=a(e,"collectionId","buildData.id","Build-data collection ID");return r(e,"builtin:build-data","set_build_data_lock",{collectionId:t,entryId:s8(e.node.config.entryId,"Entry ID",500),locked:!0===e.node.config.locked},{sessionPatch:e=>({buildData:{id:t,entry:e.entry}})})}),e.register("SIGNING_REFRESH",e=>r(e,"builtin:signing-assets","refresh_signing_assets",{agentIds:Array.isArray(e.node.config.agentIds)?e.node.config.agentIds.map(String):void 0},{sessionPatch:e=>({signing:{jobs:e.operation}}),wait:t=>{let r=Array.isArray(t.operation)?t.operation.flatMap(e=>{if(!e||"object"!=typeof e||Array.isArray(e))return[];let t=e.id;return"string"==typeof t&&t?[t]:[]}):[];return r.length?i(e,"AGENT_JOBS",JSON.stringify({ids:r}),90):void 0}})),e.register("SIGNING_SYNC_PROFILE",e=>r(e,"builtin:signing-assets","sync_signing_profile",{uuid:a(e,"uuid","signingProfile.id","Profile UUID"),sourceAgentId:s8(e.node.config.sourceAgentId,"Source agent ID",500),targetAgentIds:Array.isArray(e.node.config.targetAgentIds)?e.node.config.targetAgentIds.map(String):[]},{sessionPatch:e=>({signing:{operation:e.operation}}),wait:t=>i(e,"SIGNING_OPERATIONS",JSON.stringify({ids:[s8(s6(t.operation,"Signing operation output").id,"Signing operation ID",500)]}),300)})),e.register("SIGNING_DELETE_EXPIRED",e=>r(e,"builtin:signing-assets","delete_expired_signing_profiles",{agentIds:Array.isArray(e.node.config.agentIds)?e.node.config.agentIds.map(String):void 0},{sessionPatch:e=>({signing:{operations:e.operation}}),wait:t=>{let r=Array.isArray(t.operation)?t.operation.flatMap(e=>{if(!e||"object"!=typeof e||Array.isArray(e))return[];let t=e.id;return"string"==typeof t&&t?[t]:[]}):[];return r.length?i(e,"SIGNING_OPERATIONS",JSON.stringify({ids:r}),300):void 0}})),e.register("IOS_DEVICE_REGISTER",e=>r(e,"builtin:ios-devices","register_ios_device",{id:a(e,"deviceId","device.id","Device ID")},{sessionPatch:e=>({device:s6(e.device,"iOS device output")})})),e.register("IOS_DEVICE_REJECT",e=>r(e,"builtin:ios-devices","reject_ios_device",{id:a(e,"deviceId","device.id","Device ID")},{sessionPatch:e=>({device:s6(e.device,"iOS device output")})})),e.register("AGENT_RECONCILE",async e=>{let r=Array.isArray(e.node.config.agentIds)?e.node.config.agentIds.map(String):(await t.agentControl.listAgents()).map(({id:e})=>e),i=await t.agentControl.requestCodebaseReconcile(r);return{output:{requested:i},sessionPatch:{agent:{requested:i}}}}),e.register("AGENT_UPDATE_CADENCE",async e=>{let r=await t.agentControl.updateCadenceSettings(a(e,"agentId","agent.id","Agent ID"),s6(e.node.config.settings,"Cadence settings"));return{output:r,sessionPatch:{agent:s6(r,"Agent output")}}}),e.register("CCUSAGE_COLLECT",async e=>{let r=await t.ccusage.collect(s7(e,"ccusage"));return{output:r,sessionPatch:{usage:r}}}),e.register("MODEL_COST_REFRESH",async()=>{let e=await t.modelCosts.refresh();return{output:e,sessionPatch:{modelCosts:e}}}),e.register("GITLAB_LOAD_MR",e=>r(e,"builtin:gitlab","gitlab_get_merge_request",n(e),{sessionPatch:s})),e.register("GITLAB_CREATE_MR",e=>r(e,"builtin:gitlab","gitlab_create_merge_request",{projectId:a(e,"projectId","repo.gitlabProjectId","GitLab project ID"),sourceBranch:a(e,"sourceBranch","worktree.branch","Source branch"),targetBranch:a(e,"targetBranch","worktree.baseBranch","Target branch"),title:s8(e.node.config.title??(0,st.getSessionValue)(e.sessionData,"ticket.title"),"Merge request title",500),description:s5(e.node.config.description),removeSourceBranch:!0===e.node.config.removeSourceBranch,squash:!0===e.node.config.squash,reviewerIds:Array.isArray(e.node.config.reviewerIds)?e.node.config.reviewerIds.map(String):[],labels:Array.isArray(e.node.config.labels)?e.node.config.labels.map(String):[]},{sessionPatch:s})),e.register("GITLAB_UPDATE_MR",e=>r(e,"builtin:gitlab","gitlab_update_merge_request",{...n(e),title:s5(e.node.config.title),description:s5(e.node.config.description),stateEvent:s5(e.node.config.stateEvent),reviewerIds:Array.isArray(e.node.config.reviewerIds)?e.node.config.reviewerIds.map(String):void 0,labels:Array.isArray(e.node.config.labels)?e.node.config.labels.map(String):void 0},{sessionPatch:s})),e.register("GITLAB_SUBMIT_REVIEW",e=>r(e,"builtin:gitlab","gitlab_submit_review",{...n(e),outcome:String(e.node.config.outcome??"COMMENT"),body:s5(e.node.config.body)})),e.register("GITLAB_REPLY_DISCUSSION",e=>r(e,"builtin:gitlab","gitlab_reply_discussion",{...n(e),discussionId:s8(e.node.config.discussionId,"Discussion ID",500),body:s8(e.node.config.body,"Discussion reply",1e5)})),e.register("GITLAB_SET_DISCUSSION_RESOLVED",e=>r(e,"builtin:gitlab","gitlab_set_discussion_resolved",{...n(e),discussionId:s8(e.node.config.discussionId,"Discussion ID",500),resolved:!1!==e.node.config.resolved})),e.register("GITLAB_MERGE_MR",e=>r(e,"builtin:gitlab","gitlab_merge_merge_request",{...n(e),squash:!0===e.node.config.squash,removeSourceBranch:!0===e.node.config.removeSourceBranch,autoMerge:!0===e.node.config.autoMerge,sha:s5(e.node.config.sha)},{sessionPatch:s})),[["GITLAB_SET_MR_LABELS","labels"],["GITLAB_REQUEST_REVIEWERS","reviewerIds"]]))e.register(o,e=>r(e,"builtin:gitlab","gitlab_update_merge_request",{...n(e),[l]:Array.isArray(e.node.config[l])?e.node.config[l].map(String):[]},{sessionPatch:s}));for(let[t,i,n,s]of(e.register("GITLAB_CREATE_PIPELINE",e=>r(e,"builtin:gitlab","gitlab_create_pipeline",{projectId:a(e,"projectId","repo.gitlabProjectId","GitLab project ID"),ref:a(e,"ref","worktree.branch","Git ref"),variables:Array.isArray(e.node.config.variables)?e.node.config.variables:[]},{sessionPatch:e=>({pipeline:e.pipeline})})),[["GITLAB_RETRY_PIPELINE","gitlab_retry_pipeline","pipelineId","pipeline.id"],["GITLAB_CANCEL_PIPELINE","gitlab_cancel_pipeline","pipelineId","pipeline.id"],["GITLAB_RETRY_JOB","gitlab_retry_job","jobId","job.id"]]))e.register(t,e=>r(e,"builtin:gitlab",i,{projectId:a(e,"projectId","repo.gitlabProjectId","GitLab project ID"),[n]:a(e,n,s,n)},{sessionPatch:e=>"jobId"===n?{job:e.job}:{pipeline:e.pipeline}}));e.register("GITLAB_SAVE_AUTO_RETRY",e=>r(e,"builtin:gitlab","gitlab_save_auto_retry_rule",s6(e.node.config.input,"GitLab auto-retry rule"))),e.register("GITLAB_WAIT_PIPELINE",e=>Promise.resolve({wait:{kind:"GITLAB_PIPELINE",externalKey:JSON.stringify({projectId:a(e,"projectId","repo.gitlabProjectId","GitLab project ID"),pipelineId:a(e,"pipelineId","pipeline.id","GitLab pipeline ID")}),resumeAfter:s3(e.node.config),timeoutAt:s1(e.node.config)}}));let o=async(e,t,i)=>{let a=await r(e,"builtin:github",t,i),n=s6(a.output,"GitHub tool output"),s=od(s6(n.pullRequest,"Pull request output"));return{...a,sessionPatch:{...a.sessionPatch,pr:s}}},l=e=>({owner:s8(e.node.config.owner??(0,st.getSessionValue)(e.sessionData,"repo.owner"),"Repository owner",200),name:s8(e.node.config.name??(0,st.getSessionValue)(e.sessionData,"repo.name"),"Repository name",200),number:Number(e.node.config.number??(0,st.getSessionValue)(e.sessionData,"pr.number"))});e.register("GITHUB_UPDATE_PR",e=>o(e,"update_pull_request",{...l(e),title:s5(e.node.config.title),body:"string"==typeof e.node.config.body?e.node.config.body:void 0,draft:"boolean"==typeof e.node.config.draft?e.node.config.draft:void 0})),e.register("GITHUB_SUBMIT_REVIEW",e=>o(e,"submit_pull_request_review",{...l(e),event:String(e.node.config.event??"COMMENT"),body:"string"==typeof e.node.config.body?e.node.config.body:void 0})),e.register("GITHUB_REQUEST_REVIEWERS",e=>o(e,"request_pull_request_reviewers",{...l(e),reviewers:Array.isArray(e.node.config.reviewers)?e.node.config.reviewers.map(String):[],teamReviewers:Array.isArray(e.node.config.teamReviewers)?e.node.config.teamReviewers.map(String):[]})),e.register("GITHUB_DISPATCH_WORKFLOW",e=>r(e,"builtin:github","dispatch_github_workflow",{repositoryId:a(e,"repositoryId","repo.id","Repository ID"),workflowId:s8(e.node.config.workflowId,"Workflow ID",500),ref:s8(e.node.config.ref,"Git ref",500),inputs:e.node.config.inputs?s6(e.node.config.inputs,"Workflow inputs"):void 0},{sessionPatch:e=>({pipeline:e})}));let c=async(e,t,i)=>{let a=await r(e,"builtin:jira",t,i),n=s6(a.output,"Jira tool output"),s=ou(s6(n.ticket,"Jira ticket output"));return{...a,sessionPatch:{...a.sessionPatch,ticket:s}}};e.register("JIRA_CREATE_TICKET",e=>c(e,"create_jira_ticket",{projectKey:s8(e.node.config.projectKey,"Project key",100),issueTypeId:s8(e.node.config.issueTypeId,"Issue type ID",100),summary:s8(e.node.config.summary,"Summary"),description:"string"==typeof e.node.config.description?{format:"MARKDOWN",value:e.node.config.description}:void 0,fields:e.node.config.fields?s6(e.node.config.fields,"Additional Jira fields"):void 0})),e.register("JIRA_ADD_WORKLOG",e=>c(e,"add_jira_worklog",{issueKey:a(e,"issueKey","ticket.key","Issue key"),timeSpentSeconds:Number(e.node.config.timeSpentSeconds),startedAt:s5(e.node.config.startedAt,100),comment:"string"==typeof e.node.config.comment?{format:"MARKDOWN",value:e.node.config.comment}:void 0})),e.register("JIRA_LINK_TICKETS",e=>c(e,"link_jira_tickets",{inwardIssueKey:a(e,"inwardIssueKey","ticket.key","Inward issue key"),outwardIssueKey:s8(e.node.config.outwardIssueKey,"Outward issue key",100),linkType:s8(e.node.config.linkType,"Link type",100)}))}(eh,e),(eg=new ox(L,B,eo,M,{buildData:F,commands:q,credentials:P,iosDevices:ee,polling:j,pushNotifications:V,signingAssets:K,skills:z})).start(),em.startRuntime(),ef.startRuntime(),el.startRuntime(),lr.serverServices={prismaService:O,credentialService:P,agentControlService:B,ccusageService:$,buildDataService:F,buildsService:J,codebasesService:Y,codebaseToolsService:Z,jiraService:Q,jiraWebhookService:X,iosDevicesService:ee,gitHubService:ei,gitLabService:ea,gitHubPipelineStatusService:et,gitHubActionsNotificationsService:er,cacheServerService:es,worktreesService:eo,worktreeAutomationService:ef,skillsService:z,telemetryService:G,signingAssetsService:K,pushNotificationsService:V,notificationsService:U,pollingService:j,modelCostsService:H,runsService:W,commandsService:q,diskSpaceService:M,systemStatusService:el,actionCenterService:ec,appsService:eu,globalSearchService:ed,cliHealthService:en,toolsService:ep,workflowEventsService:L,workflowsService:em,workflowEventBridge:eg})}],887394)}];
810
+ FROM visible`)]),n=a[0],s=sn(n?.totalCount),o=sn(n?.needsAttentionCount);return{rows:i,totalCount:s,needsAttentionCount:o,activeCount:s-o}}let so=["PLAN","SESSION","BUILD","WORKFLOW"],sl={questions:{orderBy:{position:"asc"},include:{options:{orderBy:{position:"asc"}}}}};function sc(e){return e.toISOString()}function su(e){try{return JSON.parse(e)}catch{return{}}}function sd(e,t,r,i){return[e,t,i??0,r.toISOString()].join(":")}function sp(e,t){return{id:e.id,sourceKind:t,createdAt:sc(e.createdAt),questions:e.questions}}function sh(e){let t=(0,si.getSessionValue)(su(e),"worktree.id");return"string"==typeof t&&t?t:null}class sm{async list(e={}){var t,r,i,a,n;let s=await (0,t1.getPrismaClient)(),o=Math.max(1,Math.min(e.first??50,200)),l=await ss(s,{first:o,cursor:function(e){if(!e)return null;try{let t=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));if("number"!=typeof t.priority||"string"!=typeof t.updatedAt||"string"!=typeof t.key)return null;return t}catch{return null}}(e.after)}),c=l.rows.slice(0,o),u=c.flatMap(e=>"PLAN"===e.resourceKind||"SESSION"===e.resourceKind?[e.resourceId]:[]),d=c.flatMap(e=>"WORKFLOW"===e.resourceKind?[e.resourceId]:[]),p=c.flatMap(e=>"BUILD"===e.resourceKind?[e.resourceId]:[]),[h,m,f]=await Promise.all([u.length?s.agentRun.findMany({where:{id:{in:u}},take:u.length,include:{worktree:!0,questionBatches:{where:{status:"PENDING"},orderBy:{createdAt:"asc"},include:sl}}}):Promise.resolve([]),d.length?s.workflowRun.findMany({where:{id:{in:d}},take:d.length,include:{workflow:!0,attempts:{where:{supersededAt:null},include:{questionBatches:{where:{status:"PENDING"},orderBy:{createdAt:"asc"},include:sl}}}}}):Promise.resolve([]),p.length?s.build.findMany({where:{id:{in:p}},take:p.length,include:{worktree:!0,codebase:{include:{repository:!0}},configuration:!0}}):Promise.resolve([])]),g=[...new Set(m.flatMap(e=>sh(e.sessionDataJson)?[sh(e.sessionDataJson)]:[]))],y=new Map((g.length?await s.worktree.findMany({where:{id:{in:g}},select:{id:!0,folder:!0,branch:!0,highlightColor:!0}}):[]).map(e=>[e.id,e])),w=new Map(c.map(e=>[e.key,e.reason])),b=[];for(let e of h){let i=`${e.kind}:${e.id}`,a=w.get(i);if(!a)continue;let n=e.questionBatches.map(e=>sp(e,null)),s="FAILED"===a?sd(e.kind,e.id,e.finishedAt??e.updatedAt):null;b.push({key:i,resourceKind:e.kind,reason:a,resourceId:e.id,href:(t=e.kind,r=e.id,`/${"PLAN"===t?"plans":"sessions"}/${encodeURIComponent(r)}`),displayNumber:e.displayNumber,label:function(e,t=220){let r=e.replace(/\s+/g," ").trim();return r.length>t?`${r.slice(0,t-1)}…`:r}(e.initialPrompt),summary:[e.repositoryName,e.branch].filter(Boolean).join(" · ")||null,status:e.status,phase:e.phase,error:e.error,createdAt:sc(e.createdAt),updatedAt:sc(e.updatedAt),worktree:e.worktree,questionBatches:"QUESTION"===a?n:[],buildRun:null,failureFingerprint:s})}for(let e of m){let t=`WORKFLOW:${e.id}`,r=w.get(t);if(!r)continue;let a=sh(e.sessionDataJson),n=e.attempts.flatMap(e=>e.questionBatches.map(t=>sp(t,e.kind))),s="FAILED"===r?sd("WORKFLOW",e.id,e.finishedAt??e.updatedAt,e.generation):null;b.push({key:t,resourceKind:"WORKFLOW",reason:r,resourceId:e.id,href:(i=e.id,`/workflows/runs/${encodeURIComponent(i)}`),displayNumber:e.displayNumber,label:e.workflow.name,summary:e.triggerSubjectKey||null,status:e.status,phase:e.phase,error:e.blockedReason??e.error,createdAt:sc(e.createdAt),updatedAt:sc(e.updatedAt),worktree:a?y.get(a)??null:null,questionBatches:"QUESTION"===r?n:[],buildRun:null,failureFingerprint:s})}for(let e of f){let t=`BUILD:${e.id}`,r=w.get(t);if(!r)continue;let i="FAILED"===r?sd("BUILD",e.id,e.finishedAt??e.updatedAt):null,n=e.codebase?.repository.name??null,s=e.configuration?.name??null;b.push({key:t,resourceKind:"BUILD",reason:r,resourceId:e.id,href:(a=e.id,`/builds/${encodeURIComponent(a)}`),displayNumber:null,label:s??n??"iOS build",summary:[n,e.worktree?.branch].filter(Boolean).join(" · ")||null,status:e.status,phase:null,error:e.error,createdAt:sc(e.createdAt),updatedAt:sc(e.updatedAt),worktree:e.worktree,questionBatches:[],buildRun:"UNRUN_BUILD"===r?{buildId:e.id,destinationType:e.destinationType,preferredDestination:su(e.destinationJson)}:null,failureFingerprint:i})}let v=new Map(b.map(e=>[e.key,e])),k=c.flatMap(e=>v.has(e.key)?[v.get(e.key)]:[]);return{items:k,nextCursor:l.rows.length>o&&k.length?(n=k[k.length-1],Buffer.from(JSON.stringify({priority:function(e){switch(e){case"QUESTION":return 0;case"BLOCKED":return 1;case"FAILED":return 2;case"UNRUN_BUILD":return 3;case"ACTIVE":return 4}}(n.reason),updatedAt:n.updatedAt,key:n.key})).toString("base64url")):null,totalCount:l.totalCount,needsAttentionCount:l.needsAttentionCount,activeCount:l.activeCount}}async acknowledge(e){let t=e.resourceKind.trim().toUpperCase();if(!so.includes(t))throw Error("Action Center resource kind is invalid");let r=await (0,t1.getPrismaClient)(),i=null;if("PLAN"===t||"SESSION"===t){let a=await r.agentRun.findUnique({where:{id:e.resourceId},select:{id:!0,kind:!0,status:!0,finishedAt:!0,updatedAt:!0}});a?.kind===t&&"FAILED"===a.status&&(i=sd(t,a.id,a.finishedAt??a.updatedAt))}else if("WORKFLOW"===t){let t=await r.workflowRun.findUnique({where:{id:e.resourceId},select:{id:!0,status:!0,generation:!0,finishedAt:!0,updatedAt:!0}});t?.status==="FAILED"&&(i=sd("WORKFLOW",t.id,t.finishedAt??t.updatedAt,t.generation))}else{let t=await r.build.findUnique({where:{id:e.resourceId},select:{id:!0,status:!0,finishedAt:!0,updatedAt:!0}});t?.status==="FAILED"&&(i=sd("BUILD",t.id,t.finishedAt??t.updatedAt))}if(!i||i!==e.failureFingerprint)throw Error("Action Center failure is no longer current");return await r.actionCenterAcknowledgement.upsert({where:{resourceKind_resourceId_failureFingerprint:{resourceKind:t,resourceId:e.resourceId,failureFingerprint:i}},create:{id:(0,b.randomUUID)(),resourceKind:t,resourceId:e.resourceId,failureFingerprint:i},update:{acknowledgedAt:new Date}}),ie.agentEventBus.publish(ie.SIDEBAR_STATUS_CHANGED_TOPIC,{sidebarStatusChanged:!0}),!0}subscribe(){return ie.agentEventBus.iterate(ie.SIDEBAR_STATUS_CHANGED_TOPIC)}}let sf="apps.changed";function sg(e){let t=e.name.trim(),r=e.description?.trim()??"",i=[...new Set(e.agentIds??[])],a=[...new Set(e.repositoryIds)];if(!t)throw Error("App name is required");if(t.length>120)throw Error("App name must be 120 characters or fewer");if(r.length>2e3)throw Error("App description must be 2,000 characters or fewer");if(!a.length)throw Error("Select at least one repository");return{name:t,normalizedName:t.normalize("NFKC").toLocaleLowerCase("en-US"),description:r,agentIds:i,repositoryIds:a}}let sy={repositories:{include:{repository:{include:{codebases:{include:{agent:!0},orderBy:[{folder:"asc"},{id:"asc"}]}}}},orderBy:{createdAt:"asc"}}};class sw{publish(e){ie.agentEventBus.publish(sf,{appsChanged:{id:e}})}subscribe(){return ie.agentEventBus.iterate(sf)}async list(){let e=await (0,t1.getPrismaClient)();return Promise.all((await e.app.findMany({include:sy,orderBy:[{name:"asc"},{id:"asc"}]})).map(e=>this.withCounts(e)))}async get(e){let t=await (0,t1.getPrismaClient)(),r=await t.app.findUnique({where:{id:e},include:sy});return r?this.withCounts(r):null}async create(e){let t=sg(e),r=await (0,t1.getPrismaClient)();await this.assertRepositories(t.repositoryIds),await this.assertUniqueName(t.normalizedName);let i=await r.app.create({data:{id:(0,b.randomUUID)(),name:t.name,normalizedName:t.normalizedName,description:t.description,agentIdsJson:JSON.stringify(t.agentIds),repositories:{create:t.repositoryIds.map(e=>({repositoryId:e}))}},include:sy});return this.publish(i.id),this.withCounts(i)}async update(e){let t=sg(e),r=await (0,t1.getPrismaClient)();if(!await r.app.findUnique({where:{id:e.id}}))throw Error("App not found");await this.assertRepositories(t.repositoryIds),await this.assertUniqueName(t.normalizedName,e.id);let i=await r.$transaction(async r=>(await r.appRepository.deleteMany({where:{appId:e.id}}),r.app.update({where:{id:e.id},data:{name:t.name,normalizedName:t.normalizedName,description:t.description,agentIdsJson:JSON.stringify(t.agentIds),repositories:{create:t.repositoryIds.map(e=>({repositoryId:e}))}},include:sy})));return this.publish(i.id),this.withCounts(i)}async delete(e){let t=await (0,t1.getPrismaClient)();if(!(await t.app.deleteMany({where:{id:e}})).count)throw Error("App not found");return this.publish(e),{id:e}}async assertRepositories(e){let t=await (0,t1.getPrismaClient)();if(await t.codebaseRepository.count({where:{id:{in:e}}})!==e.length)throw Error("One or more repositories could not be found")}async assertUniqueName(e,t){let r=await (0,t1.getPrismaClient)();if(await r.app.findFirst({where:{normalizedName:e,...t?{id:{not:t}}:{}},select:{id:!0}}))throw Error("App names must be unique")}async withCounts(e){let t=await (0,t1.getPrismaClient)(),r=e.repositories.map(e=>e.repositoryId),i={in:r},[a,n,s,o,l,c]=await Promise.all([t.codebase.count({where:{repositoryId:i}}),t.worktree.count({where:{missingAt:null,codebase:{repositoryId:i}}}),t.worktree.count({where:{missingAt:null,codebase:{repositoryId:i},OR:[{hasStagedChanges:!0},{hasUnstagedChanges:!0}]}}),t.agentRun.count({where:{kind:"PLAN",archivedAt:null,repositoryId:i}}),t.agentRun.count({where:{kind:"SESSION",archivedAt:null,repositoryId:i}}),t.build.count({where:{repositoryId:i}})]),{repositories:u,agentIdsJson:d,...p}=e;return{...p,agentIds:this.stringArray(d),repositories:u.map(e=>e.repository),counts:{repositories:r.length,codebases:a,worktrees:n,dirtyWorktrees:s,plans:o,sessions:l,builds:c}}}stringArray(e){try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}catch{return[]}}}let sb=e=>encodeURIComponent(e),sv=e=>e?.toISOString()??null;function sk(e){return e.trim().toLocaleLowerCase().replace(/\s+/g," ")}function sE(e){return sk(e).split(" ").map(e=>e.replace(/^#/,"")).filter(Boolean)}function sS(e,t,r,i=[],a=[]){let n=function(e,t,r=[],i=[]){let a=sk(e).replace(/^#/,""),n=sE(e);if(!a||0===n.length)return null;let s=sk(t),o=r.filter(e=>null!=e).map(e=>sk(String(e)).replace(/^#/,"")),l=i.filter(e=>null!=e).map(e=>sk(String(e))),c=[s,...o,...l].join(" ");return n.every(e=>c.includes(e))?o.includes(a)?1e3:s===a?900:o.some(e=>e.startsWith(a))?800:s.startsWith(a)?700:s.includes(a)?600:l.some(e=>e.startsWith(a))?500:c.includes(a)?400:300+n.filter(e=>s.includes(e)).length:null}(t,r,i,a);return null===n?null:{...e,children:e.children??[],score:n}}function sI(e){return e.filter(e=>null!==e).sort((e,t)=>e.score!==t.score?t.score-e.score:(t.updatedAt??"").localeCompare(e.updatedAt??"")||e.title.localeCompare(t.title))}function sA(e,t){return sI(e).slice(0,t)}function sx(e,t,r){let i=new Set;return sI(e).filter(e=>{let t=r(e);return!i.has(t)&&(i.add(t),!0)}).slice(0,t)}function s_(e){let{score:t,...r}=e;return r}function sC(e){return`github.com/${e.toLocaleLowerCase()}`}function sR(e){let t=e.filter(e=>!!e?.trim());return t.length?t.join(" · "):null}class sT{async search(e,t=5,r=3){let i=e.trim();if(!i)return{items:[]};if(i.length>200)throw Error("query must be at most 200 characters");if(!Number.isInteger(t)||t<1||t>10)throw Error("firstPerGroup must be an integer from 1 to 10");if(!Number.isInteger(r)||r<0||r>5)throw Error("relatedFirst must be an integer from 0 to 5");let a=await (0,t1.getPrismaClient)(),n=[...sE(i)].sort((e,t)=>t.length-e.length)[0]??i,s=Number(i.replace(/^#/,"")),o=Number.isInteger(s)&&s>=0,[l,c,u,d,p,h,m,f,g,y,w,b,v,k,E,S,I,A,x,_]=await Promise.all([a.agent.findMany({where:{OR:[{id:{contains:n}},{name:{contains:n}},{hostname:{contains:n}}]},orderBy:{updatedAt:"desc"},take:100}),a.agentJob.findMany({where:{visibility:"USER",OR:[{id:{contains:n}},{kind:{contains:n}},{status:{contains:n}},{agent:{name:{contains:n}}},{agent:{hostname:{contains:n}}}]},include:{agent:!0},orderBy:{updatedAt:"desc"},take:100}),a.codebaseRepository.findMany({where:{OR:[{id:{contains:n}},{name:{contains:n}},{description:{contains:n}},{canonicalOrigin:{contains:n}},{displayOrigin:{contains:n}}]},orderBy:{updatedAt:"desc"},take:100}),a.codebase.findMany({where:{availability:{not:"MISSING"},OR:[{id:{contains:n}},{folder:{contains:n}},{branch:{contains:n}},{observedOrigin:{contains:n}},{repository:{name:{contains:n}}},{agent:{name:{contains:n}}}]},include:{repository:!0,agent:!0},orderBy:{updatedAt:"desc"},take:100}),a.worktree.findMany({where:{missingAt:null,availability:{not:"MISSING"},OR:[{id:{contains:n}},{folder:{contains:n}},{relativePath:{contains:n}},{branch:{contains:n}},{codebase:{repository:{name:{contains:n}}}},{codebase:{agent:{name:{contains:n}}}},{pullRequest:{title:{contains:n}}},{gitLabMergeRequest:{title:{contains:n}}},...o?[{pullRequest:{number:s}}]:[],...o?[{gitLabMergeRequest:{iid:s}}]:[]]},include:{codebase:{include:{repository:!0,agent:!0}},pullRequest:!0,gitLabMergeRequest:!0},orderBy:{updatedAt:"desc"},take:100}),a.build.findMany({where:{OR:[{id:{contains:n}},{requestId:{contains:n}},{status:{contains:n}},{action:{contains:n}},{commandSummary:{contains:n}},{configuration:{name:{contains:n}}},{worktree:{branch:{contains:n}}},{worktree:{folder:{contains:n}}},{codebase:{repository:{name:{contains:n}}}}]},include:{configuration:!0,worktree:{include:{codebase:{include:{repository:!0}}}},codebase:{include:{repository:!0}}},orderBy:{updatedAt:"desc"},take:100}),a.workflow.findMany({where:{OR:[{id:{contains:n}},{name:{contains:n}},{description:{contains:n}}]},orderBy:{updatedAt:"desc"},take:100}),a.workflowRun.findMany({where:{OR:[{id:{contains:n}},...o?[{displayNumber:s}]:[],{status:{contains:n}},{triggerSubjectKey:{contains:n}},{workflow:{name:{contains:n}}}]},include:{workflow:!0},orderBy:{updatedAt:"desc"},take:100}),a.jiraCachedTicket.findMany({where:{OR:[{issueKey:{contains:n}},{projectKey:{contains:n}},{summaryJson:{contains:n}},{detailJson:{contains:n}}]},orderBy:{updatedAt:"desc"},take:100}),a.worktreePullRequest.findMany({where:{worktree:{missingAt:null},OR:[{githubId:{contains:n}},...o?[{number:s}]:[],{title:{contains:n}},{repositoryNameWithOwner:{contains:n}},{headRefName:{contains:n}},{jiraKey:{contains:n}}]},include:{worktree:!0},orderBy:{updatedAt:"desc"},take:100}),a.gitHubPipelineRecord.findMany({where:{isCurrent:!0,workflowRunId:{not:null},OR:[{githubPipelineId:{contains:n}},{workflowRunId:{contains:n}},{workflowId:{contains:n}},...o?[{runNumber:s}]:[],{name:{contains:n}},{status:{contains:n}},{snapshot:{repositoryNameWithOwner:{contains:n}}}]},include:{snapshot:!0},orderBy:{updatedAt:"desc"},take:100}),a.worktreeGitLabMergeRequest?.findMany({where:{worktree:{missingAt:null},OR:[{gitlabId:{contains:n}},...o?[{iid:s}]:[],{title:{contains:n}},{sourceBranch:{contains:n}},{projectId:{contains:n}}]},include:{worktree:!0},orderBy:{updatedAt:"desc"},take:100})??Promise.resolve([]),a.gitLabPipelineRecord?.findMany({where:{OR:[{pipelineId:{contains:n}},{ref:{contains:n}},{status:{contains:n}},{snapshot:{projectId:{contains:n}}}]},include:{snapshot:!0},orderBy:{updatedAt:"desc"},take:100})??Promise.resolve([]),a.agentRun.findMany({where:{kind:{in:["PLAN","SESSION"]},OR:[{id:{contains:n}},...o?[{displayNumber:s}]:[],{initialPrompt:{contains:n}},{repositoryName:{contains:n}},{branch:{contains:n}},{jiraIssueKey:{contains:n}},{model:{contains:n}},{status:{contains:n}}]},orderBy:{updatedAt:"desc"},take:100}),a.commandDefinition.findMany({where:{OR:[{id:{contains:n}},{name:{contains:n}},{description:{contains:n}},{script:{contains:n}}]},orderBy:{updatedAt:"desc"},take:100}),a.commandRun.findMany({where:{OR:[{id:{contains:n}},...o?[{displayNumber:s}]:[],{snapshotName:{contains:n}},{snapshotDescription:{contains:n}},{agentName:{contains:n}},{worktreeBranch:{contains:n}},{status:{contains:n}}]},orderBy:{updatedAt:"desc"},take:100}),a.skill.findMany({where:{deletedAt:null,OR:[{id:{contains:n}},{name:{contains:n}},{description:{contains:n}}]},orderBy:{updatedAt:"desc"},take:100}),a.skillGroup.findMany({where:{OR:[{id:{contains:n}},{name:{contains:n}}]},orderBy:{updatedAt:"desc"},take:100}),a.iosDevice.findMany({where:{OR:[{id:{contains:n}},{udid:{contains:n}},{displayName:{contains:n}},{product:{contains:n}},{osVersion:{contains:n}},{status:{contains:n}}]},orderBy:{updatedAt:"desc"},take:100}),a.signingProfileAsset.findMany({where:{missingAt:null,OR:[{id:{contains:n}},{uuid:{contains:n}},{name:{contains:n}},{bundleId:{contains:n}},{teamName:{contains:n}},{profileType:{contains:n}}]},include:{agent:!0},orderBy:{observedAt:"desc"},take:100})]),C=[...new Set(w.map(e=>sC(e.snapshot.repositoryNameWithOwner)))],R=new Map([...u,...C.length?await a.codebaseRepository.findMany({where:{canonicalOrigin:{in:C}}}):[]].map(e=>[e.canonicalOrigin.toLocaleLowerCase(),e])),T=sA(p.map(e=>sS({key:`worktree:${e.id}`,kind:"WORKTREE",group:"WORKTREES",title:e.branch??e.relativePath,subtitle:sR([e.codebase.repository.name,e.relativePath,e.codebase.agent.name]),href:`/worktrees/${sb(e.id)}`,status:e.availability,updatedAt:sv(e.updatedAt)},i,e.branch??e.relativePath,[e.id,e.branch,e.pullRequest?.number],[e.folder,e.relativePath,e.codebase.repository.name,e.codebase.agent.name,e.pullRequest?.title,e.gitLabMergeRequest?.title])),t),D=sA(m.map(e=>sS({key:`workflow:${e.id}`,kind:"WORKFLOW",group:"WORKFLOWS",title:e.name,subtitle:e.description||null,href:`/workflows/${sb(e.id)}`,status:e.archivedAt?"ARCHIVED":e.enabled?"ENABLED":"DISABLED",updatedAt:sv(e.updatedAt)},i,e.name,[e.id],[e.description])),t);r>0&&(await this.attachWorktreeChildren(T,r),await this.attachWorkflowChildren(D,r));let N=new Set([...T,...D].flatMap(e=>e.children.map(e=>e.key))),O=sA(g.map(e=>{let t,r,a,n=(a=(r=(t=function(e){if(!e)return{};try{let t=JSON.parse(e);return t&&"object"==typeof t&&!Array.isArray(t)?t:{}}catch{return{}}}(e.detailJson??e.summaryJson)).fields&&"object"==typeof t.fields&&!Array.isArray(t.fields)?t.fields:{}).status&&"object"==typeof r.status&&!Array.isArray(r.status)?r.status:{},{summary:"string"==typeof r.summary?r.summary:null,status:"string"==typeof a.name?a.name:null});return sS({key:`ticket:${e.issueKey}`,kind:"JIRA_TICKET",group:"TICKETS",title:n.summary?`${e.issueKey} \xb7 ${n.summary}`:e.issueKey,subtitle:e.projectKey,href:`/jira/tickets/${sb(e.issueKey)}`,status:n.status,updatedAt:sv(e.updatedAt)},i,n.summary??e.issueKey,[e.issueKey],[e.projectKey,n.status])}),t),P=sx(y.map(e=>{let[t,...r]=e.repositoryNameWithOwner.split("/"),a=r.join("/");return t&&a?sS({key:`pull-request:${e.repositoryNameWithOwner}:${e.number}`,kind:"GITHUB_PULL_REQUEST",group:"PULL_REQUESTS",title:`${e.repositoryNameWithOwner} #${e.number} \xb7 ${e.title}`,subtitle:sR([e.headRefName,e.jiraKey]),href:`/pull-requests/${sb(t)}/${sb(a)}/${e.number}`,status:e.state,updatedAt:sv(e.updatedAt)},i,e.title,[e.number,`#${e.number}`,e.githubId,e.jiraKey],[e.repositoryNameWithOwner,e.headRefName]):null}),t,e=>e.key.toLocaleLowerCase()),L=sx(b.map(e=>sS({key:`gitlab-merge-request:${e.projectId}:${e.iid}`,kind:"GITLAB_MERGE_REQUEST",group:"PULL_REQUESTS",title:`!${e.iid} \xb7 ${e.title}`,subtitle:e.sourceBranch,href:`/gitlab/merge-requests/${sb(e.projectId)}/${e.iid}`,status:e.state,updatedAt:sv(e.updatedAt)},i,e.title,[e.iid,`!${e.iid}`,e.gitlabId],[e.projectId,e.sourceBranch])),t,e=>e.key.toLocaleLowerCase()),B=sA(u.map(e=>sS({key:`repository:${e.id}`,kind:"REPOSITORY",group:"REPOSITORIES",title:e.name,subtitle:e.displayOrigin,href:`/codebases/repositories/${sb(e.id)}`,status:null,updatedAt:sv(e.updatedAt)},i,e.name,[e.id],[e.displayOrigin,e.canonicalOrigin,e.description])),t),U=sA(d.map(e=>sS({key:`codebase:${e.id}`,kind:"CODEBASE",group:"CODEBASES",title:e.folder,subtitle:sR([e.repository.name,e.branch,e.agent.name]),href:`/codebases/${sb(e.id)}`,status:e.availability,updatedAt:sv(e.updatedAt)},i,e.folder,[e.id,e.branch],[e.observedOrigin,e.repository.name,e.agent.name])),t),j=sA(f.map(e=>sS({key:`workflow-run:${e.id}`,kind:"WORKFLOW_RUN",group:"WORKFLOWS",title:`${e.workflow.name} #${e.displayNumber}`,subtitle:e.triggerSubjectKey||null,href:`/workflows/runs/${sb(e.id)}`,status:e.status,updatedAt:sv(e.updatedAt)},i,e.workflow.name,[e.id,e.displayNumber,`#${e.displayNumber}`],[e.status,e.triggerSubjectKey])).filter(e=>!e||!N.has(e.key)),t),M=sA(w.map(e=>{let t=R.get(sC(e.snapshot.repositoryNameWithOwner)),r=new URLSearchParams;return t&&r.set("repository",t.id),e.workflowId&&r.set("pipeline",e.workflowId),sS({key:`github-actions:${e.id}`,kind:"GITHUB_ACTIONS_RUN",group:"GITHUB_ACTIONS",title:`${e.name}${e.runNumber?` #${e.runNumber}`:""}`,subtitle:e.snapshot.repositoryNameWithOwner,href:`/actions${r.size?`?${r.toString()}`:""}`,status:e.status,updatedAt:sv(e.updatedAt)},i,e.name,[e.githubPipelineId,e.workflowRunId,e.workflowId,e.runNumber],[e.snapshot.repositoryNameWithOwner,e.status])}),t),q=sA(v.map(e=>sS({key:`gitlab-pipeline:${e.snapshot.projectId}:${e.pipelineId}`,kind:"GITLAB_PIPELINE",group:"GITLAB_PIPELINES",title:`Pipeline #${e.pipelineId}`,subtitle:e.ref,href:`/gitlab/pipelines?project=${sb(e.snapshot.projectId)}&pipeline=${sb(e.pipelineId)}`,status:e.status,updatedAt:sv(e.updatedAt)},i,`Pipeline #${e.pipelineId}`,[e.pipelineId],[e.snapshot.projectId,e.ref,e.status])),t),$=sA(h.map(e=>{let t=e.worktree?.codebase.repository??e.codebase?.repository;return sS({key:`build:${e.id}`,kind:"BUILD",group:"BUILDS",title:e.configuration?.name??`${e.action} build`,subtitle:sR([t?.name,e.worktree?.branch,e.id.slice(0,8)]),href:`/builds/${sb(e.id)}`,status:e.status,updatedAt:sv(e.updatedAt)},i,e.configuration?.name??`${e.action} build`,[e.id,e.requestId],[e.action,e.status,e.commandSummary,t?.name,e.worktree?.branch,e.worktree?.folder])}).filter(e=>!e||!N.has(e.key)),t),F=sA(l.map(e=>sS({key:`agent:${e.id}`,kind:"AGENT",group:"AGENTS_JOBS",title:e.name,subtitle:e.hostname,href:`/agents/${sb(e.id)}`,status:e.disconnectedAt?"OFFLINE":null,updatedAt:sv(e.updatedAt)},i,e.name,[e.id],[e.hostname])),t),G=sA(c.map(e=>sS({key:`agent-job:${e.id}`,kind:"AGENT_JOB",group:"AGENTS_JOBS",title:e.kind,subtitle:sR([e.agent.name,e.id.slice(0,8)]),href:`/jobs/${sb(e.id)}`,status:e.status,updatedAt:sv(e.updatedAt)},i,e.kind,[e.id],[e.status,e.agent.name,e.agent.hostname])),t),K=sA(k.map(e=>{let t="PLAN"===e.kind?"PLAN":"SESSION";return sS({key:`${t.toLocaleLowerCase()}:${e.id}`,kind:t,group:"PLANS_SESSIONS",title:`${"PLAN"===t?"Plan":"Session"} #${e.displayNumber}`,subtitle:sR([e.repositoryName,e.branch,e.initialPrompt.slice(0,100)]),href:`/${"PLAN"===t?"plans":"sessions"}/${sb(e.id)}`,status:e.status,updatedAt:sv(e.updatedAt)},i,e.initialPrompt,[e.id,e.displayNumber,`#${e.displayNumber}`,e.jiraIssueKey],[e.repositoryName,e.branch,e.model,e.status])}),t),H=sA(E.map(e=>sS({key:`command:${e.id}`,kind:"COMMAND",group:"COMMANDS_RUNS",title:e.name,subtitle:e.description||null,href:`/commands/${sb(e.id)}/edit`,status:e.archivedAt?"ARCHIVED":null,updatedAt:sv(e.updatedAt)},i,e.name,[e.id],[e.description,e.script])),t),V=sA(S.map(e=>sS({key:`command-run:${e.id}`,kind:"COMMAND_RUN",group:"COMMANDS_RUNS",title:`${e.snapshotName} #${e.displayNumber}`,subtitle:sR([e.agentName,e.worktreeBranch]),href:`/commands/runs/${sb(e.id)}`,status:e.status,updatedAt:sv(e.updatedAt)},i,e.snapshotName,[e.id,e.displayNumber,`#${e.displayNumber}`],[e.snapshotDescription,e.agentName,e.worktreeBranch,e.status])),t),W=sA(I.map(e=>sS({key:`skill:${e.id}`,kind:"SKILL",group:"SKILLS",title:e.name,subtitle:e.description,href:`/skills/${sb(e.id)}`,status:null,updatedAt:sv(e.updatedAt)},i,e.name,[e.id],[e.description])),t),J=sA(A.map(e=>sS({key:`skill-group:${e.id}`,kind:"SKILL_GROUP",group:"SKILLS",title:e.name,subtitle:null,href:`/skills/groups/${sb(e.id)}`,status:null,updatedAt:sv(e.updatedAt)},i,e.name,[e.id])),t),z=sA(x.map(e=>sS({key:`device:${e.id}`,kind:"DEVICE",group:"DEVICES_PROFILES",title:e.displayName,subtitle:sR([e.product,e.osVersion]),href:`/devices/${sb(e.id)}`,status:e.status,updatedAt:sv(e.updatedAt)},i,e.displayName,[e.id,e.udid],[e.product,e.osVersion,e.status])),t),Y=sA(_.map(e=>sS({key:`profile:${e.id}`,kind:"PROVISIONING_PROFILE",group:"DEVICES_PROFILES",title:e.name,subtitle:sR([e.bundleId,e.teamName,e.agent.name]),href:`/provisioning-profiles/${sb(e.id)}`,status:e.expired?"EXPIRED":e.profileType,updatedAt:sv(e.observedAt)},i,e.name,[e.id,e.uuid],[e.bundleId,e.teamName,e.profileType,e.agent.name])),t);return{items:[...T,...O,...P,...L,...B,...U,...sA([...D,...j],t),...M,...q,...$,...sA([...F,...G],t),...K,...sA([...H,...V],t),...sA([...W,...J],t),...sA([...z,...Y],t)].map(s_)}}async attachWorktreeChildren(e,t){if(!e.length)return;let r=await (0,t1.getPrismaClient)(),i=e.map(e=>e.key.slice(9)),a=new Map(await Promise.all(i.map(async e=>{let[i,a]=await Promise.all([r.workflowRun.findMany({where:{resourceLinks:{some:{kind:"WORKTREE",resourceId:e}}},include:{workflow:!0},orderBy:{createdAt:"desc"},take:t}),r.build.findMany({where:{worktreeId:e},include:{configuration:!0},orderBy:{createdAt:"desc"},take:t})]);return[e,{runs:i,builds:a}]})));for(let r of e){let e=r.key.slice(9),i=a.get(e);r.children=[...(i?.runs??[]).slice(0,t).map(e=>({key:`workflow-run:${e.id}`,kind:"WORKFLOW_RUN",group:"WORKFLOWS",title:`${e.workflow.name} #${e.displayNumber}`,subtitle:null,href:`/workflows/runs/${sb(e.id)}`,status:e.status,updatedAt:sv(e.updatedAt),children:[]})),...(i?.builds??[]).slice(0,t).map(e=>({key:`build:${e.id}`,kind:"BUILD",group:"BUILDS",title:e.configuration?.name??`${e.action} build`,subtitle:e.id.slice(0,8),href:`/builds/${sb(e.id)}`,status:e.status,updatedAt:sv(e.updatedAt),children:[]}))]}}async attachWorkflowChildren(e,t){if(!e.length)return;let r=await (0,t1.getPrismaClient)(),i=e.map(e=>e.key.slice(9)),a=new Map(await Promise.all(i.map(async e=>[e,await r.workflowRun.findMany({where:{workflowId:e},include:{workflow:!0},orderBy:{createdAt:"desc"},take:t})])));for(let r of e){let e=r.key.slice(9);r.children=(a.get(e)??[]).slice(0,t).map(e=>({key:`workflow-run:${e.id}`,kind:"WORKFLOW_RUN",group:"WORKFLOWS",title:`${e.workflow.name} #${e.displayNumber}`,subtitle:e.triggerSubjectKey||null,href:`/workflows/runs/${sb(e.id)}`,status:e.status,updatedAt:sv(e.updatedAt),children:[]}))}}}var sD=e.i(642582),sN=e.i(524214),sO=e.i(169349);let sP="default",sL=["QUEUED","RUNNING","CANCELLING"],sB=[{id:"builtin-acli-jira",name:"Atlassian Jira",command:"acli jira auth status",builtIn:!0},{id:"builtin-acli",name:"Atlassian CLI",command:"acli auth status",builtIn:!0},{id:"builtin-claude",name:"Claude",command:"claude auth status",builtIn:!0},{id:"builtin-codex",name:"Codex",command:"codex login status",builtIn:!0},{id:"builtin-opencode",name:"OpenCode",command:"opencode auth list",builtIn:!0}],sU={id:"builtin-github",name:"GitHub",command:"gh auth status",builtIn:!0},sj={id:"builtin-gitlab",name:"GitLab",command:"glab auth status",builtIn:!0};function sM(e){try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}catch{return[]}}function sq(e){return!!(e.lastSeenAt&&Date.now()-e.lastSeenAt.getTime()<=(0,a.agentOnlineWindowMs)(e)&&null===e.disconnectedAt)}class s${agentControl;gitHub;gitLab;startingAgents;constructor(e,t,r){this.agentControl=e,this.gitHub=t,this.gitLab=r,this.startingAgents=new Set,this.agentControl.registerCompletionObserver(async e=>{e.kind===sD.CLI_HEALTH_JOB_KIND&&this.publish(e.agentId)})}publish(e){ie.agentEventBus.publish(ie.CLI_HEALTH_CHANGED_TOPIC,{cliHealthStatusChanged:{agentId:e}})}async customChecks(){let e=await (0,t1.getPrismaClient)(),t=await e.cliHealthSettings.findUnique({where:{id:sP}});var r=t?.checksJson;try{let e=JSON.parse(r||"[]");if(!Array.isArray(e))return[];return e.filter(e=>!!(e&&"object"==typeof e&&"string"==typeof e.id&&"string"==typeof e.name&&"string"==typeof e.command&&"boolean"==typeof e.enabled))}catch{return[]}}async definitions(){let[e,t,r]=await Promise.all([this.customChecks(),this.gitHub.getSettings(),this.gitLab.getSettings()]);return{checks:[...sB,...t.tokenConfigured?[sU]:[],...r.configured?[sj]:[],...e.filter(e=>e.enabled).map(({enabled:e,...t})=>({...t,builtIn:!1}))],customChecks:e}}resultViews(e,t){let r=new Map((t?.checks??[]).map(e=>[e.id,e]));return e.map(e=>{let t=r.get(e.id);return t&&t.command===e.command?{...t,...e,state:0!==t.exitCode||t.timedOut||t.launchError?"UNHEALTHY":"HEALTHY"}:{...e,state:"NOT_RUN",exitCode:null,stdout:"",stderr:"",durationMs:null,checkedAt:null,timedOut:!1,launchError:null,outputTruncated:!1}})}async agentStatus(e,t){let r=await (0,t1.getPrismaClient)(),i=t??(await this.definitions()).checks,[a,n]=await Promise.all([r.agentJob.findFirst({where:{agentId:e.id,kind:sD.CLI_HEALTH_JOB_KIND,status:{in:sL}},orderBy:{createdAt:"desc"}}),r.agentJob.findFirst({where:{agentId:e.id,kind:sD.CLI_HEALTH_JOB_KIND,status:"SUCCEEDED"},orderBy:{finishedAt:"desc"}})]),s=sM(e.capabilitiesJson).includes(sD.CLI_HEALTH_JOB_KIND),o=this.resultViews(i,function(e){if(!e)return null;try{let t=JSON.parse(e);return Array.isArray(t.checks)?t:null}catch{return null}}(n?.resultJson??null)),l=o.filter(e=>"NOT_RUN"!==e.state),c=s?a?"RUNNING":0===l.length?"NOT_CHECKED":l.length===o.length&&l.every(e=>"HEALTHY"===e.state)?"HEALTHY":"ISSUES":"UNSUPPORTED";return{agentId:e.id,name:e.name,hostname:e.hostname,version:e.version,connectionStatus:sq(e)?"ONLINE":"OFFLINE",supported:s,activeJobId:a?.id??null,lastCheckedAt:n?.finishedAt?.toISOString()??null,overall:c,results:o}}async installationStatus(){let[{checks:e,customChecks:t},r]=await Promise.all([this.definitions(),this.agentControl.listAgents()]);return{version:process.env.AIDE_VERSION||sN.default.version,dependencies:[{name:"Next.js",version:sN.default.dependencies.next},{name:"Claude SDK",version:sO.default.dependencies["@anthropic-ai/claude-agent-sdk"]},{name:"Codex SDK",version:sO.default.dependencies["@openai/codex-sdk"]},{name:"OpenCode SDK",version:sO.default.dependencies["@opencode-ai/sdk"]}],customChecks:t,agents:await Promise.all(r.map(t=>this.agentStatus(t,e)))}}async statusForAgent(e){let t=await this.agentControl.getAgent(e);if(!t)throw Error("Agent not found");return this.agentStatus(t)}async run(e){let[{checks:t},r]=await Promise.all([this.definitions(),this.agentControl.listAgents()]),i=e?r.filter(t=>t.id===e):r;if(e&&0===i.length)throw Error("Agent not found");let a=i.filter(e=>sq(e)&&sM(e.capabilitiesJson).includes(sD.CLI_HEALTH_JOB_KIND));return await Promise.all(a.map(async e=>{if(!this.startingAgents.has(e.id)){this.startingAgents.add(e.id);try{if((await this.agentStatus(e,t)).activeJobId)return;await this.agentControl.createJob({agentId:e.id,kind:sD.CLI_HEALTH_JOB_KIND,payload:{checks:t},idempotencyKey:`cli-health:${(0,b.randomUUID)()}`,timeoutSeconds:600,visibility:"SYSTEM"}),this.publish(e.id)}finally{this.startingAgents.delete(e.id)}}})),this.installationStatus()}async saveSettings(e){let t=function(e){if(e.length>20)throw Error("At most 20 custom CLI health checks are allowed");let t=new Set,r=new Set;return e.map(e=>{let i=e.name?.trim()??"",a=e.command?.trim()??"",n=e.id?.trim()||(0,b.randomUUID)();if(!i||i.length>100||i.includes("\0"))throw Error("Check names must be between 1 and 100 characters and cannot contain NUL characters");if(!a||a.length>4096||a.includes("\0"))throw Error("Check commands must be between 1 and 4096 characters and cannot contain NUL characters");let s=i.toLocaleLowerCase();if(t.has(s))throw Error("Custom check names must be unique");if(n.length>100||n.includes("\0")||n.startsWith("builtin-")||r.has(n))throw Error("Custom check identifiers must be unique and valid");return t.add(s),r.add(n),{id:n,name:i,command:a,enabled:!1!==e.enabled}})}(e),r=await (0,t1.getPrismaClient)();return await r.cliHealthSettings.upsert({where:{id:sP},create:{id:sP,checksJson:JSON.stringify(t)},update:{checksJson:JSON.stringify(t)}}),this.publish(null),this.installationStatus()}}function sF(e,t,r){let i=e.trim().toLowerCase(),a=t.trim().toLowerCase();if(!i||!a)throw Error("Pull request repository coordinates are required");if(!Number.isInteger(r)||r<1)throw Error("Pull request number must be a positive integer");return`${i}/${a}#${r}`}function sG(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}function sK(e,t,r){return sG(e[t])[r]}function sH(e,t,r={}){if("string"!=typeof t&&"number"!=typeof t)return null;let i=String(t).trim();return i?{kind:e,resourceId:i,...r}:null}let sV=new Set(["JIRA_STATUS","JIRA_LABEL","JIRA_ASSIGNED_SELF","JIRA_SOURCE_NEW_TICKET","JIRA_MENTION","JIRA_SPRINT_STARTED","JIRA_TICKET_UPDATED","JIRA_COMMENT_ADDED","JIRA_WORKLOG_ADDED","JIRA_SPRINT_ENDED","JIRA_ISSUE_CREATED","JIRA_ISSUE_DELETED","JIRA_ISSUE_COMMAND","JIRA_ATTACHMENT_ADDED","JIRA_ISSUE_LINKED"]),sW=new Set(["RUN_STARTED","RUN_COMPLETED","RUN_QUESTION_NEEDED","RUN_QUESTION_ANSWERED","RUN_PAUSED","RUN_CONTINUED","RUN_FAILED","RUN_CANCELLED","RUN_PLAN_PLAYED","RUN_FOLLOW_UP","RUN_IMPORTED","RUN_USAGE_THRESHOLD","RUN_EVENT_MATCH"]),sJ=new Set(["BUILD_RESULT","BUILD_TEST_THRESHOLD","BUILD_COVERAGE_THRESHOLD","BUILD_HOOK_FAILED"]),sz=new Set(["WORKTREE_CREATED","WORKTREE_BEHIND","WORKTREE_CONFLICT","WORKTREE_MISSING","WORKTREE_DIVERGED","WORKTREE_DIRTY_DURATION","WORKTREE_NEW_COMMIT","WORKTREE_SYNC_STATE_CHANGED","WORKTREE_AUTOMATION_RESULT","WORKTREE_CLEAN"]),sY=new Set(["GITHUB_PR_STATE","GITHUB_REVIEW_CHANGES_REQUESTED","GITHUB_REVIEW_COMMENT","GITHUB_PR_CLOSED","GITHUB_ISSUE_COMMAND","GITHUB_PR_LABEL","GITHUB_PR_SYNCHRONIZED","GITHUB_REVIEW_APPROVED","GITLAB_MR_STATE","GITLAB_REVIEW_CHANGES_REQUESTED","GITLAB_REVIEW_COMMENT","GITLAB_MR_CLOSED","GITLAB_NOTE_COMMAND","GITLAB_MR_LABEL","GITLAB_MR_SYNCHRONIZED","GITLAB_REVIEW_APPROVED"]),sZ=new Set(["GITHUB_CHECK_FAILED","GITHUB_WORKFLOW_SUCCEEDED","GITHUB_ACTIONS_RESULT","GITHUB_PIPELINE_STATUS_CHANGED","GITLAB_PIPELINE_FAILED","GITLAB_PIPELINE_SUCCEEDED","GITLAB_PIPELINE_RESULT","GITLAB_PIPELINE_STATUS_CHANGED","GITLAB_JOB_STATUS_CHANGED"]);var sQ=e.i(361617),sX=e.i(483291);let s0=["","aa"," ","a a","a\na"," a","a "];function s1(e,t=!1){(0,sQ.validateCommandOutputPattern)(e);try{let r=(0,sX.compileRe2)(e,{flags:t?"g":"",label:"Output pattern"});for(let t of s0){let r=(0,sX.compileRe2)(e,{flags:"y",label:"Output pattern"});for(let e=0;e<=t.length;e+=1){r.lastIndex=e;let i=r.exec(t);if(i?.index===e&&i[0]?.length===0)throw Error("Output pattern must consume at least one character")}}return r}catch(e){if(e instanceof Error&&"Output pattern must consume at least one character"===e.message||e instanceof Error)throw e;throw Error(`Output pattern is not valid RE2 syntax: ${String(e)}`)}}function s2(e,t){let r="string"==typeof e?Number(e.trim()):e;return"number"!=typeof r||!Number.isFinite(r)||r<=0?null:Math.min(31536e3,Math.max(t,r))}function s3(e,t=null){let r=s2(e.timeoutSeconds,10)??(null===t?null:s2(t,10));return null===r?null:new Date(Date.now()+1e3*r)}function s4(e,t){return s2(e.cadenceSeconds,1)??Math.max(1,t)}function s6(e,t=1){return new Date(Date.now()+1e3*s4(e,t))}function s8(e){return e.toLowerCase().replaceAll("_"," ")}let s5=(e,t)=>{if(!e||"object"!=typeof e||Array.isArray(e))throw Error(`${t} must be an object`);return e},s9=(e,t,r=2e4)=>{if("string"!=typeof e||!e.trim())throw Error(`${t} is required`);if(e.length>r)throw Error(`${t} is too long`);return e.trim()},s7=(e,t=2e4)=>null==e||""===e?null:s9(e,"Value",t),oe=(e,t,r,i)=>s9(e.node.config[t]??(0,si.getSessionValue)(e.sessionData,r),i,500),ot=(e,t="operation")=>`${e.run.id}:${e.attempt.id}:${t}`,or=(e,t,r=!1)=>({output:t,sessionPatch:{run:{[e.node.id]:t}},links:"string"==typeof t.id?[{kind:"AGENT_RUN",resourceId:t.id,label:"string"==typeof t.kind?t.kind:"Agent run",url:`/${"PLAN"===t.kind?"plans":"sessions"}/${t.id}`,metadata:{runKind:t.kind}}]:void 0,wait:r&&"string"==typeof t.id?{kind:"AGENT_RUN",externalKey:t.id,resumeAfter:s6(e.node.config),timeoutAt:s3(e.node.config)}:void 0}),oi=(e,t,r,i=[])=>({output:{jobId:t.id},sessionPatch:r,links:[...i,{kind:"AGENT_JOB",resourceId:t.id,label:"Agent job",url:`/jobs/${t.id}`}],wait:{kind:"AGENT_JOB",externalKey:t.id,resumeAfter:s6(e.node.config),timeoutAt:s3(e.node.config,t.timeoutSeconds??3600)}}),oa=(e,t,r,i,a)=>({kind:e,resourceId:t,label:r,url:i,metadata:a}),on=(e,t)=>oa("JIRA_TICKET",e,t??e);function os(e,t,r){let i=od(e);return oa("PULL_REQUEST",sF(i.owner,i.name,og(e)),t??"Pull request",r)}function oo(e){let t=ou(e),r=of(e);return t&&r?oa("PULL_REQUEST",sF(t.owner,t.name,r),"Pull request"):null}function ol(e){let t=e.node.config.workflowRunId??(0,si.getSessionValue)(e.sessionData,"pipeline.runId"),r=(0,si.getSessionValue)(e.sessionData,"pipeline.url");return("string"==typeof t||"number"==typeof t)&&"string"==typeof r&&r?oa("GITHUB_WORKFLOW_RUN",String(t),"Workflow run",r):null}function oc(e){let t=(0,si.getSessionValue)(e.sessionData,"run.kind");if("PLAN"!==t&&"SESSION"!==t)return null;let r=function(e){try{return oE(e)}catch{return null}}(e);return r?oa("AGENT_RUN",r,t,`/${"PLAN"===t?"plans":"sessions"}/${r}`,{runKind:t}):null}function ou(e){let t=e.node.config.owner,r=e.node.config.name;if("string"==typeof t&&t.trim()&&"string"==typeof r&&r.trim())return{owner:t.trim(),name:r.trim()};let i=e.sessionData.repo&&"object"==typeof e.sessionData.repo&&!Array.isArray(e.sessionData.repo)?e.sessionData.repo.displayOrigin:null,a="string"==typeof i?i.match(/(?:https?:\/\/)?github\.com[/:]([^/]+)\/([^/.]+)(?:\.git)?$/i):null,n=a?.[1]?.trim(),s=a?.[2]?.trim();return n&&s?{owner:n,name:s}:null}function od(e){let t=ou(e);if(!t)throw Error("GitHub owner and repository are required");return t}function op(e){let t=s5(e,"Jira ticket"),r=t.issueType&&"object"==typeof t.issueType?t.issueType:{},i=t.status&&"object"==typeof t.status?t.status:{};return{...t,key:t.key,title:t.summary??t.title,type:r.name??t.type,status:i.name??t.status,statusCategory:i.category??t.statusCategory}}function oh(e){let t=s5(e,"Pull request"),r=Array.isArray(t.reviewThreads)?t.reviewThreads:[];return{...t,headBranch:t.headRefName,headSha:t.headRefOid,merged:"MERGED"===t.state,unresolvedThreads:r.filter(e=>e&&"object"==typeof e&&!Array.isArray(e)&&!0!==e.isResolved)}}function om(e){return s9(e.node.config.issueKey??(0,si.getSessionValue)(e.sessionData,"ticket.key"),"Jira issue key",100)}function of(e){let t=e.node.config.number??(0,si.getSessionValue)(e.sessionData,"pr.number"),r="string"==typeof t?Number(t):t;return"number"==typeof r&&Number.isInteger(r)&&r>=1?r:null}function og(e){let t=of(e);if(!t)throw Error("Pull request number is required");return t}function oy(e){return oe(e,"worktreeId","worktree.id","Worktree ID")}function ow(e){return oe(e,"codebaseId","codebase.id","Codebase ID")}function ob(e){let t=String(e.node.config.mode??"NEW").toUpperCase();if(!new Set(["NEW","EXISTING","TICKET"]).has(t))throw Error("Worktree branch mode must be NEW, EXISTING, or TICKET");return{mode:t,branchName:"TICKET"===t?null:s7(e.node.config.branchName??(0,si.getSessionValue)(e.sessionData,"worktree.branch"),500),ticketKey:"TICKET"===t?s7(e.node.config.ticketKey??(0,si.getSessionValue)(e.sessionData,"ticket.key"),100):null,baseBranch:s9(e.node.config.baseBranch??(0,si.getSessionValue)(e.sessionData,"worktree.baseBranch")??(0,si.getSessionValue)(e.sessionData,"repo.defaultBranch"),"Base branch",500)}}function ov(e){return oe(e,"buildId","build.id","Build ID")}function ok(e){return s9(e.node.config.agentId??(0,si.getSessionValue)(e.sessionData,"agent.id")??(0,si.getSessionValue)(e.sessionData,"codebase.agentId"),"Agent ID",500)}function oE(e){let t=e.node.config.runId;if("string"==typeof t&&t)return t;let r=e.node.config.sourceStepId;return"string"==typeof r?s9((0,si.getSessionValue)(e.sessionData,`run.${r}.id`),"Agent run ID",500):s9((0,si.getSessionValue)(e.sessionData,"run.id"),"Agent run ID",500)}function oS(e,t){let r,i,a=e.node.config.worktreeConcurrencyLimit;return{kind:t,worktreeId:(r=e.node.config.worktreeId,i=(0,si.getSessionValue)(e.sessionData,"worktree.id"),"string"==typeof r&&r===e.run.workflowId&&"string"==typeof i&&i!==r?s9(i,"Worktree ID",500):oy(e)),jiraIssueKey:s7(e.node.config.jiraIssueKey??(0,si.getSessionValue)(e.sessionData,"ticket.key"),100),provider:s9(e.node.config.provider??"CODEX","Provider",50),model:s9(e.node.config.model,"Model",200),effort:s7(e.node.config.effort,50),webSearchEnabled:!0===e.node.config.webSearchEnabled,prompt:s9(e.node.config.prompt,"Prompt",2e5),attachmentIds:Array.isArray(e.node.config.attachmentIds)?e.node.config.attachmentIds.map(String):[],mcpPresetIds:Array.isArray(e.node.config.mcpPresetIds)?e.node.config.mcpPresetIds.map(String):[],worktreeConcurrencyLimit:"number"==typeof a?a:void 0,workflowRunId:e.run.id}}class oI{nextMaintenanceAt=0;async record(e){let t=await (0,t1.getPrismaClient)();return await t.workflowTrigger.findFirst({where:{kind:e.kind,version:{activeFor:{is:{enabled:!0,archivedAt:null}}}},select:{id:!0}})?this.recordInTransaction(t,e):null}async recordInTransaction(e,t){let r=await e.workflowTriggerEvent.findUnique({where:{dedupeKey:t.dedupeKey}});return r||e.workflowTriggerEvent.create({data:{id:(0,b.randomUUID)(),kind:t.kind,subjectKey:t.subjectKey,dedupeKey:t.dedupeKey,payloadJson:JSON.stringify(t.payload)}})}async maintain(){let e=Date.now();if(e<this.nextMaintenanceAt)return;let t=await (0,t1.getPrismaClient)(),r=await t.workflowTriggerEvent.findMany({where:{status:"FAILED",receivedAt:{lt:new Date(e-6048e5)}},select:{id:!0},orderBy:{receivedAt:"asc"},take:1e3});if(r.length){await t.workflowTriggerEvent.deleteMany({where:{id:{in:r.map(({id:e})=>e)}}}),this.nextMaintenanceAt=0;return}this.nextMaintenanceAt=e+36e5}}function oA(e){try{let t=JSON.parse(e);return t&&"object"==typeof t&&!Array.isArray(t)?t:{}}catch{return{}}}function ox(e,t){return{id:e.id,name:e.name,url:e.displayOrigin,canonicalOrigin:e.canonicalOrigin,displayOrigin:e.displayOrigin,defaultBranch:t??null}}function o_(e){return{id:e.id,name:e.name,hostname:e.hostname,connected:null===e.disconnectedAt,diskFreeBytes:e.diskFreeBytes,memoryFreeBytes:e.memoryFreeBytes}}class oC{events;agentControl;worktrees;diskSpace;domains;started;running;diskAuditTimer;diskStateFingerprints;constructor(e,t,r,i,a={}){this.events=e,this.agentControl=t,this.worktrees=r,this.diskSpace=i,this.domains=a,this.started=!1,this.running=!1,this.diskStateFingerprints=new Map}start(){!this.started&&(this.started=!0,this.running=!0,this.agentControl.registerCompletionObserver(e=>this.observeAgentJob(e)),this.consumeRuns(),this.consumeBuilds(),this.consumeWorktrees(),this.consumeCodebases(),this.consumeAgents(),this.consumePipelineStatuses(),this.consumeCommandRuns(),this.consumeCommandOutput(),this.consumeSkillSyncs(),this.consumeIosDevices(),this.consumeSigningAssets(),this.consumePushNotifications(),this.consumeBuildData(),this.consumePollingOperations(),this.consumeModelCosts(),this.consumeToolCalls(),this.diskSpace&&(this.consumeDiskSpace(),this.auditDiskSpace(!0)))}stop(){this.running=!1,this.diskAuditTimer&&clearTimeout(this.diskAuditTimer),this.diskAuditTimer=void 0}async record(e,t,r,i,a={}){await this.events.record({kind:e,subjectKey:t,dedupeKey:r,payload:{...i,...a,sessionData:i}})}async worktreeSessionData(e,t=!1){return e&&this.worktrees?this.worktrees.workflowSessionDataForWorktree(e,{includeMissing:t}):{}}async observeAgentJob(e){if(e.kind===i0.WORKTREE_AUTO_SYNC_JOB_KIND&&e.worktreeId){let t=await this.worktreeSessionData(e.worktreeId,!0);await this.record("WORKTREE_AUTOMATION_RESULT",e.worktreeId,`worktree-automation:${e.id}:${e.status}`,(0,si.mergeSessionData)(t,{worktree:{id:e.worktreeId},automation:{jobId:e.id,status:e.status,error:e.error,result:oA(e.resultJson??"{}")}}),{cursorValue:`${e.id}:${e.status}`})}if("ccusage.report"===e.kind&&"SUCCEEDED"===e.status&&e.resultJson){let t=oA(e.resultJson),r=t.report&&"object"==typeof t.report&&!Array.isArray(t.report)?t.report:{},i=r.totals&&"object"==typeof r.totals&&!Array.isArray(r.totals)?r.totals:{};await this.record("CCUSAGE_THRESHOLD",e.agentId,`ccusage:${e.ccusageCollectionId??e.id}:${e.agentId}`,{run:{usage:i},agent:{id:e.agentId}},{cursorValue:e.ccusageCollectionId??e.id});return}if(!new Set(["FAILED","TIMED_OUT"]).has(e.status))return;let t=await this.worktreeSessionData(e.worktreeId,!0);await this.record("AGENT_JOB_FAILED",e.agentId,`agent-job:${e.id}:${e.status}`,(0,si.mergeSessionData)(t,{agent:{id:e.agentId},codebase:{id:e.codebaseId,agentId:e.agentId},...e.worktreeId?{worktree:{id:e.worktreeId}}:{},steps:{trigger:{id:e.id,kind:e.kind,status:e.status,error:e.error}}}),{cursorValue:`${e.id}:${e.status}`})}async consumeRuns(){let e=ie.agentEventBus.iterate(ie.RUNS_CHANGED_TOPIC);try{for await(let t of e){if(!this.running)break;"drafts"!==t.runChanged.id&&await this.observeRun(t.runChanged.id).catch(e=>console.error("Could not record workflow run trigger:",e))}}finally{await e.return?.()}}async consumePipelineStatuses(){let e=ie.agentEventBus.iterate(ie.GITHUB_PIPELINE_STATUS_CHANGED_TOPIC);try{for await(let t of e){if(!this.running)break;let e=t.githubPipelineStatusChanged,r=e.snapshot,i=e.changedPipeline??{status:r.pipelineStatus};await this.record("GITHUB_PIPELINE_STATUS_CHANGED",`${r.repositoryGithubId}:${r.headSha}`,`github-pipeline:${r.repositoryGithubId}:${r.headSha}:${r.revision}`,{repo:{githubId:r.repositoryGithubId,nameWithOwner:r.repositoryNameWithOwner,url:r.repositoryUrl},pipeline:{...i,headSha:r.headSha,aggregateStatus:r.pipelineStatus,revision:r.revision}},{cursorValue:r.revision}).catch(e=>console.error("Could not record GitHub pipeline trigger:",e))}}finally{await e.return?.()}}async consumeCommandRuns(){let e=ie.agentEventBus.iterate(ie.COMMAND_RUNS_CHANGED_TOPIC);try{for await(let t of e){if(!this.running)break;let e=this.domains.commands;if(!e)continue;let r=await e.getRun(t.commandRunsChanged.id);if(!r||!new Set(["SUCCEEDED","FAILED","CANCELLED"]).has(r.status))continue;let i=await this.worktreeSessionData(r.worktreeId,!0),a=(0,si.mergeSessionData)(i,{command:{id:r.id,commandId:r.commandId,name:r.snapshotName,status:r.status,exitCode:r.exitCode,signal:r.signal,error:r.error,finishedAt:r.finishedAt?.toISOString()??null},agent:{id:r.agentId,name:r.agentName},...r.worktreeId?{worktree:{id:r.worktreeId}}:{}}),n=r.finishedAt?.toISOString()??"terminal";await this.record("COMMAND_RUN_RESULT",r.id,`command-result:${r.id}:${r.status}:${n}`,a,{cursorValue:`${r.status}:${n}`}).catch(e=>console.error("Could not record command result trigger:",e))}}finally{await e.return?.()}}async consumeCommandOutput(){let e=ie.agentEventBus.iterate(ie.COMMAND_RUN_OUTPUT_CHANGED_TOPIC);try{for await(let t of e){if(!this.running)break;let e=t.commandRunOutputAdded,r=Buffer.from(e.dataBase64,"base64").toString("utf8");await this.record("COMMAND_OUTPUT_MATCH",e.runId,`command-output:${e.id}`,{command:{id:e.runId},output:{data:r,stream:e.stream,attempt:e.attemptNumber,sequence:e.sequence}},{cursorValue:e.id}).catch(e=>console.error("Could not record command output trigger:",e))}}finally{await e.return?.()}}async consumeSkillSyncs(){let e=ie.agentEventBus.iterate(ie.SKILLS_CHANGED_TOPIC);try{for await(let t of e){if(!this.running)break;let e=this.domains.skills;if(!e||!t.id)continue;let r=await e.getRun(t.id);if(!r)continue;let i=r.items.filter(e=>"BLOCKED"===e.status).map(e=>({id:e.id,skillId:e.skillId,skillName:e.skill?.name??null,direction:e.direction,error:e.error})),a={skillSync:{id:r.id,kind:r.kind,status:r.status,error:r.error,conflictCount:i.length,conflicts:i,updatedAt:r.updatedAt.toISOString(),finishedAt:r.finishedAt?.toISOString()??null},...r.groupId?{skill:{groupId:r.groupId}}:{}};("NEEDS_RESOLUTION"===r.status||i.length)&&await this.record("SKILL_SYNC_CONFLICT",r.id,`skill-conflict:${r.id}:${r.updatedAt.toISOString()}`,a,{cursorValue:r.updatedAt.toISOString()}),new Set(["READY","PARTIAL","SUCCEEDED"]).has(r.status)&&await this.record("SKILL_SYNC_RESULT",r.id,`skill-result:${r.id}:${r.status}:${r.updatedAt.toISOString()}`,a,{cursorValue:`${r.status}:${r.updatedAt.toISOString()}`})}}finally{await e.return?.()}}async consumeIosDevices(){let e=ie.agentEventBus.iterate(ie.IOS_DEVICES_CHANGED_TOPIC);try{for await(let t of e){if(!this.running)break;let e=this.domains.iosDevices;if(!e||!t.id)continue;let r=await e.device(t.id);if(!r)continue;let i={device:{id:r.id,udid:r.udid,name:r.displayName,product:r.product,osVersion:r.osVersion,status:r.status,error:r.registrationError,updatedAt:r.updatedAt.toISOString()}};await this.record("IOS_DEVICE_ENROLLED",r.id,`ios-device-enrolled:${r.id}:${r.createdAt.toISOString()}`,i,{cursorValue:r.createdAt.toISOString()}),new Set(["REGISTERED","REGISTRATION_FAILED","REJECTED"]).has(r.status)&&await this.record("IOS_DEVICE_REGISTRATION_RESULT",r.id,`ios-device-registration:${r.id}:${r.status}:${r.updatedAt.toISOString()}`,i,{cursorValue:`${r.status}:${r.updatedAt.toISOString()}`})}}finally{await e.return?.()}}async consumeSigningAssets(){let e=ie.agentEventBus.iterate(ie.SIGNING_ASSETS_CHANGED_TOPIC);try{for await(let t of e){if(!this.running)break;if(!t.changed)continue;let e=this.domains.signingAssets;if(!e)continue;let[r,i]=await Promise.all([e.operations(200),e.profiles()]);for(let e of r.filter(e=>e.finishedAt)){let t={signingOperation:{id:e.id,kind:e.kind,status:e.status,assetKey:e.assetKey,error:e.error,finishedAt:e.finishedAt?.toISOString()??null},...e.assetKey?{signingProfile:{id:e.assetKey}}:{}};await this.record("SIGNING_OPERATION_RESULT",e.id,`signing-operation:${e.id}:${e.status}:${e.updatedAt.toISOString()}`,t,{cursorValue:`${e.status}:${e.updatedAt.toISOString()}`})}for(let e of i.filter(e=>e.expiresAt)){let t=e.expiresAt;await this.record("SIGNING_ASSET_EXPIRING",e.id,`signing-expiry:${e.id}:${t}`,{signingProfile:{...e,id:e.id}},{cursorValue:t,expiresInDays:Math.ceil((new Date(t).getTime()-Date.now())/864e5)})}}}finally{await e.return?.()}}async consumePushNotifications(){let e=ie.agentEventBus.iterate(ie.PUSH_NOTIFICATIONS_CHANGED_TOPIC);try{for await(let t of e){if(!this.running)break;if(!t.changed)continue;let e=this.domains.pushNotifications;if(e)for(let t of(await e.history(200)).filter(e=>!new Set(["DRAFT","QUEUED","SENDING"]).has(e.status))){let e=t.updatedAt.toISOString();await this.record("PUSH_NOTIFICATION_RESULT",t.id,`push-result:${t.id}:${t.status}:${e}`,{pushBatch:{id:t.id,status:t.status,targetMode:t.targetMode,deliveryCount:t.deliveries.length,updatedAt:e}},{cursorValue:`${t.status}:${e}`})}}}finally{await e.return?.()}}async consumeBuildData(){let e=ie.agentEventBus.iterate(ie.BUILD_DATA_CHANGED_TOPIC);try{for await(let t of e){if(!this.running)break;let e=this.domains.buildData;if(!e)continue;let r=await e.getCollection(t.buildDataCollectionChanged.id);if(!r||"COMPLETED"!==r.status)continue;let i=r.entries.reduce((e,t)=>e+(t.sizeBytes??0),0),a={buildData:{id:r.id,status:r.status,finishedAt:r.finishedAt,totalBytes:i,entryCount:r.entries.length,successfulAgentCount:r.progress.successfulCount}},n=r.finishedAt??r.deadlineAt;await this.record("BUILD_DATA_THRESHOLD",r.id,`build-data-threshold:${r.id}:${n}`,a,{cursorValue:i}),await this.record("BUILD_DATA_CLEANUP_RESULT",r.id,`build-data-result:${r.id}:${n}`,a,{cursorValue:n})}}finally{await e.return?.()}}async consumePollingOperations(){let e=ie.agentEventBus.iterate(ie.POLLING_CHANGED_TOPIC);try{for await(let t of e){if(!this.running)break;let e=this.domains.polling;if(!e)continue;let r=(await e.list()).find(e=>e.id===t.pollingOperationChanged);if(!r)continue;let i=r.lastCompletedAt??r.lastStartedAt??r.nextScheduledAt??r.status;await this.record("POLLING_OPERATION_STATE",r.id,`polling-state:${r.id}:${r.status}:${i}`,{polling:r},{cursorValue:`${r.status}:${i}`}).catch(e=>console.error("Could not record polling operation trigger:",e));let a=await this.domains.credentials?.status();if(a&&"READY"!==a.state){let e=a.warnings.map(({code:e})=>e);await this.record("CREDENTIAL_STORE_DEGRADED",a.storageType,`credential-store:${a.state}:${e.join(",")}`,{credentialStore:a},{cursorValue:{state:a.state,warningCodes:e,mismatchCount:a.mismatchCount}})}}}finally{await e.return?.()}}async consumeModelCosts(){let e=ie.agentEventBus.iterate(ie.MODEL_COST_CATALOG_CHANGED_TOPIC);try{for await(let{catalog:t}of e){if(!this.running)break;let e=t.fetchedAt??`${t.url}:${t.error??"pending"}`;await this.record("MODEL_COST_CATALOG_CHANGED",t.url,`model-costs:${t.url}:${e}`,{modelCosts:t},{cursorValue:e})}}finally{await e.return?.()}}async consumeToolCalls(){let e=ie.agentEventBus.iterate(ie.TOOL_CALL_AUDIT_CHANGED_TOPIC);try{for await(let t of e){if(!this.running)break;let e=await (0,t1.getPrismaClient)(),r=await e.toolCallAudit.findUnique({where:{id:t.toolCallAuditChanged.id}});if(!r||"RUNNING"===r.resultStatus)continue;let i=r.caller.startsWith("workflow:")?r.caller.slice(9):null,a=i?await e.workflowRun.findUnique({where:{id:i},select:{id:!0,workflowId:!0}}):null,n=a?null:await e.workflowStepAttempt.findUnique({where:{id:r.correlationId},select:{run:{select:{id:!0,workflowId:!0}}}}),s=a??n?.run??null,o=r.finishedAt?.toISOString()??"unfinished";await this.record("TOOL_CALL_RESULT",r.id,`tool-call:${r.id}:${r.resultStatus}:${o}`,{toolCall:{id:r.id,correlationId:r.correlationId,caller:r.caller,source:r.source,groupId:r.groupId,toolName:r.toolName,argumentsSha256:r.argumentsSha256,resultStatus:r.resultStatus,durationMs:r.durationMs,finishedAt:r.finishedAt?.toISOString()??null}},{cursorValue:`${r.resultStatus}:${o}`,...s?{workflowCorrelation:{workflowId:s.workflowId,runId:s.id}}:{}})}}finally{await e.return?.()}}async observeRun(e){let t=await (0,t1.getPrismaClient)(),r=await t.agentRun.findUnique({where:{id:e},include:{worktree:{include:{codebase:{include:{repository:!0}}}},agent:{select:{id:!0,name:!0,hostname:!0,disconnectedAt:!0,diskFreeBytes:!0,memoryFreeBytes:!0}},questionBatches:{orderBy:{createdAt:"desc"},take:1,include:{questions:{include:{options:!0}}}},events:{orderBy:{sequence:"desc"},take:1},toolCalls:{orderBy:{sequence:"desc"},take:1}}});if(!r)return;let i=await t.workflowRunResourceLink.findFirst({where:{kind:"AGENT_RUN",resourceId:r.id},include:{run:!0},orderBy:{createdAt:"desc"}}),a=await this.worktreeSessionData(r.worktree?.id??null),n=(0,si.mergeSessionData)(a,{run:{id:r.id,kind:r.kind,status:r.status,phase:r.phase,origin:r.origin,provider:r.provider,model:r.model,finalOutput:r.finalOutput,error:r.error,sourcePlanId:r.sourcePlanId,parentRunId:r.parentRunId,followUpMode:r.followUpMode,usage:{inputTokens:r.inputTokens,outputTokens:r.outputTokens,reasoningTokens:r.reasoningTokens,cacheReadTokens:r.cacheReadTokens,cacheWriteTokens:r.cacheWriteTokens,toolCallCount:r.toolCallCount,estimatedCost:r.estimatedCost}},...r.worktree?{worktree:{id:r.worktree.id,path:r.worktree.folder,branch:r.worktree.branch,headSha:r.worktree.headSha},codebase:{id:r.worktree.codebase.id,folder:r.worktree.codebase.folder,agentId:r.worktree.codebase.agentId},repo:ox(r.worktree.codebase.repository,r.worktree.codebase.defaultBranch)}:{},...r.agent?{agent:o_(r.agent)}:{},...r.jiraIssueKey?{ticket:{key:r.jiraIssueKey}}:{}}),s=i?{workflowId:i.run.workflowId,runId:i.runId,attemptId:i.attemptId}:null,o={cursorValue:`${r.status}:${r.phase}`,workflowCorrelation:s};r.startedAt&&await this.record("RUN_STARTED",r.id,`run-started:${r.id}:${r.startedAt.toISOString()}`,n,o);let l="COMPLETED"===r.status?"RUN_COMPLETED":"FAILED"===r.status?"RUN_FAILED":"CANCELLED"===r.status?"RUN_CANCELLED":"PAUSED"===r.status?"RUN_PAUSED":null;l&&await this.record(l,r.id,`run-status:${r.id}:${r.status}:${r.finishedAt?.toISOString()??r.updatedAt.toISOString()}`,n,o),"RUNNING"===r.phase&&r.startedAt&&r.updatedAt>r.startedAt&&await this.record("RUN_CONTINUED",r.id,`run-continued:${r.id}:${r.updatedAt.toISOString()}`,n,o),r.sourcePlanId&&await this.record("RUN_PLAN_PLAYED",r.id,`run-plan-played:${r.id}:${r.sourcePlanId}`,n,o),r.parentRunId&&"PLAN_PLAY"!==r.followUpMode&&await this.record("RUN_FOLLOW_UP",r.id,`run-follow-up:${r.id}:${r.parentRunId}`,n,o),"IMPORTED"===r.origin&&await this.record("RUN_IMPORTED",r.id,`run-imported:${r.id}:${r.updatedAt.toISOString()}`,n,o),await this.record("RUN_USAGE_THRESHOLD",r.id,`run-usage:${r.id}:${r.updatedAt.toISOString()}`,n,{...o,cursorValue:r.updatedAt.toISOString()});let c=r.questionBatches[0];if(c){let e={...n,run:{...n.run,questions:c.questions}};"PENDING"===c.status?await this.record("RUN_QUESTION_NEEDED",r.id,`run-question:${c.id}:pending`,e,o):"ANSWERED"===c.status&&await this.record("RUN_QUESTION_ANSWERED",r.id,`run-question:${c.id}:answered`,e,o)}let u=r.events[0];u&&await this.record("RUN_EVENT_MATCH",r.id,`run-event:${u.id}`,n,{...o,event:u});let d=r.toolCalls[0];d&&await this.record("RUN_EVENT_MATCH",r.id,`run-tool:${d.id}:${d.status}`,n,{...o,toolCall:d})}async consumeBuilds(){let e=ie.agentEventBus.iterate(ie.BUILDS_CHANGED_TOPIC);try{for await(let t of e){if(!this.running)break;await this.observeBuild(t.buildsChanged.id).catch(e=>console.error("Could not record workflow build trigger:",e))}}finally{await e.return?.()}}async observeBuild(e){let t=await (0,t1.getPrismaClient)(),r=await t.build.findUnique({where:{id:e},include:{codebase:{include:{repository:!0,agent:{select:{id:!0,name:!0,hostname:!0,disconnectedAt:!0,diskFreeBytes:!0,memoryFreeBytes:!0}}}},worktree:!0,reports:!0,scriptExecutions:!0}});if(!r)return;let i=await this.worktreeSessionData(r.worktree?.id??null),a=(0,si.mergeSessionData)(i,{build:{id:r.id,status:r.status,action:r.action,error:r.error},...r.codebase?{codebase:{id:r.codebase.id,folder:r.codebase.folder,agentId:r.codebase.agentId},repo:ox(r.codebase.repository,r.codebase.defaultBranch),agent:o_(r.codebase.agent)}:{},...r.worktree?{worktree:{id:r.worktree.id,path:r.worktree.folder,branch:r.worktree.branch,headSha:r.worktree.headSha}}:{}});for(let e of(new Set(["SUCCEEDED","FAILED","CANCELLED"]).has(r.status)&&await this.record("BUILD_RESULT",r.id,`build-result:${r.id}:${r.status}`,a,{cursorValue:r.status}),r.reports.filter(({status:e})=>"READY"===e))){let t=oA(e.summaryJson),i={...a,build:{...a.build,..."TEST_RESULTS"===e.kind?{testSummary:t}:{coverageSummary:t}}};await this.record("TEST_RESULTS"===e.kind?"BUILD_TEST_THRESHOLD":"BUILD_COVERAGE_THRESHOLD",r.id,`build-report:${e.id}:${e.updatedAt.toISOString()}`,i,{cursorValue:e.updatedAt.toISOString()})}for(let e of r.scriptExecutions.filter(({causedBuildFailure:e})=>e))await this.record("BUILD_HOOK_FAILED",r.id,`build-hook:${e.id}:failed`,a,{cursorValue:e.id,script:{id:e.id,name:e.nameSnapshot,phase:e.phase}})}async consumeWorktrees(){let e=ie.agentEventBus.iterate(ie.WORKTREE_CHANGED_TOPIC);try{for await(let t of e){if(!this.running)break;let e=t.worktreeOverviewChanged,r=await (0,t1.getPrismaClient)();for(let t of(await r.worktree.findMany({where:e.worktreeId?{id:e.worktreeId}:e.codebaseId?{codebaseId:e.codebaseId}:{},include:{codebase:{include:{repository:!0}}},take:e.worktreeId?1:500})))await this.observeWorktree(t).catch(e=>console.error("Could not record workflow worktree trigger:",e))}}finally{await e.return?.()}}async observeWorktree(e){let t=e.lastCheckedAt??e.updatedAt,r=e.hasStagedChanges||e.hasUnstagedChanges,i=await this.worktreeSessionData(e.id,!0),a=(0,si.mergeSessionData)(i,{repo:ox(e.codebase.repository,e.codebase.defaultBranch),codebase:{id:e.codebase.id,folder:e.codebase.folder,agentId:e.codebase.agentId},worktree:{id:e.id,path:e.folder,branch:e.branch,headSha:e.headSha,syncState:e.syncState,pushStatus:e.pushStatus,statusError:e.statusError,baseBehind:e.baseBehind,dirty:r,missingAt:e.missingAt?.toISOString()??null,dirtySince:r?e.updatedAt.toISOString():null}}),n={cursorValue:t.toISOString()};await this.record("WORKTREE_SYNC_STATE_CHANGED",e.id,`worktree-sync:${e.id}:${e.syncState}:${t.toISOString()}`,a,{cursorValue:e.syncState}),await this.record("WORKTREE_CLEAN",e.id,`worktree-clean:${e.id}:${t.toISOString()}`,a,{cursorValue:r}),(e.baseBehind??0)>0&&await this.record("WORKTREE_BEHIND",e.id,`worktree-behind:${e.id}:${t.toISOString()}`,a,n),await this.record("WORKTREE_DIRTY_DURATION",e.id,`worktree-dirty:${e.id}:${t.toISOString()}`,a,n),await this.record("WORKTREE_MISSING",e.id,`worktree-missing:${e.id}:${t.toISOString()}`,a,{cursorValue:!!e.missingAt}),await this.record("WORKTREE_DIVERGED",e.id,`worktree-diverged:${e.id}:${t.toISOString()}`,a,{cursorValue:"DIVERGED"===e.pushStatus}),e.headSha&&await this.record("WORKTREE_NEW_COMMIT",e.id,`worktree-commit:${e.id}:${e.headSha}`,a,{cursorValue:e.headSha})}async consumeCodebases(){let e=ie.agentEventBus.iterate(ie.CODEBASE_CHANGED_TOPIC);try{for await(let t of e){if(!this.running)break;let e=await (0,t1.getPrismaClient)(),r=t.codebaseOverviewChanged;for(let t of(await e.codebase.findMany({where:r.codebaseId?{id:r.codebaseId}:r.repositoryId?{repositoryId:r.repositoryId}:{},include:{repository:!0,agent:{select:{id:!0,name:!0,hostname:!0,disconnectedAt:!0,diskFreeBytes:!0,memoryFreeBytes:!0}}},take:r.codebaseId?1:500}))){let e={repo:ox(t.repository,t.defaultBranch),agent:o_(t.agent),codebase:{id:t.id,folder:t.folder,agentId:t.agentId,branch:t.defaultBranch,syncState:t.syncState,availability:t.availability,statusError:t.statusError,lastFetchError:t.lastFetchError,remoteBranches:JSON.parse(t.remoteBranchesJson)}},r=(t.lastCheckedAt??t.updatedAt).toISOString();await this.record("CODEBASE_SYNC_STATE_CHANGED",t.id,`codebase-sync:${t.id}:${t.syncState}:${r}`,e,{cursorValue:t.syncState}),(t.statusError||t.lastFetchError)&&await this.record("CODEBASE_OPERATION_FAILED",t.id,`codebase-failed:${t.id}:${r}`,e,{cursorValue:r,error:t.statusError??t.lastFetchError});let i=e.codebase.remoteBranches;if(Array.isArray(i))for(let r of i.filter(e=>"string"==typeof e))await this.record("CODEBASE_REMOTE_BRANCH",t.id,`codebase-remote-branch:${t.id}:${r}`,e,{cursorValue:r,branch:r})}}}finally{await e.return?.()}}async emitDiskSnapshot(e,t){let r=e.agent.id;t.report&&await this.record("AGENT_DISK_REPORT",r,`agent-disk-report:${r}:${e.disk.lastReportedAt??t.changeId}`,e,{cursorValue:e.disk.lastReportedAt}),t.threshold&&await this.record("AGENT_DISK_THRESHOLD",r,`agent-disk-threshold:${r}:${t.changeId}`,e);let i=ia(e);if(await this.record("AGENT_DISK_STATE_CHANGED",r,`agent-disk-state:${r}:${t.changeId}`,e,{cursorValue:i}),this.diskStateFingerprints.set(r,JSON.stringify(i)),t.cleanup){let i={...e,cleanup:t.cleanup};await this.record("AGENT_DISK_CLEANUP_RESULT",r,`agent-disk-cleanup:${t.cleanup.jobId}:${t.cleanup.status}`,i,{cleanup:t.cleanup})}}async observeDiskChange(e){if(!this.diskSpace)return;let{id:t,reason:r,cleanup:i}=e.diskSpaceChange;if("settings"===e.diskSpaceChanged){let e=await this.diskSpace.overview();for(let i of e.agents)await this.emitDiskSnapshot(ii(e.settings,i,r),{changeId:t,report:!1,threshold:!0});return}let a=await this.diskSpace.snapshot(e.diskSpaceChanged,r);await this.emitDiskSnapshot(a,{changeId:t,report:"REPORT_RECEIVED"===r,threshold:!0,cleanup:i})}async consumeDiskSpace(){if(!this.diskSpace)return;let e=this.diskSpace.subscribe();try{for await(let t of e){if(!this.running)break;await this.observeDiskChange(t).catch(e=>console.error("Could not record disk-space workflow trigger:",e))}}finally{await e.return?.()}}async auditDiskSpace(e){if(this.diskSpace&&this.running)try{let t=await this.diskSpace.overview();for(let r of t.agents){let i=ii(t.settings,r,e?"STARTUP_RECONCILE":"STATE_AUDIT"),a=JSON.stringify(ia(i));(e||this.diskStateFingerprints.get(r.agent.id)!==a)&&await this.emitDiskSnapshot(i,{changeId:(0,b.randomUUID)(),report:!1,threshold:e})}}catch(e){console.error("Could not audit disk-space workflow state:",e)}finally{this.running&&(this.diskAuditTimer=setTimeout(()=>void this.auditDiskSpace(!1),1e3*r7.DISK_SPACE_POLL_INTERVAL_SECONDS),this.diskAuditTimer.unref?.())}}async consumeAgents(){let e=ie.agentEventBus.iterate(ie.AGENT_CHANGED_TOPIC);try{for await(let t of e){if(!this.running)break;let e=await (0,t1.getPrismaClient)(),r=await e.agent.findUnique({where:{id:t.agentChanged.id}});if(!r)continue;let i=null===r.disconnectedAt,a={codebase:{agentId:r.id},agent:{id:r.id,name:r.name,connected:i,diskFreeBytes:r.diskFreeBytes,memoryFreeBytes:r.memoryFreeBytes}};await this.record("AGENT_CONNECTION",r.id,`agent-connection:${r.id}:${r.updatedAt.toISOString()}`,a,{cursorValue:i}),await this.record("AGENT_RESOURCE_THRESHOLD",r.id,`agent-resource:${r.id}:${r.updatedAt.toISOString()}`,a,{cursorValue:{diskFreeBytes:r.diskFreeBytes,memoryFreeBytes:r.memoryFreeBytes}}),await this.record("AGENT_VERSION_CHANGED",r.id,`agent-version:${r.id}:${r.version}`,{...a,agent:{...a.agent,version:r.version,osVersion:r.osVersion,architecture:r.architecture}},{cursorValue:r.version})}}finally{await e.return?.()}}}function oR(e){return null===e||["string","number","boolean"].includes(typeof e)?e:JSON.stringify(e)}function oT(e,t){if("ALL"===e.op)return e.conditions.every(e=>oT(e,t));if("ANY"===e.op)return e.conditions.some(e=>oT(e,t));if("NOT"===e.op)return!oT(e.condition,t);if(!("left"in e))return!1;let r=(0,si.resolveWorkflowValue)(e.left,t),i=(0,si.resolveWorkflowValue)(e.right,t);switch(e.op){case"EXISTS":return null!=r;case"EQ":return JSON.stringify(r)===JSON.stringify(i);case"NE":return JSON.stringify(r)!==JSON.stringify(i);case"GT":return oR(r)>oR(i);case"GTE":return oR(r)>=oR(i);case"LT":return oR(r)<oR(i);case"LTE":return oR(r)<=oR(i);case"CONTAINS":return Array.isArray(r)?r.some(e=>JSON.stringify(e)===JSON.stringify(i)):String(r??"").includes(String(i??""));case"MATCHES":return(0,sX.compileRe2)(String(i??""),{label:"Workflow condition pattern"}).test(String(r??""))}}var oD=e.i(248626),oN=e.i(336921),oO=e.i(53803),oP=e.i(264977);async function oL(e,t){let r=e.trim();if(!r||r.length>5e4)throw Error(`Workflow script must contain 1–${5e4.toLocaleString()} characters`);let i=await (0,oO.getQuickJS)(),a=Date.now()+250;try{return i.evalCode(`"use strict"; const session = Object.freeze(${JSON.stringify(t)}); (${r})(session);`,{memoryLimitBytes:8388608,maxStackSizeBytes:524288,shouldInterrupt:(0,oP.shouldInterruptAfterDeadline)(a)})}catch(t){let e=t instanceof Error?t.message:String(t);throw Error(`Workflow script failed: ${"interrupted"===e?"execution timed out after 250ms":e}`)}}class oB{handlers=new Map;register(e,t){this.handlers.set(e,t)}has(e){return this.handlers.has(e)}execute(e){let t=this.handlers.get(e.node.kind);if(!t)throw Error(`Workflow step ${e.node.kind} is not registered`);return t(e)}}let oU="workflows:changed",oj=e=>`workflow-run:${e}`,oM=e=>`workflow-run:${e}:events`,oq=e=>`workflow-run:${e}:questions`,o$=["QUEUED","RUNNING","PAUSING","PAUSED","WAITING","BLOCKED"],oF=new Set(["SUCCEEDED","FAILED","CANCELLED"]),oG=new Set(["SUCCEEDED","FAILED","CANCELLED","SKIPPED","SUPERSEDED"]),oK=new Set(["RUNNING","WAITING"]),oH=new Set(["WORKTREE_CREATE","WORKTREE_DELETE","WORKTREE_MOVE","WORKTREE_MOVE_CONTROL"]);function oV(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}function oW(e,t){let r;if(e.exclusiveWorktree&&("string"==typeof(r=(0,si.getSessionValue)(t,"worktree.id"))&&r?r:null)!==e.worktreeId)throw Error("Exclusive workflows cannot change worktrees; start a new workflow on the target worktree instead")}let oJ=e=>JSON.parse(e);function oz(e){return{agent:{id:e.id,name:e.name,hostname:e.hostname,...void 0!==e.lastSeenAt&&void 0!==e.disconnectedAt?{connected:null!==e.lastSeenAt&&null===e.disconnectedAt&&Date.now()-e.lastSeenAt.getTime()<=(0,a.agentOnlineWindowMs)(e)}:{},...void 0!==e.diskFreeBytes?{diskFreeBytes:e.diskFreeBytes}:{},...void 0!==e.memoryFreeBytes?{memoryFreeBytes:e.memoryFreeBytes}:{}}}}function oY(e){return(0,si.mergeSessionData)(oz(e.agent),{codebase:{id:e.id,folder:e.folder,agentId:e.agentId,branch:e.branch,headSha:e.headSha},repo:{id:e.repository.id,name:e.repository.name,url:e.repository.displayOrigin,canonicalOrigin:e.repository.canonicalOrigin,displayOrigin:e.repository.displayOrigin,defaultBranch:e.defaultBranch}})}function oZ(e,t,r){let i=e.trim();if(!i)throw Error(`${t} is required`);if(i.length>r)throw Error(`${t} is too long`);return i}function oQ(e){let t=e?.trim().toUpperCase()||"QUEUE";if(!new Set(["QUEUE","CONCURRENT","COALESCE_LATEST"]).has(t))throw Error("Workflow overlap policy is not supported");return t}function oX(e){let t=e?.trim().toUpperCase()||"WORKTREE";if(!new Set(["WORKTREE","GLOBAL"]).has(t))throw Error("Workflow overlap scope is not supported");return t}let o0=["EXCLUSIVE","NON_EXCLUSIVE","EXCLUDED"];function o1(e,t){let r=e?.trim().toUpperCase()||(!0===t?"EXCLUSIVE":"NON_EXCLUSIVE");if(!o0.includes(r))throw Error("Workflow worktree concurrency is not supported");return r}function o2(e,t){return"EXCLUSIVE"===e||(t??!1)}function o3(e,t){return"WORKTREE"===e?{worktreeId:t}:{}}function o4(e,t){let r=e??("CONCURRENT"===t?4:1);if(!Number.isInteger(r)||r<1||r>32)throw Error("Maximum concurrent runs must be between 1 and 32");return r}function o6(e){return Array.isArray(e)?`[${e.map(o6).join(",")}]`:e&&"object"==typeof e?`{${Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${JSON.stringify(e)}:${o6(t)}`).join(",")}}`:JSON.stringify(e)}function o8(e,t,r){if(Buffer.byteLength(e,"utf8")>r)throw Error(`${t} is too large`)}function o5(e,t){if(!e||"object"!=typeof e||Array.isArray(e))throw Error(`${t} must be an object`);return e}function o9(e){ie.agentEventBus.publish(oU,{workflowChanged:{id:e}})}function o7(e){ie.agentEventBus.publish(oj(e),{workflowRunChanged:{id:e}}),ie.agentEventBus.publish(oU,{workflowChanged:{id:"runs",runId:e}}),ie.agentEventBus.publish(ie.SIDEBAR_STATUS_CHANGED_TOPIC,{sidebarStatusChanged:!0})}function le(e){return[...iC.WORKFLOW_STEP_BY_KIND.get(e.kind).requiredPaths.map(t=>t.replaceAll("<stepId>",e.id)),...e.requiredPaths,...(0,oD.requiredConfigSessionPaths)(e.kind,"step",e.config)]}function lt(e){return[...iC.WORKFLOW_STEP_BY_KIND.get(e.kind).providedPaths.map(t=>t.replaceAll("<stepId>",e.id)),...e.providedPaths,`steps.${e.id}.*`]}async function lr(e){return(await e.workflowRunNumberSequence.upsert({where:{id:"default"},create:{id:"default",nextValue:2},update:{nextValue:{increment:1}}})).nextValue-1}class li{events;executor;checkpointRestorer;credentials;agentControl;notifications;runsService;worktrees;commandsService;jiraService;runtimeTimer;commandOutputStream;ticking;workerId;activeExecutions;claimedSecretJobs;waitPollers;constructor(e,t=new oB,r,i,a,n,s,o,l,c){this.events=e,this.executor=t,this.checkpointRestorer=r,this.credentials=i,this.agentControl=a,this.notifications=n,this.runsService=s,this.worktrees=o,this.commandsService=l,this.jiraService=c,this.ticking=!1,this.workerId=(0,b.randomUUID)(),this.activeExecutions=new Map,this.claimedSecretJobs=new Set,this.waitPollers=new Map,this.runsService?.setWorktreeAdmissionPromoter(async()=>{await this.startQueuedRuns()}),this.agentControl&&(this.executor.register("TERMINAL_RUN",e=>this.startTerminalJob(e)),this.executor.register("WORKTREE_SNAPSHOT",e=>this.startCheckpointJob(e)),this.agentControl.registerCompletionHandler(oN.WORKFLOW_TERMINAL_JOB_KIND,e=>this.workflowAgentJobCompleted(e)),this.agentControl.registerCompletionObserver(e=>this.genericAgentJobCompleted(e)),this.agentControl.registerCompletionHandler(oN.WORKFLOW_GIT_CHECKPOINT_JOB_KIND,e=>this.workflowAgentJobCompleted(e)))}async controlLinkedAgentRuns(e,t){if(!this.runsService)return;let r=await (0,t1.getPrismaClient)(),i=await r.workflowRunResourceLink.findMany({where:{runId:e,kind:"AGENT_RUN",attempt:{status:{in:["RUNNING","WAITING"]}}},select:{resourceId:!0},distinct:["resourceId"]});await Promise.allSettled(i.map(async({resourceId:e})=>{let r=await this.runsService.get(e);!r||"MANAGED"!==r.origin||"PAUSE"===t&&"IN_PROGRESS"!==r.status||"CONTINUE"===t&&"PAUSED"!==r.status||"CANCEL"===t&&new Set(["COMPLETED","FAILED","CANCELLED"]).has(r.status)||await this.runsService.lifecycle(e,t)}))}async cancelWaitingCommandRuns(e){if(!this.commandsService)return;let t=await (0,t1.getPrismaClient)(),r=await t.workflowRunResourceLink.findMany({where:{runId:e,kind:"COMMAND_RUN",attempt:{status:"WAITING"}},select:{resourceId:!0},distinct:["resourceId"]});await Promise.allSettled(r.map(({resourceId:e})=>this.commandsService.terminateRun(e)))}async promoteWorktreeAdmissions(e){if(e)try{await this.runsService?.reconcileQueuedRuns(),await this.startQueuedRuns()}catch(t){console.error(`Could not promote worktree queue for ${e}:`,t instanceof Error?t.message:t)}}async runWorktree(e){let t=(0,si.getSessionValue)(oJ(e),"worktree.id");return"string"==typeof t&&t?(await (0,t1.getPrismaClient)()).worktree.findUnique({where:{id:t},select:{id:!0,folder:!0,branch:!0,highlightColor:!0}}):null}async runAgent(e){let t=oJ(e),r=(0,si.getSessionValue)(t,"agent.id")??(0,si.getSessionValue)(t,"codebase.agentId"),i=await (0,t1.getPrismaClient)();if("string"==typeof r&&r)return i.agent.findUnique({where:{id:r}});let a=(0,si.getSessionValue)(t,"worktree.id");if("string"!=typeof a||!a)return null;let n=await i.worktree.findUnique({where:{id:a},select:{codebase:{select:{agent:!0}}}});return n?.codebase.agent??null}async queueForWorktree(e){let t=await (0,t1.getPrismaClient)(),[r,i,a]=await Promise.all([t.workflowRun.findMany({where:{worktreeId:e,status:"QUEUED"},orderBy:[{queuedAt:"asc"},{id:"asc"}],select:{id:!0,displayNumber:!0,status:!0,phase:!0,queuedAt:!0,exclusiveWorktree:!0,worktreeConcurrency:!0,worktreeLeaseOwnerRunId:!0,workflowId:!0,workflow:{select:{name:!0}},worktree:{select:{id:!0,folder:!0,branch:!0,highlightColor:!0}}}}),t.agentRun.findMany({where:{worktreeId:e,origin:"MANAGED",status:"QUEUED",kind:{in:["PLAN","SESSION"]}},orderBy:[{createdAt:"asc"},{id:"asc"}],select:{id:!0,kind:!0,displayNumber:!0,status:!0,phase:!0,createdAt:!0,initialPrompt:!0,worktreeConcurrencyLimit:!0,worktree:{select:{id:!0,folder:!0,branch:!0,highlightColor:!0}},workflowRun:{select:{id:!0,workflowId:!0,worktreeLeaseOwnerRunId:!0}}}}),t.worktreeWorkflowLease.findUnique({where:{worktreeId:e},select:{workflowRunId:!0}})]);return[...r.map(t=>({id:t.id,kind:"WORKFLOW",displayNumber:t.displayNumber,name:t.workflow.name,status:t.status,phase:t.phase,worktreeId:e,worktree:t.worktree,workflowId:t.workflowId,workflowRunId:t.id,queuedAt:t.queuedAt,exclusiveWorktree:t.exclusiveWorktree,worktreeConcurrency:t.worktreeConcurrency,worktreeConcurrencyLimit:null,leaseOwnerRunId:t.worktreeLeaseOwnerRunId})),...i.map(t=>({id:t.id,kind:t.kind,displayNumber:t.displayNumber,name:t.initialPrompt,status:t.status,phase:t.phase,worktreeId:e,worktree:t.worktree,workflowId:t.workflowRun?.workflowId??null,workflowRunId:t.workflowRun?.id??null,queuedAt:t.createdAt,exclusiveWorktree:!1,worktreeConcurrency:"NON_EXCLUSIVE",worktreeConcurrencyLimit:t.worktreeConcurrencyLimit,leaseOwnerRunId:t.workflowRun?.worktreeLeaseOwnerRunId??null}))].sort((e,t)=>{if(a){let r=e.leaseOwnerRunId===a.workflowRunId;if(r!==(t.leaseOwnerRunId===a.workflowRunId))return r?-1:1}return e.queuedAt.getTime()-t.queuedAt.getTime()||e.id.localeCompare(t.id)}).map(({leaseOwnerRunId:e,...t},r)=>({...t,position:r+1,queuedAt:t.queuedAt.toISOString()}))}async runQueue(e){if(e.worktreeId)return this.queueForWorktree(e.worktreeId);if(!e.workflowId)throw Error("A worktree or workflow is required to read its queue");let t=await (0,t1.getPrismaClient)(),[r,i]=await Promise.all([t.workflowRun.findMany({where:{workflowId:e.workflowId,status:"QUEUED"},select:{id:!0,worktreeId:!0,displayNumber:!0,status:!0,phase:!0,queuedAt:!0,exclusiveWorktree:!0,worktreeConcurrency:!0,workflow:{select:{name:!0}}}}),t.agentRun.findMany({where:{origin:"MANAGED",status:"QUEUED",workflowRun:{workflowId:e.workflowId}},select:{id:!0,worktreeId:!0}})]),a=new Set(r.map(({id:e})=>e)),n=new Set(i.map(({id:e})=>e)),s=[...new Set([...r,...i].map(({worktreeId:e})=>e).filter(e=>!!e))];return[...(await Promise.all(s.map(e=>this.queueForWorktree(e)))).flat().filter(e=>"WORKFLOW"===e.kind?a.has(e.id):n.has(e.id)),...r.filter(({worktreeId:e})=>!e).sort((e,t)=>e.queuedAt.getTime()-t.queuedAt.getTime()||e.id.localeCompare(t.id)).map((t,r)=>({position:r+1,id:t.id,kind:"WORKFLOW",displayNumber:t.displayNumber,name:t.workflow.name,status:t.status,phase:t.phase,worktreeId:null,worktree:null,workflowId:e.workflowId,workflowRunId:t.id,queuedAt:t.queuedAt.toISOString(),exclusiveWorktree:t.exclusiveWorktree,worktreeConcurrency:t.worktreeConcurrency,worktreeConcurrencyLimit:null}))].sort((e,t)=>new Date(e.queuedAt).getTime()-new Date(t.queuedAt).getTime()||e.id.localeCompare(t.id))}async runQueueForWorkflowRun(e){let t=await (0,t1.getPrismaClient)(),r=await t.workflowRun.findUnique({where:{id:e},select:{status:!0,worktreeId:!0,workflowId:!0}});return r&&"QUEUED"===r.status?r.worktreeId?this.queueForWorktree(r.worktreeId):(await this.runQueue({workflowId:r.workflowId})).filter(({worktreeId:e})=>!e):[]}async notifyRun(e,t,r,i,a){if(!this.notifications)return;let n=await (0,t1.getPrismaClient)(),s=await n.workflowRun.findUnique({where:{id:e},select:{sessionDataJson:!0,workflow:{select:{completionNotificationsEnabled:!0}}}});if("WORKFLOW_COMPLETED"===t&&s?.workflow.completionNotificationsEnabled===!1)return;let o=s?await this.runWorktree(s.sessionDataJson):null,l=await n.$transaction(n=>this.notifications.recordInTransaction(n,{dedupeKey:`workflow:${e}:${a}`,typeKey:t,title:r,body:i,href:`/workflows/runs/${e}`,resourceKind:"WORKFLOW_RUN",resourceId:e,worktreeId:o?.id??null,highlightColor:o?.highlightColor??null}));this.notifications.created(l)}startRuntime(){this.runtimeTimer||(this.consumeCommandOutputMatches(),this.runtimeTimer=setInterval(()=>{this.tick().catch(e=>{console.error("Workflow runtime tick failed:",e)})},1e3),this.runtimeTimer.unref?.(),this.tick().catch(e=>{console.error("Workflow runtime startup failed:",e)}))}stopRuntime(){for(let e of(this.runtimeTimer&&clearInterval(this.runtimeTimer),this.runtimeTimer=void 0,this.commandOutputStream?.return?.(),this.commandOutputStream=void 0,this.activeExecutions.values()))e.abort();this.activeExecutions.clear()}catalog(){return{schemaVersion:iC.WORKFLOW_SCHEMA_VERSION,globalConcurrency:4,steps:iC.WORKFLOW_STEP_CATALOG,triggers:iC.WORKFLOW_TRIGGER_CATALOG}}registerWaitPoller(e,t){this.waitPollers.set(e,t)}async list(e={}){let t=await (0,t1.getPrismaClient)(),r=Math.min(Math.max(e.first??100,1),200),i=e.archive?.toUpperCase()??"ACTIVE",a=e.search?.trim(),n=await t.workflow.findMany({where:{..."ALL"===i?{}:"ARCHIVED"===i?{archivedAt:{not:null}}:{archivedAt:null},...null===e.enabled||void 0===e.enabled?{}:{enabled:e.enabled},...a?{OR:[{name:{contains:a}},{description:{contains:a}}]}:{}},include:{activeVersion:!0,quickActionRepositories:{include:{repository:!0}},_count:{select:{versions:!0,runs:!0}}},orderBy:[{updatedAt:"desc"},{id:"desc"}],take:r+1,...e.after?{cursor:{id:e.after},skip:1}:{}});return{items:n.slice(0,r),nextCursor:n.length>r?n[r-1].id:null,totalCount:await t.workflow.count()}}async get(e){return(await (0,t1.getPrismaClient)()).workflow.findUnique({where:{id:e},include:{activeVersion:!0,versions:{orderBy:{version:"desc"}},quickActionRepositories:{include:{repository:!0}},_count:{select:{runs:!0}}}})}async version(e){return(await (0,t1.getPrismaClient)()).workflowVersion.findUnique({where:{id:e},include:{triggers:!0}})}async create(e){let t=oZ(e.name,"Workflow name",200),r=(0,iC.parseWorkflowDefinition)(e.definition??(0,iC.emptyWorkflowDefinition)(t)),i=JSON.stringify({...r,name:t,description:e.description?.trim()??r.description});o8(i,"Workflow definition",2097152);let a=oQ(e.overlapPolicy),n=o1(e.worktreeConcurrency,e.exclusiveWorktree),s=await (0,t1.getPrismaClient)(),o=await s.workflow.create({data:{id:(0,b.randomUUID)(),name:t,description:e.description?.trim()??r.description,draftDefinitionJson:i,draftSchemaVersion:iC.WORKFLOW_SCHEMA_VERSION,overlapPolicy:a,overlapScope:oX(e.overlapScope),maxConcurrentRuns:o4(e.maxConcurrentRuns,a),completionNotificationsEnabled:e.completionNotificationsEnabled??!0,exclusiveWorktree:"EXCLUSIVE"===n,worktreeConcurrency:n,blocksGitOperations:o2(n,e.blocksGitOperations)}});return o9(o.id),this.get(o.id)}async saveDraft(e){let t=(0,iC.parseWorkflowDefinition)(e.definition),r=JSON.stringify(t);o8(r,"Workflow definition",2097152);let i=await this.get(e.id);if(!i)throw Error("Workflow not found");let a=oQ(e.overlapPolicy??i.overlapPolicy),n=o1(e.worktreeConcurrency??(null===e.exclusiveWorktree||void 0===e.exclusiveWorktree?i.worktreeConcurrency:null),e.exclusiveWorktree??i.exclusiveWorktree),s=await (0,t1.getPrismaClient)();return await s.workflow.update({where:{id:e.id},data:{name:t.name,description:t.description,draftDefinitionJson:r,draftSchemaVersion:t.schemaVersion,overlapPolicy:a,overlapScope:oX(e.overlapScope??i.overlapScope),maxConcurrentRuns:o4(e.maxConcurrentRuns??i.maxConcurrentRuns,a),completionNotificationsEnabled:e.completionNotificationsEnabled??i.completionNotificationsEnabled,exclusiveWorktree:"EXCLUSIVE"===n,worktreeConcurrency:n,blocksGitOperations:o2(n,e.blocksGitOperations??i.blocksGitOperations)}}),o9(e.id),this.get(e.id)}async validateDraft(e){let t=await this.get(e);if(!t)throw Error("Workflow not found");let r=(0,iC.validateWorkflowDefinition)(oJ(t.draftDefinitionJson)),i=[...r.diagnostics];if(r.definition){for(let e of r.definition.nodes){if("SAVED_COMMAND"===e.kind||"CUSTOM_COMMAND"===e.kind){let t=(0,sQ.commandOutputPattern)(e.config);if(t)try{s1(t)}catch(t){i.some(({code:t,nodeId:r})=>"COMMAND_MATCH_PATTERN_INVALID"===t&&r===e.id)||i.push({severity:"ERROR",code:"COMMAND_MATCH_PATTERN_INVALID",message:t instanceof Error?t.message:String(t),nodeId:e.id})}}try{!function e(t){let r=oV(t);if("ALL"===r.op||"ANY"===r.op){if(Array.isArray(r.conditions))for(let t of r.conditions)e(t);return}if("NOT"===r.op)return void e(r.condition);if("MATCHES"!==r.op)return;let i=function(e){if("string"==typeof e)return e;let t=oV(e);return"LITERAL"===t.source&&"string"==typeof t.value?t.value:null}(r.right);null!==i&&(0,sX.compileRe2)(i,{label:"Workflow condition pattern"})}(e.config.condition)}catch(t){i.push({severity:"ERROR",code:"WORKFLOW_REGEX_PATTERN_INVALID",message:t instanceof Error?t.message:String(t),nodeId:e.id})}}for(let e of r.definition.triggers){let t="GITHUB_ISSUE_COMMAND"===e.kind||"JIRA_ISSUE_COMMAND"===e.kind?e.config.commandPattern:"COMMAND_OUTPUT_MATCH"===e.kind?e.config.outputPattern:null;if("string"==typeof t)try{(0,sX.compileRe2)(t,{label:"COMMAND_OUTPUT_MATCH"===e.kind?"Command output trigger pattern":"Issue command pattern"})}catch(t){i.some(({code:t,triggerId:r})=>"WORKFLOW_REGEX_PATTERN_INVALID"===t&&r===e.id)||i.push({severity:"ERROR",code:"WORKFLOW_REGEX_PATTERN_INVALID",message:t instanceof Error?t.message:String(t),triggerId:e.id})}}i.push(...await this.validateSubworkflows(t.id,r.definition))}return{valid:!(0,iC.hasWorkflowErrors)(i),diagnostics:i}}async validateSubworkflows(e,t){let r=t.nodes.filter(({kind:e})=>"CONTROL_SUBWORKFLOW"===e).map(e=>({node:e,versionId:e.config.versionId})).filter(e=>"string"==typeof e.versionId);if(!r.length)return[];let i=await (0,t1.getPrismaClient)(),a=new Map,n=new Map,s=new Set,o=new Set,l=r.map(({versionId:e})=>e);for(;l.length;){let e=[...new Set(l)].filter(e=>!o.has(e));if(!e.length)break;for(let t of(e.forEach(e=>o.add(e)),l=[],await i.workflowVersion.findMany({where:{id:{in:e}}}))){a.set(t.id,t);try{let e=(0,iC.parseWorkflowDefinition)(oJ(t.definitionJson)).nodes.filter(({kind:e})=>"CONTROL_SUBWORKFLOW"===e).map(({config:e})=>e.versionId).filter(e=>"string"==typeof e);n.set(t.id,e),l.push(...e)}catch{s.add(t.id)}}}let c=(e,t)=>{let r=a.get(e);if(!r)return"MISSING";if(s.has(e))return"INVALID";if(t.has(r.workflowId))return"RECURSIVE";let i=new Set(t).add(r.workflowId);for(let t of n.get(e)??[]){let e=c(t,i);if(e)return e}return null},u=[];for(let{node:t,versionId:i}of r){let r=c(i,new Set([e]));"MISSING"===r?u.push({severity:"ERROR",code:"SUBWORKFLOW_NOT_FOUND",message:"Pinned sub-workflow chain contains a missing version",nodeId:t.id}):"INVALID"===r?u.push({severity:"ERROR",code:"SUBWORKFLOW_INVALID",message:"Pinned sub-workflow chain contains an invalid definition",nodeId:t.id}):"RECURSIVE"===r&&u.push({severity:"ERROR",code:"SUBWORKFLOW_RECURSION",message:"Pinned sub-workflow calls cannot form a recursive chain",nodeId:t.id})}return u}async publish(e){let t=await this.get(e);if(!t)throw Error("Workflow not found");let r=(0,iC.parseWorkflowDefinition)(oJ(t.draftDefinitionJson)),i=await this.validateDraft(e);if(!i.valid)throw Error(`Workflow cannot be published: ${i.diagnostics.filter(({severity:e})=>"ERROR"===e).map(({message:e})=>e).slice(0,5).join("; ")}`);let a=await (0,t1.getPrismaClient)(),n=await a.$transaction(async t=>{let i=await t.workflowVersion.findFirst({where:{workflowId:e},orderBy:{version:"desc"}}),a=(0,b.randomUUID)(),n=await t.workflowVersion.create({data:{id:a,workflowId:e,version:(i?.version??0)+1,name:r.name,description:r.description,schemaVersion:r.schemaVersion,definitionJson:JSON.stringify(r),contentHash:(0,b.createHash)("sha256").update(o6(r)).digest("hex"),triggers:{create:r.triggers.map(e=>({id:(0,b.randomUUID)(),nodeId:e.id,kind:e.kind,configJson:JSON.stringify(e.config)}))}},include:{triggers:!0}});return await t.workflow.update({where:{id:e},data:{activeVersionId:a}}),n});return o9(e),n}async setEnabled(e,t){let r=await (0,t1.getPrismaClient)(),i=await r.workflow.findUnique({where:{id:e}});if(!i)throw Error("Workflow not found");if(t&&!i.activeVersionId)throw Error("Publish the workflow before enabling it");return await r.workflow.update({where:{id:e},data:{enabled:t}}),o9(e),this.get(e)}async setQuickAction(e){let t=await (0,t1.getPrismaClient)(),r=[...new Set(e.repositoryIds.map(e=>e.trim()).filter(Boolean))],[i,a]=await Promise.all([t.workflow.findUnique({where:{id:e.id},select:{id:!0}}),t.codebaseRepository.count({where:{id:{in:r}}})]);if(!i)throw Error("Workflow not found");if(a!==r.length)throw Error("One or more repositories were not found");let n=e.quickActionIconKey.trim();if(!iR.WORKFLOW_QUICK_ACTION_KINDS.includes(e.kind))throw Error("Quick action kind is invalid");if("none"!==n&&!v.BUILD_CONFIGURATION_ICON_KEYS.includes(n))throw Error("Quick action icon is invalid");let s=e.quickActionButtonVariant.trim();if(!["default","outline","secondary","destructive"].includes(s))throw Error("Quick action button style is invalid");return await t.$transaction(async t=>{await t.workflow.update({where:{id:e.id},data:{quickActionKind:e.kind,quickActionIconKey:n,quickActionButtonVariant:s}}),await t.workflowQuickActionRepository.deleteMany({where:{workflowId:e.id}}),r.length&&await t.workflowQuickActionRepository.createMany({data:r.map(t=>({workflowId:e.id,repositoryId:t}))})}),o9(e.id),this.get(e.id)}async archive(e,t){let r=await (0,t1.getPrismaClient)();return await r.workflow.update({where:{id:e},data:{archivedAt:t?new Date:null,...t?{enabled:!1}:{}}}),o9(e),this.get(e)}async delete(e){let t=await (0,t1.getPrismaClient)();if(await t.workflowRun.count({where:{workflowId:e}}))throw Error("Archive workflows that have run history instead of deleting them");return await t.workflow.delete({where:{id:e}}),o9(e),!0}export(e,t){return this.exportInternal(e,t)}async exportInternal(e,t){let r=await this.get(e);if(!r)throw Error("Workflow not found");let i=t?r.versions.find(e=>e.id===t):null;if(t&&!i)throw Error("Workflow version not found");let a=(0,iC.parseWorkflowDefinition)(oJ(i?.definitionJson??r.draftDefinitionJson));return{format:"aide.workflow.export",schemaVersion:iC.WORKFLOW_SCHEMA_VERSION,exportedAt:new Date().toISOString(),workflow:{name:i?.name??r.name,description:i?.description??r.description,overlapPolicy:r.overlapPolicy,overlapScope:r.overlapScope,maxConcurrentRuns:r.maxConcurrentRuns,completionNotificationsEnabled:r.completionNotificationsEnabled,exclusiveWorktree:r.exclusiveWorktree,worktreeConcurrency:r.worktreeConcurrency,blocksGitOperations:r.blocksGitOperations,definition:(0,iC.sanitizeWorkflowExportDefinition)(a)}}}async import(e){o8("string"==typeof e.payload?e.payload:JSON.stringify(e.payload),"Workflow import",2097152);let t=o5("string"==typeof e.payload?JSON.parse(e.payload):e.payload,"Workflow import"),r="aide.workflow.export"===t.format,i=r?o5(t.workflow,"Exported workflow"):t,a=(0,iC.parseWorkflowDefinition)(r?i.definition:i);return this.create({name:e.name?.trim()||a.name,description:a.description,definition:{...a,name:e.name?.trim()||a.name},overlapPolicy:"string"==typeof i.overlapPolicy?i.overlapPolicy:"QUEUE",overlapScope:"string"==typeof i.overlapScope?i.overlapScope:!0===i.exclusiveWorktree?"WORKTREE":"GLOBAL",maxConcurrentRuns:"number"==typeof i.maxConcurrentRuns?i.maxConcurrentRuns:1,completionNotificationsEnabled:"boolean"!=typeof i.completionNotificationsEnabled||i.completionNotificationsEnabled,worktreeConcurrency:"string"==typeof i.worktreeConcurrency?i.worktreeConcurrency:!0===i.exclusiveWorktree?"EXCLUSIVE":"NON_EXCLUSIVE",blocksGitOperations:"boolean"==typeof i.blocksGitOperations?i.blocksGitOperations:!0===i.exclusiveWorktree,exclusiveWorktree:"boolean"==typeof i.exclusiveWorktree&&i.exclusiveWorktree})}async runs(e={}){let t=await (0,t1.getPrismaClient)(),r=Math.min(Math.max(e.first??100,1),200),i=Number(e.search),a=e.archive?.toUpperCase()??"ACTIVE",n="ALL"===a?{}:"ARCHIVED"===a?{archivedAt:{not:null}}:{archivedAt:null},s=await t.workflowRun.findMany({where:{...n,...e.workflowId?{workflowId:e.workflowId}:{},...e.status?{status:e.status.toUpperCase()}:{},...Number.isInteger(i)&&i>0?{displayNumber:i}:e.search?.trim()?{workflow:{name:{contains:e.search.trim()}}}:{}},include:{workflow:!0,version:!0,trigger:!0,_count:{select:{attempts:!0,events:!0}}},orderBy:[{createdAt:"desc"},{id:"desc"}],take:r+1,...e.after?{cursor:{id:e.after},skip:1}:{}});return{items:s.slice(0,r),nextCursor:s.length>r?s[r-1].id:null,totalCount:await t.workflowRun.count({where:{...n,...e.workflowId?{workflowId:e.workflowId}:{}}})}}async archiveRuns(e,t){let r=await (0,t1.getPrismaClient)(),i=[...new Set(e)],a=await r.workflowRun.updateMany({where:{id:{in:i}},data:{archivedAt:t?new Date:null}});for(let e of i)o7(e);return a.count}async deleteRuns(e){let t=await (0,t1.getPrismaClient)(),r=[...new Set(e)];if(await t.workflowRun.count({where:{id:{in:r},status:{notIn:["SUCCEEDED","FAILED","CANCELLED"]}}}))throw Error("Cancel runs that have not finished before deleting them");let i=await t.workflowRun.deleteMany({where:{id:{in:r}}});for(let e of r)o7(e);return i.count}async run(e){return(await (0,t1.getPrismaClient)()).workflowRun.findUnique({where:{id:e},include:{workflow:!0,version:!0,trigger:!0,parentRun:!0,childRuns:{orderBy:{createdAt:"asc"}},attempts:{orderBy:[{generation:"asc"},{nodeId:"asc"},{iterationKey:"asc"},{attempt:"asc"}],include:{waits:{orderBy:{createdAt:"asc"}},resourceLinks:{orderBy:{createdAt:"asc"}},questionBatches:{orderBy:{createdAt:"asc"},include:{questions:{orderBy:{position:"asc"},include:{options:{orderBy:{position:"asc"}}}},answerRevisions:{orderBy:{revision:"asc"}},checkpoint:!0}},checkpoints:{orderBy:{createdAt:"asc"}}}},waits:{orderBy:{createdAt:"asc"}},events:{orderBy:{sequence:"asc"}},resourceLinks:{orderBy:{createdAt:"asc"}}}})}async runEvents(e,t=-1,r=500){return(await (0,t1.getPrismaClient)()).workflowRunEvent.findMany({where:{runId:e,sequence:{gt:t}},orderBy:{sequence:"asc"},take:Math.min(Math.max(r,1),1e3)})}async questionBatch(e){return(await (0,t1.getPrismaClient)()).runQuestionBatch.findUnique({where:{id:e},include:{questions:{orderBy:{position:"asc"},include:{options:{orderBy:{position:"asc"}}}},answerRevisions:{orderBy:{revision:"asc"}},checkpoint:!0}})}async jobSecrets(e,t){if(!this.credentials||!this.agentControl)throw Error("Workflow credentials are unavailable");if(this.claimedSecretJobs.has(t))throw Error("Workflow job secrets were already claimed");let r=await this.agentControl.getJob(t);if(!r||r.agentId!==e||"workflow.terminal.run"!==r.kind||"RUNNING"!==r.status)throw Error("Workflow job is not eligible to claim secrets");let i=(0,oN.parseWorkflowTerminalPayload)(oJ(r.payloadJson)),a=new Set(Object.values(t2.CREDENTIAL_KINDS)),n=[];for(let e of i.credentialEnvironment){if(!a.has(e.credential.kind))throw Error("Workflow references an unsupported credential kind");let t=await this.credentials.getText(e.credential);if(null===t)throw Error(`Credential ${e.credential.id} is unavailable`);n.push({name:e.name,value:t})}return this.claimedSecretJobs.add(t),n}async workflowAgentContext(e){let t=await (0,t1.getPrismaClient)(),r=(0,si.getSessionValue)(e,"worktree.id");if("string"==typeof r){let e=await t.worktree.findUnique({where:{id:r},include:{codebase:{include:{agent:!0}}}});if(!e)throw Error("Workflow worktree is unavailable");let i=JSON.parse(e.codebase.agent.capabilitiesJson);return{agentId:e.codebase.agentId,codebaseId:e.codebaseId,worktreeId:e.id,cwd:e.folder,capabilities:Array.isArray(i)?i.filter(e=>"string"==typeof e):[]}}let i=(0,si.getSessionValue)(e,"codebase.id");if("string"!=typeof i)throw Error("Workflow requires a codebase or worktree");let a=await t.codebase.findUnique({where:{id:i},include:{agent:!0}});if(!a)throw Error("Workflow codebase is unavailable");let n=JSON.parse(a.agent.capabilitiesJson);return{agentId:a.agentId,codebaseId:a.id,worktreeId:null,cwd:a.folder,capabilities:Array.isArray(n)?n.filter(e=>"string"==typeof e):[]}}async startTerminalJob(e){if(!this.agentControl)throw Error("Agent control is unavailable");let t=await this.workflowAgentContext(e.sessionData);if(!t.capabilities.includes(oN.WORKFLOW_TERMINAL_JOB_KIND))throw Error("The selected agent must be updated to run workflow terminal steps");let r={...e.node.config.environment&&"object"==typeof e.node.config.environment&&!Array.isArray(e.node.config.environment)?Object.fromEntries(Object.entries(e.node.config.environment).map(([e,t])=>[e,String(t)])):{},AIDE_TICKET_KEY:String((0,si.getSessionValue)(e.sessionData,"ticket.key")??""),AIDE_TICKET_TITLE:String((0,si.getSessionValue)(e.sessionData,"ticket.title")??""),AIDE_BRANCH:String((0,si.getSessionValue)(e.sessionData,"worktree.branch")??""),AIDE_BASE_BRANCH:String((0,si.getSessionValue)(e.sessionData,"worktree.baseBranch")??""),AIDE_WORKTREE_PATH:String((0,si.getSessionValue)(e.sessionData,"worktree.path")??t.cwd),AIDE_CODEBASE_PATH:String((0,si.getSessionValue)(e.sessionData,"codebase.folder")??t.cwd),AIDE_REPO_ORIGIN:String((0,si.getSessionValue)(e.sessionData,"repo.displayOrigin")??"")},i=Array.isArray(e.node.config.credentials)?e.node.config.credentials:[],a=await this.agentControl.createJob({agentId:t.agentId,kind:oN.WORKFLOW_TERMINAL_JOB_KIND,payload:{workflowRunId:e.run.id,stepAttemptId:e.attempt.id,stepId:e.node.id,codebaseId:t.codebaseId,worktreeId:t.worktreeId,cwd:t.cwd,script:oZ(String(e.node.config.script??""),"Terminal script",1e6),interpreter:"NODE"===e.node.config.interpreter?"NODE":"SHELL",sessionData:e.sessionData,environment:r,credentialEnvironment:i},idempotencyKey:e.attempt.idempotencyKey,timeoutSeconds:Number(e.node.config.timeoutSeconds??900),codebaseId:t.codebaseId,worktreeId:t.worktreeId,visibility:"SYSTEM",blocksGitOperations:e.run.blocksGitOperations});return{output:{jobId:a.id},links:[{kind:"AGENT_JOB",resourceId:a.id,label:"Workflow terminal job",url:`/jobs/${a.id}`}],wait:{kind:"AGENT_JOB",externalKey:a.id,resumeAfter:s6(e.node.config),timeoutAt:s3(e.node.config,900)}}}async startCheckpointJob(e){if(!this.agentControl)throw Error("Agent control is unavailable");let t=await this.workflowAgentContext(e.sessionData);if(!t.capabilities.includes(oN.WORKFLOW_GIT_CHECKPOINT_JOB_KIND))throw Error("The selected agent must be updated to capture workflow checkpoints");let r=await this.agentControl.createJob({agentId:t.agentId,kind:oN.WORKFLOW_GIT_CHECKPOINT_JOB_KIND,payload:{operation:"CAPTURE",workflowRunId:e.run.id,stepAttemptId:e.attempt.id,cwd:t.cwd,kind:String(e.node.config.kind??"STEP"),checkpoint:null,stash:!1},idempotencyKey:e.attempt.idempotencyKey,timeoutSeconds:300,codebaseId:t.codebaseId,worktreeId:t.worktreeId,visibility:"SYSTEM"});return{output:{jobId:r.id},links:[{kind:"AGENT_JOB",resourceId:r.id,label:"Workflow checkpoint job",url:`/jobs/${r.id}`}],wait:{kind:"AGENT_JOB",externalKey:r.id,resumeAfter:s6(e.node.config),timeoutAt:s3(e.node.config)}}}async workflowAgentJobCompleted(e){if(e.kind===oN.WORKFLOW_TERMINAL_JOB_KIND){let t=(0,oN.parseWorkflowTerminalPayload)(oJ(e.payloadJson));if("SUCCEEDED"!==e.status||!e.resultJson)return void await this.resolveExternalWait("AGENT_JOB",e.id,{jobId:e.id,status:e.status},e.error||`Workflow terminal job ${e.status.toLowerCase()}`);let r=o5(oJ(e.resultJson),"Workflow terminal result");return void await this.resolveExternalWait("AGENT_JOB",e.id,{...r,jobId:e.id,stepAttemptId:t.stepAttemptId})}if(e.kind!==oN.WORKFLOW_GIT_CHECKPOINT_JOB_KIND)return;let t=(0,oN.parseWorkflowGitCheckpointPayload)(oJ(e.payloadJson));if("SUCCEEDED"!==e.status||!e.resultJson)return void await this.resolveExternalWait("AGENT_JOB",e.id,{jobId:e.id,status:e.status},e.error||`Workflow checkpoint job ${e.status.toLowerCase()}`);let r=o5(oJ(e.resultJson),"Workflow checkpoint result"),i=null;if(r.checkpoint&&"object"==typeof r.checkpoint){let e=r.checkpoint,a=await (0,t1.getPrismaClient)();i=(0,b.randomUUID)(),await a.$transaction([a.runCheckpoint.create({data:{id:i,workflowStepAttemptId:t.stepAttemptId,kind:String(e.kind??t.kind),headSha:"string"==typeof e.headSha?e.headSha:null,branch:"string"==typeof e.branch?e.branch:null,upstreamSha:"string"==typeof e.upstreamSha?e.upstreamSha:null,indexTree:"string"==typeof e.indexTree?e.indexTree:null,worktreeTree:"string"==typeof e.worktreeTree?e.worktreeTree:null,refName:"string"==typeof e.refName?e.refName:null,manifestJson:"string"==typeof e.manifestJson?e.manifestJson:null,diffSummary:"string"==typeof e.diffSummary?e.diffSummary:null,diffPatch:"string"==typeof e.diffPatch?e.diffPatch:null,stashRef:"string"==typeof r.stashRef?r.stashRef:"string"==typeof e.stashRef?e.stashRef:null}}),a.workflowRunResourceLink.create({data:{id:(0,b.randomUUID)(),runId:t.workflowRunId,attemptId:t.stepAttemptId,kind:"CHECKPOINT",resourceId:i,label:`${String(e.kind??t.kind)} checkpoint`}})])}await this.resolveExternalWait("AGENT_JOB",e.id,{...r,jobId:e.id,checkpointId:i})}async genericAgentJobCompleted(e){if(e.kind===oN.WORKFLOW_TERMINAL_JOB_KIND||e.kind===oN.WORKFLOW_GIT_CHECKPOINT_JOB_KIND)return;let t=e.resultJson?o5(oJ(e.resultJson),"Agent job result"):{status:e.status};if("SUCCEEDED"===e.status){let r=await (0,t1.getPrismaClient)(),i=t.worktree&&"object"==typeof t.worktree&&!Array.isArray(t.worktree)?t.worktree:null,a=i&&"string"==typeof i.gitDirectory?i.gitDirectory:null,n=e.codebaseId?await r.worktree.findFirst({where:{codebaseId:e.codebaseId,...e.worktreeId?{id:e.worktreeId}:a?{gitDirectory:a}:{id:"__missing__"}},include:{codebase:{include:{repository:!0,agent:!0}}}}):null,s=n?.codebase??(e.codebaseId?await r.codebase.findUnique({where:{id:e.codebaseId},include:{repository:!0,agent:!0}}):null),o={};if(n&&this.worktrees?.workflowSessionDataForWorktree)try{o=await this.worktrees.workflowSessionDataForWorktree(n.id,{includeMissing:!0})}catch{}if(s&&!o.codebase&&(o.repo={id:s.repository.id,name:s.repository.name,url:s.repository.displayOrigin,canonicalOrigin:s.repository.canonicalOrigin,displayOrigin:s.repository.displayOrigin,defaultBranch:s.defaultBranch},o.codebase={id:s.id,folder:s.folder,agentId:s.agentId,branch:s.defaultBranch,headSha:s.headSha},o.agent={id:s.agent.id,name:s.agent.name,hostname:s.agent.hostname}),n&&!o.worktree&&(o.worktree={id:n.id,path:n.folder,branch:n.branch,baseBranch:n.baseBranchOverride??n.codebase.defaultBranch,headSha:n.headSha,pushStatus:n.pushStatus,ahead:n.ahead,behind:n.behind,baseBehind:n.baseBehind,dirty:n.hasStagedChanges||n.hasUnstagedChanges}),Object.keys(o).length){let e=t.sessionPatch&&"object"==typeof t.sessionPatch&&!Array.isArray(t.sessionPatch)?t.sessionPatch:{};t={...t,sessionPatch:(0,si.mergeSessionData)(e,o)}}}await this.resolveExternalWait("AGENT_JOB",e.id,{...t,jobId:e.id,status:e.status},"SUCCEEDED"===e.status?null:e.error||`Agent job ${e.status.toLowerCase()}`)}async restoreCheckpointWithAgent(e,t){if(!this.agentControl)throw Error("Agent control is unavailable");let r=await (0,t1.getPrismaClient)(),i=await r.runCheckpoint.findUnique({where:{id:e},include:{workflowStepAttempt:{include:{run:!0}}}}),a=i?.workflowStepAttempt;if(!i||!a)throw Error("Workflow checkpoint not found");let n=await this.workflowAgentContext((0,si.workflowSessionData)(a.run.sessionDataJson)),s=await this.agentControl.createJob({agentId:n.agentId,kind:oN.WORKFLOW_GIT_CHECKPOINT_JOB_KIND,payload:{operation:"RESTORE",workflowRunId:a.runId,stepAttemptId:a.id,cwd:n.cwd,kind:"REPLAY_RESTORE",checkpoint:{headSha:i.headSha,branch:i.branch,upstreamSha:i.upstreamSha,indexTree:i.indexTree,worktreeTree:i.worktreeTree,refName:i.refName},stash:t.stash},idempotencyKey:`workflow:restore:${e}:${(0,b.randomUUID)()}`,timeoutSeconds:300,codebaseId:n.codebaseId,worktreeId:n.worktreeId,visibility:"SYSTEM"}),o=Date.now()+3e5;for(;Date.now()<o;){let e=await this.agentControl.getJob(s.id);if(!e)throw Error("Workflow restore job disappeared");if(new Set(["SUCCEEDED","FAILED","CANCELLED","TIMED_OUT"]).has(e.status)){if("SUCCEEDED"!==e.status)throw Error(e.error||`Workflow restore job ${e.status.toLowerCase()}`);return}await new Promise(e=>setTimeout(e,250))}throw await this.agentControl.cancelJob(s.id),Error("Workflow restore job timed out")}async compareCheckpointWithAgent(e){if(!this.agentControl)throw Error("Agent control is unavailable");let t=await (0,t1.getPrismaClient)(),r=await t.runCheckpoint.findUnique({where:{id:e},include:{workflowStepAttempt:{include:{run:!0}}}}),i=r?.workflowStepAttempt;if(!r||!i)throw Error("Workflow checkpoint not found");let a=await this.workflowAgentContext((0,si.workflowSessionData)(i.run.sessionDataJson)),n=await this.agentControl.createJob({agentId:a.agentId,kind:oN.WORKFLOW_GIT_CHECKPOINT_JOB_KIND,payload:{operation:"COMPARE",workflowRunId:i.runId,stepAttemptId:i.id,cwd:a.cwd,kind:"REPLAY_PREVIEW",checkpoint:{headSha:r.headSha,branch:r.branch,upstreamSha:r.upstreamSha,indexTree:r.indexTree,worktreeTree:r.worktreeTree,refName:r.refName},stash:!1},idempotencyKey:`workflow:compare:${e}:${(0,b.randomUUID)()}`,timeoutSeconds:60,codebaseId:a.codebaseId,worktreeId:a.worktreeId,visibility:"SYSTEM"}),s=Date.now()+6e4;for(;Date.now()<s;){let e=await this.agentControl.getJob(n.id);if(!e)throw Error("Workflow comparison job disappeared");if(new Set(["SUCCEEDED","FAILED","CANCELLED","TIMED_OUT"]).has(e.status)){if("SUCCEEDED"!==e.status||!e.resultJson)throw Error(e.error||`Workflow comparison job ${e.status.toLowerCase()}`);let t=o5(oJ(e.resultJson),"Workflow comparison result");return o5(t.comparison,"Git checkpoint comparison")}await new Promise(e=>setTimeout(e,250))}throw await this.agentControl.cancelJob(n.id),Error("Workflow comparison job timed out")}async runsForResource(e,t){let r=await (0,t1.getPrismaClient)(),i=await r.workflowRunResourceLink.findMany({where:{kind:e.trim().toUpperCase(),resourceId:t.trim()},select:{runId:!0},distinct:["runId"],orderBy:{createdAt:"desc"}});return r.workflowRun.findMany({where:{id:{in:i.map(({runId:e})=>e)}},include:{workflow:!0,version:!0,trigger:!0,attempts:{orderBy:[{generation:"asc"},{createdAt:"asc"}],include:{resourceLinks:{orderBy:{createdAt:"asc"}},questionBatches:{orderBy:{createdAt:"asc"},include:{questions:{orderBy:{position:"asc"},include:{options:{orderBy:{position:"asc"}}}}}}}},resourceLinks:{orderBy:{createdAt:"asc"}}},orderBy:{createdAt:"desc"}})}async acceptingResource(e){let t=e.trim().toUpperCase(),r=await (0,t1.getPrismaClient)();return(await r.workflow.findMany({where:{enabled:!0,archivedAt:null,activeVersionId:{not:null}},include:{activeVersion:!0},orderBy:{name:"asc"}})).filter(e=>!!e.activeVersion&&(0,iC.parseWorkflowDefinition)(oJ(e.activeVersion.definitionJson)).triggers.some(e=>(0,iR.isResourceTriggerKind)(e.kind)&&(0,iC.workflowResourceKind)(e.config)===t))}async quickActions(e){let t=await (0,t1.getPrismaClient)();if(!iR.WORKFLOW_QUICK_ACTION_KINDS.includes(e.kind))throw Error("Quick action kind is invalid");let r=e.resourceKind.trim().toUpperCase(),i=e.repositoryId?.trim()||null;return(await t.workflow.findMany({where:{enabled:!0,archivedAt:null,activeVersionId:{not:null},quickActionKind:e.kind,OR:[{quickActionRepositories:{none:{}}},{quickActionRepositories:{some:{repositoryId:i??""}}}]},include:{activeVersion:!0},orderBy:[{name:"asc"},{id:"asc"}]})).filter(e=>!!e.activeVersion&&(0,iC.parseWorkflowDefinition)(oJ(e.activeVersion.definitionJson)).triggers.some(e=>(0,iR.isResourceTriggerKind)(e.kind)&&(0,iC.workflowResourceKind)(e.config)===r))}async recordEvent(e){return this.events.record(e)}async hydrateResourceSessionData(e,t,r){let i=e?.toUpperCase()??null,a=await (0,t1.getPrismaClient)(),n={},s=null;if("CODEBASE"===i&&t){let e=await a.codebase.findUnique({where:{id:t},select:{id:!0,folder:!0,agentId:!0,branch:!0,headSha:!0,defaultBranch:!0,agent:{select:{id:!0,name:!0,hostname:!0,lastSeenAt:!0,disconnectedAt:!0,heartbeatIntervalSeconds:!0,diskFreeBytes:!0,memoryFreeBytes:!0}},repository:{select:{id:!0,name:!0,canonicalOrigin:!0,displayOrigin:!0}}}});e&&(n=oY(e))}if("BUILD"===i&&t){let e=await a.build.findUnique({where:{id:t},select:{id:!0,status:!0,action:!0,error:!0,artifactDirectory:!0,worktreeId:!0,agent:{select:{id:!0,name:!0,hostname:!0,lastSeenAt:!0,disconnectedAt:!0,heartbeatIntervalSeconds:!0,diskFreeBytes:!0,memoryFreeBytes:!0}},codebase:{select:{id:!0,folder:!0,agentId:!0,branch:!0,headSha:!0,defaultBranch:!0,agent:{select:{id:!0,name:!0,hostname:!0,lastSeenAt:!0,disconnectedAt:!0,heartbeatIntervalSeconds:!0,diskFreeBytes:!0,memoryFreeBytes:!0}},repository:{select:{id:!0,name:!0,canonicalOrigin:!0,displayOrigin:!0}}}},artifacts:{select:{id:!0,kind:!0,relativePath:!0,sizeBytes:!0,checksum:!0}},reports:{where:{status:"READY"},select:{kind:!0,summaryJson:!0}}}});if(e){s=e.worktreeId;let t=t=>{let r=e.reports.find(e=>e.kind===t);if(r)try{return(0,si.workflowSessionData)(r.summaryJson)}catch{return}},r=t("TEST_RESULTS"),i=t("CODE_COVERAGE");n=(0,si.mergeSessionData)(e.codebase?oY(e.codebase):e.agent?oz(e.agent):{},{build:{id:e.id,status:e.status,action:e.action,error:e.error,artifactDirectory:e.artifactDirectory,artifacts:e.artifacts,...r?{testSummary:r}:{},...i?{coverageSummary:i}:{}}})}}if("AGENT_RUN"===i&&t){let e=await a.agentRun.findUnique({where:{id:t},select:{id:!0,kind:!0,status:!0,phase:!0,origin:!0,provider:!0,model:!0,branch:!0,finalOutput:!0,error:!0,jiraIssueKey:!0,worktreeId:!0,agent:{select:{id:!0,name:!0,hostname:!0,disconnectedAt:!0,diskFreeBytes:!0,memoryFreeBytes:!0}},inputTokens:!0,outputTokens:!0,reasoningTokens:!0,cacheReadTokens:!0,cacheWriteTokens:!0,toolCallCount:!0,estimatedCost:!0}});e&&(s=e.worktreeId,n=(0,si.mergeSessionData)(e.agent?oz(e.agent):{},{run:{id:e.id,kind:e.kind,status:e.status,phase:e.phase,origin:e.origin,provider:e.provider,model:e.model,branch:e.branch,finalOutput:e.finalOutput,error:e.error,usage:{inputTokens:e.inputTokens,outputTokens:e.outputTokens,reasoningTokens:e.reasoningTokens,cacheReadTokens:e.cacheReadTokens,cacheWriteTokens:e.cacheWriteTokens,toolCallCount:e.toolCallCount,estimatedCost:e.estimatedCost}},...e.jiraIssueKey?{ticket:{key:e.jiraIssueKey}}:{}}))}if("PULL_REQUEST"===i&&t&&this.worktrees?.workflowSessionDataForPullRequest){let e=/^([^/]+)\/([^#]+)#([1-9]\d*)$/.exec(t);e&&(n=(0,si.mergeSessionData)(n,await this.worktrees.workflowSessionDataForPullRequest(e[1],e[2],Number(e[3]))))}if("JIRA_TICKET"===i&&t&&this.jiraService)try{let e=await this.jiraService.ticket(t),r=e.comments.at(-1)??null;n=(0,si.mergeSessionData)(n,{ticket:{...e,title:e.summary,type:e.issueType,url:e.jiraUrl},...r?{comment:{id:r.id,body:r.content?.rawText??"",author:r.author}}:{}})}catch{}let o=(0,si.getSessionValue)(r,"worktree.id"),l="WORKTREE"===i?t:"GITHUB_PIPELINE"===i||"GITHUB_JOB"===i?"string"==typeof o?o:null:s;if(l&&this.worktrees)if(this.worktrees.workflowSessionDataForWorktree)n=(0,si.mergeSessionData)(await this.worktrees.workflowSessionDataForWorktree(l),n);else{let e=await this.worktrees.ticketKeyForWorktree(l);e&&(n=(0,si.mergeSessionData)({ticket:{key:e}},n))}let c=(0,si.getSessionValue)(r,"pipeline.pullRequests");!(0,si.getSessionValue)(n,"pr")&&!(0,si.getSessionValue)(r,"pr")&&Array.isArray(c)&&c[0]&&"object"==typeof c[0]&&!Array.isArray(c[0])&&(n=(0,si.mergeSessionData)(n,{pr:c[0]}));let u=(0,si.getSessionValue)(r,"pr.jiraKey")??(0,si.getSessionValue)(r,"pipeline.jiraKey");return"string"!=typeof(0,si.getSessionValue)(n,"ticket.key")&&"string"==typeof u&&u.trim()&&(n=(0,si.mergeSessionData)(n,{ticket:{key:u}})),(0,si.mergeSessionData)(n,r)}async trigger(e){let t=await (0,t1.getPrismaClient)(),r=await t.workflow.findUnique({where:{id:e.workflowId},include:{activeVersion:{include:{triggers:!0}}}});if(!r?.activeVersion)throw Error("Published workflow not found");if(!r.enabled||r.archivedAt)throw Error("Workflow is paused");let i=e.resourceKind?.toUpperCase()??null,a=e.choice?.trim()||null,{triggers:n}=r.activeVersion,s=i?"RESOURCE_MANUAL":"MANUAL",o=i?"RESOURCE_MANUAL_CHOICE":"MANUAL_CHOICE",l=e=>n.find(t=>t.kind===e&&(!i||(0,iC.workflowResourceKind)(o5(oJ(t.configJson),"Trigger configuration"))===i))??null,c=l(o),u=l(s),d=a?c:u;if(a&&!c)throw Error(i?`No resource trigger offers choices for ${i} resources`:"This workflow has no manual trigger with choices");if(!a&&!u&&c){let e=(0,iC.workflowTriggerChoices)(o5(oJ(c.configJson),"Trigger configuration"));throw Error(`This workflow needs a choice: ${e.map(({key:e})=>e).join(", ")}`)}if(i&&!d)throw Error(`No resource trigger accepts ${e.resourceKind} resources`);if(a&&c&&!(0,iC.workflowTriggerChoices)(o5(oJ(c.configJson),"Trigger configuration")).some(({key:e})=>e===a))throw Error(`Unknown choice ${a}`);let p=e.subjectKey?.trim()||(i&&e.resourceId?`${i}:${e.resourceId}`:`manual:${(0,b.randomUUID)()}`),h={sessionData:await this.hydrateResourceSessionData(e.resourceKind,e.resourceId,e.sessionData??{}),resourceKind:e.resourceKind??null,resourceId:e.resourceId??null,choice:a,manual:!0},m=await this.createRunForTrigger(r,r.activeVersion,d,null,a?o:s,p,h,`manual:${r.id}:${(0,b.randomUUID)()}`);return o7(m.id),this.run(m.id)}async createRunForTrigger(e,t,r,i,a,n,s,o,l=null,c=null){return(await (0,t1.getPrismaClient)()).$transaction(async u=>{if(c){let e=await u.workflowTriggerDelivery.findUnique({where:{id:c},include:{run:!0}});if(e)return e.run}let d=async e=>(c&&await u.workflowTriggerDelivery.create({data:{id:c,runId:e.id}}),e),p=await u.workflowRun.findUnique({where:{idempotencyKey:o}});if(p)return d(p);let h=o5(s.sessionData??{},"Session data"),m=(0,si.getSessionValue)(h,"worktree.id"),f="string"==typeof m&&m?(await u.worktree.findUnique({where:{id:m},select:{id:!0}}))?.id??null:null;if("COALESCE_LATEST"===e.overlapPolicy){let t=await u.workflowRun.findFirst({where:{workflowId:e.id,triggerSubjectKey:n,status:"QUEUED",...o3(e.overlapScope,f)},orderBy:{queuedAt:"desc"}});if(t)return d(await u.workflowRun.update({where:{id:t.id},data:{triggerId:r?.id??null,triggerEventId:i,triggerKind:a,triggerPayloadJson:JSON.stringify(s),queuedAt:new Date}}))}let g=(0,b.randomUUID)(),y=JSON.stringify((0,si.mergeSessionData)({workflow:{id:e.id,name:t.name,runId:g,startedAt:null,trigger:{id:r?.nodeId??null,kind:a,subjectKey:n,choice:"string"==typeof s.choice?s.choice:null}},steps:{}},h));o8(y,"Workflow session data",2097152);let w=l?await u.workflowRun.findUnique({where:{id:l},select:{worktreeId:!0,worktreeLeaseOwnerRunId:!0}}):null,v=(w?.worktreeId===f?w.worktreeLeaseOwnerRunId:null)??(!l&&"EXCLUSIVE"===e.worktreeConcurrency&&f?g:null),k=await u.workflowRun.create({data:{id:g,displayNumber:await lr(u),workflowId:e.id,versionId:t.id,triggerId:r?.id??null,triggerEventId:i,parentRunId:l,worktreeId:f,worktreeLeaseOwnerRunId:v,exclusiveWorktree:"EXCLUSIVE"===e.worktreeConcurrency,worktreeConcurrency:e.worktreeConcurrency,blocksGitOperations:e.blocksGitOperations,idempotencyKey:o,triggerKind:a,triggerSubjectKey:n,triggerPayloadJson:JSON.stringify(s),sessionDataJson:y,phase:v?"WAITING_FOR_WORKTREE":"QUEUED"}}),E=function(e,t){let r=e.trim().toUpperCase(),i=sG(t.sessionData);if((0,iR.isResourceTriggerKind)(r)){let e=t.resourceKind,r="string"==typeof e?e.toUpperCase():null,a="GITHUB_JOB"===r?sK(i,"job","url"):"GITLAB_JOB"===r?sK(i,"job","webUrl"):"GITHUB_PIPELINE"===r?sK(i,"pipeline","url"):"GITLAB_PIPELINE"===r?sK(i,"pipeline","webUrl"):"GITLAB_MERGE_REQUEST"===r?sK(i,"pr","webUrl"):null;return"string"==typeof e?sH(e.toUpperCase(),t.resourceId,{url:"string"==typeof a?a:null,metadata:"AGENT_RUN"===e.toUpperCase()?{runKind:sK(i,"run","kind")}:null}):null}if(sV.has(r))return sH("JIRA_TICKET",sK(i,"ticket","key"));if(sW.has(r))return sH("AGENT_RUN",sK(i,"run","id"),{metadata:{runKind:sK(i,"run","kind")}});if(sJ.has(r))return sH("BUILD",sK(i,"build","id"));if(sz.has(r))return sH("WORKTREE",sK(i,"worktree","id"));if("CODEBASE_REMOTE_BRANCH"===r||"CODEBASE_SYNC_STATE_CHANGED"===r||"CODEBASE_OPERATION_FAILED"===r)return sH("CODEBASE",sK(i,"codebase","id"));if("COMMAND_RUN_RESULT"===r||"COMMAND_OUTPUT_MATCH"===r)return sH("COMMAND_RUN",sK(i,"command","id"));if("SKILL_SYNC_RESULT"===r||"SKILL_SYNC_CONFLICT"===r)return sH("SKILL_SYNC",sK(i,"skillSync","id"));if("IOS_DEVICE_ENROLLED"===r||"IOS_DEVICE_REGISTRATION_RESULT"===r)return sH("IOS_DEVICE",sK(i,"device","id"));if("SIGNING_OPERATION_RESULT"===r||"SIGNING_ASSET_EXPIRING"===r)return sH("SIGNING_PROFILE",sK(i,"signingProfile","id"));if("PUSH_NOTIFICATION_RESULT"===r)return sH("PUSH_NOTIFICATION_BATCH",sK(i,"pushBatch","id"));if("BUILD_DATA_THRESHOLD"===r||"BUILD_DATA_CLEANUP_RESULT"===r)return sH("BUILD_DATA_COLLECTION",sK(i,"buildData","id"));if("AGENT_JOB_FAILED"===r)return sH("AGENT_JOB",sK(sG(i.steps),"trigger","id"));if("AGENT_CONNECTION"===r||"AGENT_DISK_REPORT"===r||"AGENT_DISK_THRESHOLD"===r||"AGENT_DISK_STATE_CHANGED"===r||"AGENT_DISK_CLEANUP_RESULT"===r||"CCUSAGE_THRESHOLD"===r)return sH("AGENT",sK(i,"agent","id")??sK(i,"codebase","agentId"));if("WORKFLOW_FINISHED"===r)return sH("WORKFLOW_RUN",sK(t,"run","id"));if(sY.has(r)){let e=function(e){if("string"!=typeof e)return null;let t=e.trim(),r=t.match(/(?:https?:\/\/|ssh:\/\/git@|git@)?github\.com[/:]([^/]+)\/([^/#]+?)(?:\.git)?$/i)??t.match(/^([^/:]+)\/([^/#]+?)(?:\.git)?$/);return r?.[1]&&r[2]?{owner:r[1],repository:r[2]}:null}(sK(i,"repo","displayOrigin")),t=Number(sK(i,"pr","number"));return e&&Number.isInteger(t)&&t>0?sH("PULL_REQUEST",sF(e.owner,e.repository,t)):null}if(sZ.has(r)){let e=sK(i,"pipeline","url");return sH("GITHUB_WORKFLOW_RUN",sK(i,"pipeline","runId"),{url:"string"==typeof e?e:null})}return"GITHUB_PUSH_DEFAULT"===r?sH("CODEBASE_REPOSITORY",sK(i,"repo","id")):null}(a,s);return E&&await u.workflowRunResourceLink.create({data:{id:(0,b.randomUUID)(),runId:k.id,kind:E.kind.toUpperCase(),resourceId:E.resourceId,label:E.label??null,url:E.url??null,metadataJson:E.metadata?JSON.stringify(E.metadata):null}}),d(k)})}async processTriggerEvents(){let e=await (0,t1.getPrismaClient)(),t=await e.workflowTriggerEvent.findMany({where:{status:"PENDING"},orderBy:{receivedAt:"asc"},take:50});if(!t.length)return;let r=await e.workflow.findMany({where:{enabled:!0,archivedAt:null,activeVersionId:{not:null}},include:{activeVersion:{include:{triggers:!0}}}});for(let s of t)try{let t=o5(oJ(s.payloadJson),"Trigger payload");for(let o of r)if(o.activeVersion)for(let r of o.activeVersion.triggers.filter(({kind:e})=>e===s.kind)){var i,a,n;if(t.workflowCorrelation&&"object"==typeof t.workflowCorrelation&&t.workflowCorrelation.workflowId===o.id)continue;let l=(i=s.dedupeKey,a=o.id,n=r.nodeId,(0,b.createHash)("sha256").update(JSON.stringify([i,a,n])).digest("hex"));if(await e.workflowTriggerDelivery.findUnique({where:{id:l},select:{id:!0}})||!await this.triggerMatches(r,s.subjectKey,t))continue;let c=await this.createRunForTrigger({...o,activeVersion:o.activeVersion},o.activeVersion,r,s.id,s.kind,s.subjectKey,t,l,null,l);o7(c.id)}await e.workflowTriggerEvent.update({where:{id:s.id},data:{status:"PROCESSED",processedAt:new Date,error:null}})}catch(t){await e.workflowTriggerEvent.update({where:{id:s.id},data:{status:"FAILED",processedAt:new Date,error:t instanceof Error?t.message:String(t)}})}}async triggerMatches(e,t,r){let i,a=(0,si.resolveWorkflowValue)(o5(oJ(e.configJson),"Trigger configuration"),r),n=null;if(void 0!==r.cursorValue&&("string"!=typeof a.thresholdPath||"string"!=typeof a.thresholdOperator)){let a=await (0,t1.getPrismaClient)(),s=await a.workflowTriggerState.findUnique({where:{triggerId_subjectKey:{triggerId:e.id,subjectKey:t}}});if(n=o6(i=s?.cursorJson?o5(oJ(s.cursorJson),"Trigger cursor").value:void 0)!==o6(r.cursorValue),"WORKTREE_CLEAN"===e.kind&&(n=!0===i&&!1===r.cursorValue),"JIRA_SPRINT_STARTED"===e.kind||"JIRA_SPRINT_ENDED"===e.kind){let e=Array.isArray(i)?i:null,t=Array.isArray(r.cursorValue)?r.cursorValue:null;n=null!==e&&null!==t&&t.some(t=>!e.some(e=>o6(e)===o6(t)))}await a.workflowTriggerState.upsert({where:{triggerId_subjectKey:{triggerId:e.id,subjectKey:t}},create:{id:(0,b.randomUUID)(),triggerId:e.id,subjectKey:t,cursorJson:JSON.stringify({value:r.cursorValue}),lastMatched:n,...n?{lastFiredAt:new Date}:{}},update:{cursorJson:JSON.stringify({value:r.cursorValue}),lastMatched:n,...n?{lastFiredAt:new Date}:{}}})}if("GITHUB_ISSUE_COMMAND"===e.kind){let e=(0,si.getSessionValue)(r,"comment.author.login"),t=(0,si.getSessionValue)(r,"comment.body"),i=Array.isArray(a.allowedLogins)?a.allowedLogins:[];if("string"!=typeof e||!i.includes(e)||"string"!=typeof t||"string"!=typeof a.commandPattern||!(0,sX.compileRe2)(a.commandPattern,{label:"GitHub issue command pattern"}).test(t))return!1}if("GITLAB_NOTE_COMMAND"===e.kind){let e=(0,si.getSessionValue)(r,"comment.author.username"),t=(0,si.getSessionValue)(r,"comment.body"),i=Array.isArray(a.allowedUsernames)?a.allowedUsernames:[];if("string"!=typeof e||!i.includes(e)||"string"!=typeof t||"string"!=typeof a.commandPattern||!(0,sX.compileRe2)(a.commandPattern,{label:"GitLab note command pattern"}).test(t))return!1}if("JIRA_ISSUE_COMMAND"===e.kind){let e=(0,si.getSessionValue)(r,"comment.author.accountId"),t=(0,si.getSessionValue)(r,"comment.body"),i=Array.isArray(a.allowedAccountIds)?a.allowedAccountIds:[];if("string"!=typeof e||!i.includes(e)||"string"!=typeof t||"string"!=typeof a.commandPattern||!(0,sX.compileRe2)(a.commandPattern,{label:"Jira issue command pattern"}).test(t))return!1}if("COMMAND_OUTPUT_MATCH"===e.kind){let e=(0,si.getSessionValue)(r,"output.data");if("string"!=typeof e||"string"!=typeof a.outputPattern||!(0,sX.compileRe2)(a.outputPattern,{label:"Command output trigger pattern"}).test(e))return!1}if("WORKTREE_CONFLICT"===e.kind&&!0!==(0,si.getSessionValue)(r,"worktree.conflicted")||"WORKTREE_MISSING"===e.kind&&null==(0,si.getSessionValue)(r,"worktree.missingAt")||"WORKTREE_DIVERGED"===e.kind&&"DIVERGED"!==(0,si.getSessionValue)(r,"worktree.pushStatus"))return!1;if(a.filters&&"object"==typeof a.filters)for(let[e,t]of Object.entries(a.filters)){let i=(0,si.getSessionValue)(r,e);if(Array.isArray(t)){if(!t.some(e=>o6(e)===o6(i)))return!1}else if(o6(t)!==o6(i))return!1}if("string"==typeof a.thresholdPath&&"string"==typeof a.thresholdOperator){let i=oT({op:a.thresholdOperator,left:{source:"SESSION",path:a.thresholdPath},right:a.thresholdValue},r),n=await (0,t1.getPrismaClient)(),s=await n.workflowTriggerState.findUnique({where:{triggerId_subjectKey:{triggerId:e.id,subjectKey:t}}});return await n.workflowTriggerState.upsert({where:{triggerId_subjectKey:{triggerId:e.id,subjectKey:t}},create:{id:(0,b.randomUUID)(),triggerId:e.id,subjectKey:t,lastMatched:i,cursorJson:JSON.stringify({value:(0,si.getSessionValue)(r,a.thresholdPath)}),...i?{lastFiredAt:new Date}:{}},update:{lastMatched:i,cursorJson:JSON.stringify({value:(0,si.getSessionValue)(r,a.thresholdPath)}),...i&&!s?.lastMatched?{lastFiredAt:new Date}:{}}}),i&&!s?.lastMatched}return n??!0}async processSchedules(){let e=await (0,t1.getPrismaClient)(),t=await e.workflow.findMany({where:{enabled:!0,archivedAt:null,activeVersionId:{not:null}},include:{activeVersion:{include:{triggers:{where:{kind:"SCHEDULE"},include:{states:!0}}}}}}),r=new Date;for(let i of t)for(let t of i.activeVersion?.triggers??[]){let a=o5(oJ(t.configJson),"Schedule configuration"),n=Number(a.cadenceSeconds);if(!Number.isInteger(n)||n<1)continue;let s=i.id,o=t.states.find(e=>e.subjectKey===s);if(!o){let i="string"==typeof a.firstRunAt?new Date(a.firstRunAt):null,l=i&&Number.isFinite(i.getTime())?i:new Date(r.getTime()+1e3*n);o=await e.workflowTriggerState.create({data:{id:(0,b.randomUUID)(),triggerId:t.id,subjectKey:s,nextScheduledAt:l}})}if(!o.nextScheduledAt||o.nextScheduledAt>r)continue;let l=o.nextScheduledAt,c=new Date(Math.max(r.getTime(),l.getTime())+1e3*n);await e.workflowTriggerState.update({where:{id:o.id},data:{lastFiredAt:r,nextScheduledAt:c}}),await this.events.record({kind:"SCHEDULE",subjectKey:s,dedupeKey:`schedule:${t.id}:${l.toISOString()}`,payload:{sessionData:{},scheduledFor:l.toISOString(),cadenceSeconds:n}})}}async lifecycle(e,t){let r=await (0,t1.getPrismaClient)(),i=await r.workflowRun.findUnique({where:{id:e}});if(!i)throw Error("Workflow run not found");if("PAUSE"===t){if(!new Set(["RUNNING","WAITING","BLOCKED"]).has(i.status))throw Error("Only an active workflow run can be paused");if(!await r.$transaction(async t=>!!(await t.workflowRun.updateMany({where:{id:e,status:{in:["RUNNING","WAITING","BLOCKED"]}},data:{status:"PAUSING",phase:"DRAINING"}})).count&&(await t.workflowStepAttempt.updateMany({where:{runId:e,status:"READY"},data:{status:"PENDING",phase:"PAUSED_PENDING"}}),!0)))return this.run(e);await this.controlLinkedAgentRuns(e,"PAUSE"),await this.appendEvent(e,null,"RUN_PAUSING","Workflow pause requested")}else if("RESUME"===t){if("PAUSED"!==i.status)throw Error("Only a paused workflow run can be resumed");if(!(await r.workflowRun.updateMany({where:{id:e,status:"PAUSED"},data:{status:"RUNNING",phase:"SCHEDULING",pausedAt:null}})).count)return this.run(e);await this.controlLinkedAgentRuns(e,"CONTINUE"),await this.appendEvent(e,null,"RUN_RESUMED","Workflow resumed")}else{if(oF.has(i.status))return this.run(e);for(let[t,i]of(await this.controlLinkedAgentRuns(e,"CANCEL"),await this.cancelWaitingCommandRuns(e),this.activeExecutions)){let a=await r.workflowStepAttempt.findUnique({where:{id:t},select:{runId:!0}});a?.runId===e&&i.abort()}if(!await r.$transaction(async t=>!!(await t.workflowRun.updateMany({where:{id:e,status:{notIn:[...oF]}},data:{status:"CANCELLED",phase:"CANCELLED",finishedAt:new Date}})).count&&(await t.workflowStepAttempt.updateMany({where:{runId:e,status:{notIn:[...oG]}},data:{status:"CANCELLED",phase:"CANCELLED",finishedAt:new Date,claimOwner:null,claimExpiresAt:null}}),await t.workflowWait.updateMany({where:{runId:e,status:"PENDING"},data:{status:"CANCELLED",resolvedAt:new Date}}),await t.workflowResourceLease.deleteMany({where:{runId:e}}),await t.worktreeWorkflowLease.deleteMany({where:{workflowRunId:e}}),!0)))return this.run(e);await this.appendEvent(e,null,"RUN_CANCELLED","Workflow cancelled"),await this.promoteWorktreeAdmissions(i.worktreeId)}return o7(e),this.run(e)}async repairRunData(e,t){let r=o5(t,"Session data patch"),i=await (0,t1.getPrismaClient)(),a=await i.workflowRun.findUnique({where:{id:e}});if(!a)throw Error("Workflow run not found");if(!new Set(["BLOCKED","PAUSED"]).has(a.status))throw Error("Only blocked or paused workflows accept repair data");let n=(0,si.workflowSessionData)(a.sessionDataJson),s=(0,si.getSessionValue)(n,"workflow"),o=(0,si.mergeSessionData)(n,r);s&&"object"==typeof s&&(o=(0,si.setSessionValue)(o,"workflow",s)),oW(a,o);let l=JSON.stringify(o);return o8(l,"Workflow session data",2097152),await i.$transaction([i.workflowRun.update({where:{id:e},data:{sessionDataJson:l,sessionRevision:{increment:1},status:"PAUSED"===a.status?"PAUSED":"RUNNING",phase:"PAUSED"===a.status?"PAUSED":"SCHEDULING",blockedReason:null}}),i.workflowStepAttempt.updateMany({where:{runId:e,status:"BLOCKED"},data:{status:"PENDING",phase:"PENDING",error:null}})]),await this.appendEvent(e,null,"RUN_DATA_REPAIRED","Workflow session data repaired"),o7(e),this.run(e)}async answerQuestion(e,t){let r=await (0,t1.getPrismaClient)(),i=await r.$transaction(async r=>{let i=await r.runQuestionBatch.findUnique({where:{id:e},include:{workflowStepAttempt:!0,answerRevisions:!0}}),a=i?.workflowStepAttempt;if(!i||!a)throw Error("Workflow question not found");if("PENDING"!==i.status)throw Error("Question was already answered");return await r.runAnswerRevision.create({data:{id:(0,b.randomUUID)(),batchId:e,revision:i.answerRevisions.length,answersJson:JSON.stringify(t)}}),await r.runQuestionBatch.update({where:{id:e},data:{status:"ANSWERED",answeredAt:new Date}}),await r.workflowWait.updateMany({where:{attemptId:a.id,status:"PENDING",kind:"HUMAN"},data:{status:"RESOLVED",resultJson:JSON.stringify({answers:t}),resolvedAt:new Date}}),a});return await this.completeWaitingAttempt(i.id,{answers:t},"HUMAN"),ie.agentEventBus.publish(oq(i.runId),{workflowQuestionChanged:{id:e,runId:i.runId}}),this.run(i.runId)}async consumeCommandOutputMatches(){if(this.commandOutputStream||!this.commandsService)return;let e=ie.agentEventBus.iterate(ie.COMMAND_RUN_OUTPUT_CHANGED_TOPIC);this.commandOutputStream=e;try{for await(let t of e){if(this.commandOutputStream!==e)break;await this.reconcileCommandOutputMatches(t.commandRunOutputAdded.runId).catch(e=>console.error("Could not process workflow command output:",e))}}finally{this.commandOutputStream===e&&(this.commandOutputStream=void 0),await e.return?.()}}async commandOutputRows(e,t,r){if(!this.commandsService)return[];let i=[],a=t,n=r;for(;;){let t=await this.commandsService.listOutput(e,a,n,5e3);if(i.push(...t),t.length<5e3)return i;let r=t.at(-1);a=r.attempt.attempt,n=r.sequence}}commandMatchBranchNodes(e,t){let r=new Map;for(let t of e.edges)r.set(t.source,[...r.get(t.source)??[],t]);let i=(r.get(t)??[]).filter(({sourceHandle:e})=>"match"===e).map(({target:e})=>e),a=new Set;for(;i.length;){let e=i.shift();a.has(e)||(a.add(e),i.push(...(r.get(e)??[]).map(({target:e})=>e)))}return e.nodes.filter(({id:e})=>a.has(e))}async persistCommandMatches(e,t,r){var i;let a=await (0,t1.getPrismaClient)(),n=(i=e.predicateJson,JSON.stringify({...i?oV(oJ(i)):{},outputMatch:t}));if(!r.length)return!!(await a.workflowWait.updateMany({where:{id:e.id,status:"PENDING",predicateJson:e.predicateJson},data:{predicateJson:n}})).count;let s=(0,iC.parseWorkflowDefinition)(oJ(e.attempt.run.version.definitionJson)),o=s.nodes.find(({id:t})=>t===e.attempt.nodeId);if(!o)throw Error("Workflow command step is missing");let l=this.commandMatchBranchNodes(s,o.id);if(!await a.$transaction(async t=>{if(!(await t.workflowWait.updateMany({where:{id:e.id,status:"PENDING",predicateJson:e.predicateJson},data:{predicateJson:n}})).count)return!1;let i=await t.workflowRun.findUnique({where:{id:e.runId}});if(!i||!oK.has(i.status))return!1;let a=(0,si.workflowSessionData)(i.sessionDataJson??"{}"),s=`steps.${o.id}`,c=oV((0,si.getSessionValue)(a,s)),u=Array.isArray(c.matches)?c.matches:[],d=[...u,...r];oW(i,a=(0,si.setSessionValue)(a,s,{...c,matches:d,latestMatch:r.at(-1)}));let p=JSON.stringify(a);o8(p,"Workflow session data",2097152);let h=l.length?r.flatMap((t,i)=>{let a=`match.${e.attempt.id}.${t.ordinal}`,n=(0,si.setSessionValue)({},s,{...c,matches:[...u,...r.slice(0,i+1)],latestMatch:t}),d={runId:e.runId,generation:e.attempt.generation,iterationKey:a,attempt:0};return[{id:(0,b.randomUUID)(),...d,nodeId:o.id,kind:o.kind,status:"SUCCEEDED",phase:"MATCH_EMITTED",inputJson:JSON.stringify(n),outputJson:JSON.stringify({value:t,selectedHandles:["match"],sessionPatch:n}),requiredPathsJson:JSON.stringify(le(o)),providedPathsJson:JSON.stringify(lt(o)),idempotencyKey:`${e.runId}:${o.id}:${e.attempt.generation}:${a}:0`,startedAt:new Date,finishedAt:new Date},...l.map(t=>({id:(0,b.randomUUID)(),...d,nodeId:t.id,kind:t.kind,status:"PENDING",phase:"MATCH_PENDING",inputJson:JSON.stringify(n),requiredPathsJson:JSON.stringify(le(t)),providedPathsJson:JSON.stringify(lt(t)),idempotencyKey:`${e.runId}:${t.id}:${e.attempt.generation}:${a}:0`}))]}):[];return h.length&&await t.workflowStepAttempt.createMany({data:h}),await t.workflowRun.update({where:{id:e.runId},data:{sessionDataJson:p,sessionRevision:{increment:1}}}),!0}))return!1;for(let t of r)await this.appendEvent(e.runId,e.attemptId,"STEP_OUTPUT_MATCHED",`Step ${o.name??o.id} matched command output`,{nodeId:o.id,match:t});return o7(e.runId),await this.progressRun(e.runId),await this.dispatchReadyAttempts(),!0}async failCommandMatchWait(e,t){let r=await (0,t1.getPrismaClient)();if(!(await r.workflowWait.updateMany({where:{id:e.id,status:"PENDING",predicateJson:e.predicateJson},data:{status:"FAILED",resolvedAt:new Date}})).count)return;await this.commandsService?.terminateRun(e.externalKey);let i=(0,iC.parseWorkflowDefinition)(oJ(e.attempt.run.version.definitionJson)).nodes.find(({id:t})=>t===e.attempt.nodeId);await this.failAttempt(e.attempt,i??null,t)}async processCommandMatchWait(e){if(!e.externalKey||!this.commandsService)return;let t=function(e){if(!e)return null;let t=oV(oJ(e)),r=oV(t.outputMatch);return"string"==typeof r.pattern&&r.pattern?{pattern:r.pattern,mode:(0,sQ.commandOutputMatchMode)({outputMatchMode:r.mode}),matchCount:Number.isInteger(r.matchCount)?Number(r.matchCount):0,matched:!0===r.matched,scanAttempt:Number.isInteger(r.scanAttempt)&&Number(r.scanAttempt)>0?Number(r.scanAttempt):1,scanCharacterOffset:Number.isInteger(r.scanCharacterOffset)&&Number(r.scanCharacterOffset)>=0?Number(r.scanCharacterOffset):0,observedAttempt:Number.isInteger(r.observedAttempt)&&Number(r.observedAttempt)>=0?Number(r.observedAttempt):0,observedSequence:Number.isInteger(r.observedSequence)?Number(r.observedSequence):-1}:null}(e.predicateJson);if(t)try{let r=await this.commandOutputRows(e.externalKey,t.observedAttempt,t.observedSequence);if(!r.length)return;let i=r.at(-1);if(t.observedAttempt=i.attempt.attempt,t.observedSequence=i.sequence,"ONCE"===t.mode&&t.matched)return void await this.persistCommandMatches(e,t,[]);let a=await this.commandOutputRows(e.externalKey,t.scanAttempt-1,-1),n=new Map;for(let e of a){let r=e.attempt.attempt;r<t.scanAttempt||n.set(r,[...n.get(r)??[],e])}let s=[...n.keys()].sort((e,t)=>e-t),o=[],l=s1(t.pattern,!0);for(let r=0;r<s.length;r+=1){let i,a=s[r],c=n.get(a),u="",d=new Map,p=[];for(let e of c){if("STDOUT"!==e.stream&&"STDERR"!==e.stream)continue;let t=d.get(e.stream)??new TextDecoder("utf-8",{fatal:!1});d.set(e.stream,t);let r=t.decode(Buffer.from(e.dataBase64,"base64"),{stream:!0}),i=u.length;u+=r,p.push({sequence:e.sequence,start:i,end:u.length})}let h=a===t.scanAttempt?Math.min(t.scanCharacterOffset,u.length):0,m=u.slice(h);if(Buffer.byteLength(m,"utf8")>sQ.COMMAND_OUTPUT_MATCH_BUFFER_BYTES)throw Error("Command output matcher exceeded its 16 MiB unmatched-output limit");for(l.lastIndex=h;i=l.exec(u);){let r=i[0];if(!r.length)throw Error("Command output patterns must consume at least one character");let n=i.index,s=n+r.length,l=(e,t)=>{let r=p.find(({start:r,end:i})=>t?e>r&&e<=i:e>=r&&e<i)??p.at(-1);return{sequence:r.sequence,offset:Math.max(0,e-r.start)}};t.matchCount+=1;let c={ordinal:t.matchCount,text:r,captures:i.slice(1).map(e=>e??null),namedCaptures:Object.fromEntries(Object.entries(i.groups??{}).map(([e,t])=>[e,t??null])),commandRunId:e.externalKey,commandAttempt:a,start:l(n,!1),end:l(s,!0)};if(o.push(c),t.scanAttempt=a,t.scanCharacterOffset=s,"ONCE"===t.mode){t.matched=!0;break}}if(t.matched)break;let f=s[r+1];void 0!==f?(t.scanAttempt=f,t.scanCharacterOffset=0):a>t.scanAttempt&&(t.scanAttempt=a,t.scanCharacterOffset=0)}await this.persistCommandMatches(e,t,o)}catch(t){await this.failCommandMatchWait(e,t instanceof Error?t:Error(String(t)))}}async reconcileCommandOutputMatches(e){if(!this.commandsService)return;let t=await (0,t1.getPrismaClient)();for(let r of(await t.workflowWait.findMany({where:{kind:"COMMAND_RUN",status:"PENDING",predicateJson:{not:null},...e?{externalKey:e}:{},run:{status:{in:[...oK]}}},include:{attempt:{include:{run:{include:{version:!0}}}}},orderBy:{createdAt:"asc"},take:100})))await this.processCommandMatchWait(r)}async tick(){if(!this.ticking){this.ticking=!0;try{await this.recoverExpiredClaims(),await this.processSchedules(),await this.processTriggerEvents(),await this.events.maintain(),await this.reconcileCommandOutputMatches(),await this.resolveDueWaits(),await this.startQueuedRuns();let e=await (0,t1.getPrismaClient)();for(let{id:t}of(await e.workflowRun.findMany({where:{status:{in:["RUNNING","WAITING","PAUSING"]}},select:{id:!0},orderBy:{updatedAt:"asc"},take:100})))await this.progressRun(t);await this.dispatchReadyAttempts()}finally{this.ticking=!1}}}async recoverExpiredClaims(){let e=await (0,t1.getPrismaClient)();for(let t of(await e.workflowStepAttempt.findMany({where:{status:"RUNNING",claimExpiresAt:{lt:new Date}},include:{run:!0},take:100})))await e.$transaction([e.workflowStepAttempt.update({where:{id:t.id},data:{status:"BLOCKED",phase:"RECOVERY_BLOCKED",error:"The workflow worker stopped while this step was running; verify external state before retrying.",claimOwner:null,claimExpiresAt:null}}),e.workflowRun.update({where:{id:t.runId},data:{status:"BLOCKED",phase:"RECOVERY_BLOCKED",blockedReason:`Step ${t.nodeId} needs recovery review`}}),e.workflowResourceLease.deleteMany({where:{attemptId:t.id}})]),await this.appendEvent(t.runId,t.id,"STEP_RECOVERY_BLOCKED","Step needs recovery review after its worker lease expired"),await this.notifyRun(t.runId,"WORKFLOW_RECOVERY_PAUSED","Workflow paused during recovery","An interrupted step requires external-state verification before replay.",`recovery:${t.id}`),o7(t.runId)}async startQueuedRuns(){let e=await (0,t1.getPrismaClient)();for(let t of(await e.workflowRun.findMany({where:{status:"QUEUED"},include:{workflow:!0,version:!0},orderBy:[{queuedAt:"asc"},{id:"asc"}],take:200}))){let r=(0,iC.parseWorkflowDefinition)(oJ(t.version.definitionJson)),i=new Date,a=(0,si.setSessionValue)((0,si.workflowSessionData)(t.sessionDataJson),"workflow.startedAt",i.toISOString());await e.$transaction(async e=>{let n="CONCURRENT"===t.workflow.overlapPolicy?t.workflow.maxConcurrentRuns:1;if(await e.workflowRun.count({where:{workflowId:t.workflowId,id:{not:t.id},...o3(t.workflow.overlapScope,t.worktreeId),status:{in:o$.filter(e=>"QUEUED"!==e)}}})>=n)return!1;if(t.worktreeId&&"EXCLUDED"!==t.worktreeConcurrency){await e.worktreeAdmissionLane.upsert({where:{worktreeId:t.worktreeId},create:{worktreeId:t.worktreeId},update:{updatedAt:i}}),await e.worktreeWorkflowLease.deleteMany({where:{worktreeId:t.worktreeId,workflowRun:{status:{in:[...oF]}}}}),await e.worktreeRunLease.deleteMany({where:{worktreeId:t.worktreeId,purpose:{not:"ANSWER_REVISION"},run:{status:{in:["COMPLETED","FAILED","CANCELLED"]}}}});let r=await e.worktreeWorkflowLease.findUnique({where:{worktreeId:t.worktreeId}});if(r&&t.worktreeLeaseOwnerRunId!==r.workflowRunId)return await e.workflowRun.updateMany({where:{id:t.id,status:"QUEUED"},data:{phase:"WAITING_FOR_WORKTREE"}}),!1;if(!r){let r=await e.workflowRun.findFirst({where:{worktreeId:t.worktreeId,status:"QUEUED",parentRunId:null,worktreeConcurrency:"EXCLUSIVE"},orderBy:[{queuedAt:"asc"},{id:"asc"}],select:{id:!0,queuedAt:!0}});if(r&&r.id!==t.id&&function(e,t,r,i){let a=e.getTime()-r.getTime();return a<0||0===a&&t<i}(r.queuedAt,r.id,t.queuedAt,t.id))return await e.workflowRun.updateMany({where:{id:t.id,status:"QUEUED"},data:{phase:"WAITING_FOR_WORKTREE"}}),!1;if(t.worktreeLeaseOwnerRunId===t.id){let[r,i,a,n]=await Promise.all([e.worktreeRunLease.count({where:{worktreeId:t.worktreeId}}),e.workflowRun.count({where:{worktreeId:t.worktreeId,id:{not:t.id},worktreeConcurrency:{not:"EXCLUDED"},status:{in:o$.filter(e=>"QUEUED"!==e)}}}),e.agentRun.findFirst({where:{worktreeId:t.worktreeId,origin:"MANAGED",status:"QUEUED",OR:[{createdAt:{lt:t.queuedAt}},{createdAt:t.queuedAt,id:{lt:t.id}}]},select:{id:!0}}),e.workflowRun.findFirst({where:{worktreeId:t.worktreeId,status:"QUEUED",id:{not:t.id},worktreeConcurrency:{not:"EXCLUDED"},OR:[{queuedAt:{lt:t.queuedAt}},{queuedAt:t.queuedAt,id:{lt:t.id}}]},select:{id:!0}})]);if(r||i||a||n)return await e.workflowRun.updateMany({where:{id:t.id,status:"QUEUED"},data:{phase:"WAITING_FOR_WORKTREE"}}),!1;await e.worktreeWorkflowLease.create({data:{worktreeId:t.worktreeId,workflowRunId:t.id}})}}}return!!(await e.workflowRun.updateMany({where:{id:t.id,status:"QUEUED"},data:{status:"RUNNING",phase:"SCHEDULING",startedAt:i,sessionDataJson:JSON.stringify(a),sessionRevision:{increment:1}}})).count&&(await e.workflowStepAttempt.count({where:{runId:t.id,generation:t.generation}})||await e.workflowStepAttempt.createMany({data:r.nodes.map(e=>({id:(0,b.randomUUID)(),runId:t.id,nodeId:e.id,kind:e.kind,generation:t.generation,iterationKey:"",attempt:0,requiredPathsJson:JSON.stringify(le(e)),providedPathsJson:JSON.stringify(lt(e)),idempotencyKey:`${t.id}:${e.id}:${t.generation}::0`}))}),!0)})&&(t.startedAt||await this.appendEvent(t.id,null,"RUN_STARTED","Workflow started"),o7(t.id))}}selectedTrigger(e,t){let r=e.trigger?.nodeId??t.triggers.find(({kind:t})=>t===e.triggerKind)?.id??null;if(!(0,iR.isChoiceTriggerKind)(e.triggerKind))return{id:r,choice:null};let i=o5(oJ(e.triggerPayloadJson),"Trigger payload");return{id:r,choice:"string"==typeof i.choice?i.choice:null}}attemptOutput(e){if(!e.outputJson)return{};let t=oJ(e.outputJson);return t&&"object"==typeof t&&!Array.isArray(t)?t:{value:t}}edgeState(e,t,r,i){if(!i.has(e.source))return e.source!==t.id||t.choice&&e.sourceHandle!==t.choice?"INACTIVE":"ACTIVE";let a=r.get(e.source);if(!a||!oG.has(a.status))return"PENDING";if(new Set(["SKIPPED","CANCELLED","SUPERSEDED"]).has(a.status))return"INACTIVE";let n=i.get(e.source);if("FAILED"===a.status)return"failure"===e.sourceHandle||"catch"===e.sourceHandle||"CONTINUE"===n.failurePolicy&&"success"===e.sourceHandle?"ACTIVE":"INACTIVE";let s=this.attemptOutput(a).selectedHandles;return s?.length?s.includes(e.sourceHandle)?"ACTIVE":"INACTIVE":"success"===e.sourceHandle||"output"===e.sourceHandle?"ACTIVE":"INACTIVE"}async progressRun(e){let t=await (0,t1.getPrismaClient)(),r=await t.workflowRun.findUnique({where:{id:e},include:{version:!0,trigger:!0,attempts:!0,waits:!0}});if(!r||oF.has(r.status))return;if("PAUSING"===r.status){await t.workflowStepAttempt.updateMany({where:{runId:e,status:"READY"},data:{status:"PENDING",phase:"PAUSED_PENDING"}});let i=new Set(["AGENT_JOB","BUILD","SKILL_RUN","WORKTREE_MOVE","GITHUB_CHECKS"]),a=new Set(r.waits.filter(({status:e,kind:t})=>"PENDING"===e&&i.has(t)).map(({attemptId:e})=>e));!r.attempts.some(({id:e,status:t})=>"RUNNING"===t||"WAITING"===t&&a.has(e))&&(await t.workflowRun.updateMany({where:{id:e,status:"PAUSING"},data:{status:"PAUSED",phase:"PAUSED",pausedAt:new Date}})).count&&(await this.appendEvent(e,null,"RUN_PAUSED","Workflow paused"),o7(e));return}if(!new Set(["RUNNING","WAITING"]).has(r.status))return;let i=(0,iC.parseWorkflowDefinition)(oJ(r.version.definitionJson)),a=new Map(i.nodes.map(e=>[e.id,e])),n=new Map;for(let e of i.edges)n.set(e.target,[...n.get(e.target)??[],e]);let s=!0;for(;s;){if(s=!1,!(r=await t.workflowRun.findUnique({where:{id:e},include:{version:!0,trigger:!0,attempts:!0,waits:!0}})))return;let o=r.attempts.filter(({generation:e,supersededAt:t})=>e===r.generation&&!t),l=new Map;for(let e of o){let t=`${e.nodeId}:${e.iterationKey}`,r=l.get(t);(!r||r.attempt<e.attempt)&&l.set(t,e)}let c=new Map([...l.values()].filter(({iterationKey:e})=>!e).map(e=>[e.nodeId,e])),u=this.selectedTrigger(r,i);for(let e of i.nodes){let r=c.get(e.id);if(!r||"PENDING"!==r.status)continue;let o=i.nodes.find(t=>"CONTROL_FOR_EACH"===t.kind&&t.config.joinNodeId===e.id);if(o){let e=c.get(o.id);if(!e||!oG.has(e.status)||[...l.values()].filter(({iterationKey:e})=>!!e).some(({status:e})=>!oG.has(e)))continue;await t.workflowStepAttempt.update({where:{id:r.id},data:{status:"READY",phase:"ITERATIONS_JOINED"}}),s=!0;continue}let d=n.get(e.id)??[];if(!d.length)continue;let p=d.map(e=>this.edgeState(e,u,c,a)),h=p.filter(e=>"ACTIVE"===e).length,m=p.filter(e=>"PENDING"===e).length;("ANY"==("CONTROL_JOIN"===e.kind&&"ANY"===e.config.mode?"ANY":"ALL")?h>0:0===m&&h>0)?(await t.workflowStepAttempt.update({where:{id:r.id},data:{status:"READY",phase:"READY"}}),s=!0):0===m&&0===h&&(await t.workflowStepAttempt.update({where:{id:r.id},data:{status:"SKIPPED",phase:"INACTIVE_BRANCH",finishedAt:new Date}}),s=!0)}await this.progressIterationAttempts(i,r,u,a,n,l,c)&&(s=!0)}if(!(r=await t.workflowRun.findUnique({where:{id:e},include:{version:!0,trigger:!0,attempts:!0,waits:!0}})))return;let o=new Map;for(let e of r.attempts.filter(({generation:e,supersededAt:t})=>e===r.generation&&!t)){let t=`${e.nodeId}:${e.iterationKey}`,r=o.get(t);(!r||r.attempt<e.attempt)&&o.set(t,e)}let l=[...o.values()],c=r.waits.some(({status:e})=>"PENDING"===e),u=l.some(({status:e})=>!oG.has(e));if(c||u){let i=c?"WAITING":"RUNNING";r.status!==i&&(await t.workflowRun.updateMany({where:{id:e,status:{in:[...oK]}},data:{status:i,phase:c?"WAITING":"SCHEDULING"}})).count&&o7(e);return}let d=(0,iC.parseWorkflowDefinition)(oJ(r.version.definitionJson)),p=l.find(e=>{if("FAILED"!==e.status)return!1;let t=d.nodes.find(({id:t})=>t===e.nodeId);return!!t&&"CONTINUE"!==t.failurePolicy&&!d.edges.some(e=>e.source===t.id&&new Set(["failure","catch"]).has(e.sourceHandle))});await this.finishRun(r,p?"FAILED":"SUCCEEDED",p?.error??null)}async finishRun(e,t,r){let i=await (0,t1.getPrismaClient)();await i.$transaction(async i=>!!(await i.workflowRun.updateMany({where:{id:e.id,status:{in:[...oK]}},data:{status:t,phase:t,error:r,finishedAt:new Date}})).count&&(await i.workflowResourceLease.deleteMany({where:{runId:e.id}}),await i.worktreeWorkflowLease.deleteMany({where:{workflowRunId:e.id}}),!0))&&(await this.appendEvent(e.id,null,`RUN_${t}`,"SUCCEEDED"===t?"Workflow completed":"Workflow failed",r?{error:r}:null),await this.resolveExternalWait("WORKFLOW_RUN",e.id,{status:t,runId:e.id},"FAILED"===t?r||"Sub-workflow failed":null),await this.events.record({kind:"WORKFLOW_FINISHED",subjectKey:e.workflowId,dedupeKey:`workflow-finished:${e.id}`,payload:{sessionData:(0,si.workflowSessionData)(e.sessionDataJson),run:{id:e.id,status:t},workflowCorrelation:{workflowId:e.workflowId,runId:e.id}}}),await this.notifyRun(e.id,"SUCCEEDED"===t?"WORKFLOW_COMPLETED":"WORKFLOW_FAILED","SUCCEEDED"===t?"Workflow completed":"Workflow failed",r||`Workflow run ${e.displayNumber} ${t.toLowerCase()}`,t.toLowerCase()),await this.promoteWorktreeAdmissions(e.worktreeId),o7(e.id))}async dispatchReadyAttempts(){let e=await (0,t1.getPrismaClient)(),t=Math.max(0,4-await e.workflowStepAttempt.count({where:{status:"RUNNING"}}));if(t)for(let r of(await e.workflowStepAttempt.findMany({where:{status:"READY",run:{status:{in:[...oK]}}},orderBy:{createdAt:"asc"},take:2*t}))){if(t<=0)break;if(!(await e.workflowStepAttempt.updateMany({where:{id:r.id,status:"READY",run:{status:{in:[...oK]}}},data:{status:"RUNNING",phase:"RUNNING",claimOwner:this.workerId,claimExpiresAt:new Date(Date.now()+3e5),startedAt:r.startedAt??new Date}})).count)continue;t-=1;let i=new AbortController;this.activeExecutions.set(r.id,i),this.executeAttempt(r.id,i.signal).catch(e=>{console.error(`Workflow attempt ${r.id} failed unexpectedly:`,e)}).finally(()=>{this.activeExecutions.delete(r.id)})}}async acquireResourceLease(e,t,r){let i=iC.WORKFLOW_STEP_BY_KIND.get(t.kind),a=null;if(i.mutatesWorktree){let e=(0,si.getSessionValue)(r,"worktree.id")??(0,si.getSessionValue)(r,"worktree.path")??(0,si.getSessionValue)(r,"codebase.id");e&&(a=`git:${String(e)}`)}else if(t.kind.startsWith("BUILD_")){let e=(0,si.getSessionValue)(r,"build.id");e&&(a=`build:${String(e)}`)}if(!a)return!0;let n=await (0,t1.getPrismaClient)();await n.workflowResourceLease.deleteMany({where:{key:a,expiresAt:{lt:new Date}}});try{return await n.workflowResourceLease.create({data:{key:a,runId:e.runId,attemptId:e.id,expiresAt:new Date(Date.now()+3e5)}}),await n.workflowStepAttempt.update({where:{id:e.id},data:{resourceLockKey:a}}),!0}catch{return await n.workflowStepAttempt.update({where:{id:e.id},data:{status:"READY",phase:"WAITING_FOR_RESOURCE",claimOwner:null,claimExpiresAt:null}}),!1}}async executeAttempt(e,t){let r=await (0,t1.getPrismaClient)(),i=await r.workflowStepAttempt.findUnique({where:{id:e},include:{run:{include:{version:!0}}}});if(!i||"RUNNING"!==i.status)return;let a=(0,iC.parseWorkflowDefinition)(oJ(i.run.version.definitionJson)),n=a.nodes.find(({id:e})=>e===i.nodeId);if(!n)return void await this.failAttempt(i,null,Error("Workflow step definition is missing"));let s=(0,si.workflowSessionData)(i.run.sessionDataJson);i.iterationKey&&(s=await this.iterationSessionData(i.run,i,s));let o=le(n).filter(e=>!(0,si.hasSessionValue)(s,e));if(o.length){await r.$transaction([r.workflowStepAttempt.update({where:{id:i.id},data:{status:"BLOCKED",phase:"MISSING_REQUIREMENTS",error:`Missing required session data: ${o.join(", ")}`,claimOwner:null,claimExpiresAt:null}}),r.workflowRun.update({where:{id:i.runId},data:{status:"BLOCKED",phase:"MISSING_REQUIREMENTS",blockedReason:`Step ${n.name??n.id} needs ${o.join(", ")}`}}),r.workflowResourceLease.deleteMany({where:{attemptId:e}})]),await this.appendEvent(i.runId,i.id,"STEP_BLOCKED",`Step blocked by missing requirements: ${o.join(", ")}`),await this.notifyRun(i.runId,"WORKFLOW_NEEDS_ATTENTION","Workflow needs data",`Step ${n.name??n.id} needs ${o.join(", ")}`,`blocked:${i.id}`),o7(i.runId);return}if(i.run.exclusiveWorktree&&oH.has(n.kind))return void await this.failAttempt(i,n,Error("Exclusive workflows cannot run steps that create, delete, or move their worktree"));if(await r.workflowStepAttempt.update({where:{id:i.id},data:{inputJson:JSON.stringify(s)}}),await this.acquireResourceLease(i,n,s))try{let e,r={...n,config:(0,si.resolveWorkflowValue)(n.config,s)};if(e=n.kind.startsWith("CONTROL_")||"HUMAN_CONFIRM"===n.kind||"HUMAN_CHOICE"===n.kind?await this.executeControl(i.run,i,r,s,a):await this.executor.execute({run:i.run,attempt:i,node:r,sessionData:s,signal:t}),t.aborted)throw Error("Workflow step was cancelled");e.wait?await this.parkAttempt(i,n,e):await this.completeAttempt(i,n,e)}catch(t){let e=t instanceof Error?t:Error(String(t));if(await this.holdForBusyCodebase(i,e))return;await this.failAttempt(i,n,e)}}async holdForBusyCodebase(e,t){if(!(0,nK.isCodebaseBusyError)(t))return!1;let r=e.startedAt??e.createdAt;if(Date.now()-r.getTime()>6e5)return!1;let i=await (0,t1.getPrismaClient)();return!!(await i.workflowStepAttempt.updateMany({where:{id:e.id,status:"RUNNING",claimOwner:this.workerId},data:{status:"READY",phase:"WAITING_FOR_RESOURCE",error:t.message,claimOwner:null,claimExpiresAt:null}})).count&&(await i.workflowResourceLease.deleteMany({where:{attemptId:e.id}}),await i.workflowRunEvent.findFirst({where:{attemptId:e.id,type:"STEP_WAITING_FOR_RESOURCE"},select:{id:!0}})||await this.appendEvent(e.runId,e.id,"STEP_WAITING_FOR_RESOURCE","Step is waiting for the codebase to become available",{error:t.message}),o7(e.runId),!0)}async iterationSessionData(e,t,r){let i=await (0,t1.getPrismaClient)(),a=await i.workflowStepAttempt.findMany({where:{runId:e.id,generation:t.generation,iterationKey:t.iterationKey,status:"SUCCEEDED"},orderBy:{finishedAt:"asc"}}),n=r;for(let e of(t.inputJson&&(n=(0,si.mergeSessionData)(n,o5(oJ(t.inputJson),"Iteration input"))),a)){let t=this.attemptOutput(e);t.sessionPatch&&(n=(0,si.mergeSessionData)(n,t.sessionPatch))}return n}async executeControl(e,t,r,i,a){switch(r.kind){case"CONTROL_IF":{let e=r.config.condition;if(!e)throw Error("If steps require a condition");let t=oT(e,i);return{output:{matched:t},selectedHandles:[t?"true":"false"]}}case"CONTROL_JOIN":{let i=a.nodes.find(e=>"CONTROL_FOR_EACH"===e.kind&&e.config.joinNodeId===r.id);if(i){let r=await (0,t1.getPrismaClient)(),a=await r.workflowStepAttempt.findMany({where:{runId:e.id,generation:t.generation,iterationKey:{not:""},status:"FAILED"}});if(a.length&&"COLLECT_ERRORS"!==i.config.errorMode)throw Error(`${a.length} for-each iteration step(s) failed`);return{output:{iterations:await r.workflowStepAttempt.count({where:{runId:e.id,generation:t.generation,iterationKey:{not:""}}}),failures:a.map(({nodeId:e,iterationKey:t,error:r})=>({nodeId:e,iterationKey:t,error:r}))}}}return{output:{joined:!0}}}case"CONTROL_TRY":return{output:{started:!0}};case"CONTROL_DELAY":{let e=Number(r.config.seconds??0);if(!Number.isFinite(e)||e<0||e>31536e3)throw Error("Delay must be between zero and 31,536,000 seconds");return{wait:{kind:"DELAY",resumeAfter:new Date(Date.now()+1e3*e)}}}case"CONTROL_WAIT_UNTIL":{let e=r.config.condition;if(!e)throw Error("Wait-until steps require a condition");if(oT(e,i))return{output:{matched:!0}};let t=s4(r.config,15);return{wait:{kind:"PREDICATE",predicate:{condition:e,cadenceSeconds:t},resumeAfter:new Date(Date.now()+1e3*t),timeoutAt:s3(r.config)}}}case"CONTROL_SET_VARIABLE":{if("string"!=typeof r.config.path)throw Error("Set-variable steps require an output path");let e="string"==typeof r.config.script?await oL(r.config.script,i):r.config.value;return{output:e,sessionPatch:(0,si.setSessionValue)({},r.config.path,e)}}case"CONTROL_FOR_EACH":{let n=Array.isArray(r.config.items)?r.config.items:"string"==typeof r.config.listPath?(0,si.getSessionValue)(i,r.config.listPath):null;if(!Array.isArray(n))throw Error("For-each source must be an array");if(n.length>1e3)throw Error("For-each is limited to 1,000 items");return await this.spawnForEach(e,t,r,a,n),{output:{itemCount:n.length},selectedHandles:n.length?["body"]:["empty"],sessionPatch:(0,si.setSessionValue)({},`steps.${r.id}.items`,n)}}case"CONTROL_SUBWORKFLOW":return this.startSubworkflow(e,t,r,i);case"HUMAN_CONFIRM":case"HUMAN_CHOICE":return this.createHumanQuestion(e,t,r);default:throw Error(`Unsupported control step ${r.kind}`)}}async progressIterationAttempts(e,t,r,i,a,n,s){let o=await (0,t1.getPrismaClient)(),l=!1;for(let e of new Set([...n.values()].map(({iterationKey:e})=>e).filter(Boolean))){let t=new Map(s);for(let r of n.values())r.iterationKey===e&&t.set(r.nodeId,r);for(let n of t.values()){if(n.iterationKey!==e||"PENDING"!==n.status)continue;let s=i.get(n.nodeId);if(!s)continue;let c=(a.get(s.id)??[]).map(e=>this.edgeState(e,r,t,i)),u=c.filter(e=>"ACTIVE"===e).length,d=c.filter(e=>"PENDING"===e).length;("ANY"==("CONTROL_JOIN"===s.kind&&"ANY"===s.config.mode?"ANY":"ALL")?u>0:0===d&&u>0)?(await o.workflowStepAttempt.update({where:{id:n.id},data:{status:"READY",phase:"ITERATION_READY"}}),l=!0):0===d&&0===u&&(await o.workflowStepAttempt.update({where:{id:n.id},data:{status:"SKIPPED",phase:"INACTIVE_ITERATION_BRANCH",finishedAt:new Date}}),l=!0)}}return l}async spawnForEach(e,t,r,i,a){let n="string"==typeof r.config.joinNodeId?r.config.joinNodeId:null,s=i.nodes.find(({id:e})=>e===n);if(!s||"CONTROL_JOIN"!==s.kind)throw Error("For-each steps require an explicit joinNodeId");let o=new Map;for(let e of i.edges)o.set(e.source,[...o.get(e.source)??[],e]);let l=(o.get(r.id)??[]).filter(({sourceHandle:e})=>"body"===e).map(({target:e})=>e),c=new Set;for(;l.length;){let e=l.shift();e===n||c.has(e)||(c.add(e),l.push(...(o.get(e)??[]).map(({target:e})=>e)))}if(a.length&&!c.size)throw Error("For-each body is not connected to its body handle");let u=i.nodes.filter(({id:e})=>c.has(e)),d=await (0,t1.getPrismaClient)();await d.$transaction(async i=>{await i.workflowStepAttempt.updateMany({where:{runId:e.id,generation:t.generation,iterationKey:t.iterationKey,nodeId:{in:[...c]},status:"PENDING"},data:{status:"SKIPPED",phase:"ITERATION_TEMPLATE",finishedAt:new Date}}),a.length&&u.length&&await i.workflowStepAttempt.createMany({data:a.flatMap((i,a)=>{let n=t.iterationKey?`${t.iterationKey}.${a}`:String(a),s=JSON.stringify({loop:{current:{forEachNodeId:r.id,index:a,item:i},[r.id]:{index:a,item:i}}});return u.map(r=>({id:(0,b.randomUUID)(),runId:e.id,nodeId:r.id,kind:r.kind,generation:t.generation,iterationKey:n,attempt:0,status:"PENDING",phase:"ITERATION_PENDING",inputJson:s,requiredPathsJson:JSON.stringify(le(r)),providedPathsJson:JSON.stringify(lt(r)),idempotencyKey:`${e.id}:${r.id}:${t.generation}:${n}:0`}))})})})}async startSubworkflow(e,t,r,i){let a="string"==typeof r.config.versionId?r.config.versionId:null;if(!a)throw Error("Sub-workflow version is required");let n=await (0,t1.getPrismaClient)(),s=await n.workflowVersion.findUnique({where:{id:a},include:{workflow:{include:{activeVersion:!0}}}});if(!s)throw Error("Sub-workflow version not found");if(!s.workflow.enabled||s.workflow.archivedAt)throw Error("Sub-workflow is paused");let o=e,l=0;for(;o;){if(o.workflowId===s.workflowId)throw Error("Recursive sub-workflow invocation is not allowed");if((l+=1)>=10)throw Error("Sub-workflow depth is limited to 10");o=o.parentRunId?await n.workflowRun.findUnique({where:{id:o.parentRunId}}):null}let c={};if(r.config.inputMapping&&"object"==typeof r.config.inputMapping)for(let[e,t]of Object.entries(r.config.inputMapping))c=(0,si.setSessionValue)(c,e,(0,si.resolveWorkflowValue)(t,i));let u=await this.createRunForTrigger({...s.workflow,activeVersion:s},s,null,null,"SUBWORKFLOW",e.id,{sessionData:c,parentRunId:e.id},`${t.id}:subworkflow:${s.id}`,e.id);return o7(u.id),{output:{childRunId:u.id},links:[{kind:"WORKFLOW_RUN",resourceId:u.id,label:`Workflow run #${u.displayNumber}`,url:`/workflows/runs/${u.id}`}],wait:{kind:"WORKFLOW_RUN",externalKey:u.id,resumeAfter:s6(r.config),timeoutAt:s3(r.config)}}}async createHumanQuestion(e,t,r){let i=Array.isArray(r.config.questions)?r.config.questions:[{header:r.name??null,prompt:"string"==typeof r.config.prompt?r.config.prompt:"HUMAN_CONFIRM"===r.kind?"Continue this workflow?":"Choose an option",multiSelect:!!r.config.multiSelect,allowCustom:"HUMAN_CONFIRM"!==r.kind&&!1!==r.config.allowCustom,options:"HUMAN_CONFIRM"===r.kind?[{label:"Confirm",description:null},{label:"Cancel",description:null}]:Array.isArray(r.config.options)?r.config.options:[]}];if(!i.length||i.length>10)throw Error("Workflow questions must contain between one and ten questions");let a=await (0,t1.getPrismaClient)(),n=(0,b.randomUUID)();return await a.runQuestionBatch.create({data:{id:n,workflowStepAttemptId:t.id,nativeRequestId:`workflow:${t.id}`,questions:{create:i.map((e,t)=>{let r=o5(e,"Workflow question"),i=Array.isArray(r.options)?r.options:[];return{id:(0,b.randomUUID)(),position:t,header:"string"==typeof r.header?r.header:null,prompt:oZ(String(r.prompt??""),"Question prompt",1e4),multiSelect:!!r.multiSelect,allowCustom:!1!==r.allowCustom,options:{create:i.map((e,t)=>{let r=o5(e,"Question option");return{id:(0,b.randomUUID)(),position:t,label:oZ(String(r.label??""),"Option label",500),description:"string"==typeof r.description?r.description.slice(0,2e3):null}})}}})}}}),ie.agentEventBus.publish(oq(e.id),{workflowQuestionChanged:{id:n,runId:e.id}}),{output:{questionBatchId:n},wait:{kind:"HUMAN",externalKey:n,timeoutAt:s3(r.config)}}}async parkAttempt(e,t,r){let i=r.wait;if(!i)throw Error("Workflow wait is missing");let a=await (0,t1.getPrismaClient)(),n=(0,b.randomUUID)();if(await a.$transaction(async a=>{let s=await a.workflowRun.findUnique({where:{id:e.runId}});if(!s||oF.has(s.status))return!1;let o=(0,si.workflowSessionData)(s.sessionDataJson??"{}"),l=!e.iterationKey&&("SAVED_COMMAND"===t.kind||"CUSTOM_COMMAND"===t.kind);l&&r.sessionPatch&&(o=(0,si.mergeSessionData)(o,r.sessionPatch)),oW(s,o);let c=JSON.stringify(o);return o8(c,"Workflow session data",2097152),!!(await a.workflowStepAttempt.updateMany({where:{id:e.id,status:"RUNNING"},data:{status:"WAITING",phase:i.kind,outputJson:JSON.stringify({value:r.output,selectedHandles:r.selectedHandles,sessionPatch:l?void 0:r.sessionPatch}),claimOwner:null,claimExpiresAt:null}})).count&&(await a.workflowWait.create({data:{id:n,runId:e.runId,attemptId:e.id,kind:i.kind,predicateJson:i.predicate?JSON.stringify(i.predicate):null,externalKey:i.externalKey??null,resumeAfter:i.resumeAfter??null,timeoutAt:i.timeoutAt??null}}),r.links?.length&&await a.workflowRunResourceLink.createMany({data:r.links.map(t=>({id:(0,b.randomUUID)(),runId:e.runId,attemptId:e.id,kind:t.kind.toUpperCase(),resourceId:t.resourceId,label:t.label??null,url:t.url??null,metadataJson:t.metadata?JSON.stringify(t.metadata):null}))}),await a.workflowRun.updateMany({where:{id:e.runId,status:{in:[...oK]}},data:{status:"WAITING",phase:i.kind,sessionDataJson:c,sessionRevision:{increment:1}}}),await a.workflowResourceLease.deleteMany({where:{attemptId:e.id}}),!0)})){let r,a;await this.appendEvent(e.runId,e.id,"STEP_WAITING",(r=t.name??t.id,a=s8(i.kind),"DELAY"===i.kind&&i.resumeAfter?`Step ${r} is waiting for ${a} until ${i.resumeAfter.toISOString()}`:`Step ${r} is waiting for ${a}`),{waitId:n,kind:i.kind,nodeId:t.id,externalKey:i.externalKey??null,resumeAfter:i.resumeAfter?.toISOString()??null,timeoutAt:i.timeoutAt?.toISOString()??null}),o7(e.runId)}}async completeAttempt(e,t,r,i){let a=await (0,t1.getPrismaClient)();if(await a.$transaction(async i=>{let a=await i.workflowRun.findUnique({where:{id:e.runId}});if(!a)throw Error("Workflow run disappeared");if(oF.has(a.status))return!1;let n=(0,si.workflowSessionData)(a.sessionDataJson);if(e.iterationKey)n=(0,si.setSessionValue)(n,`steps.${t.id}.iterations.${e.iterationKey.replaceAll(".","_")}`,{status:"SUCCEEDED",output:r.output??null,data:r.sessionPatch??null});else{r.sessionPatch&&(n=(0,si.mergeSessionData)(n,r.sessionPatch));let e=`steps.${t.id}`,i=oV((0,si.getSessionValue)(n,e));n=(0,si.setSessionValue)(n,e,{...i,status:"SUCCEEDED",output:r.output??null,snapshotId:r.links?.find(({kind:e})=>"CHECKPOINT"===e)?.resourceId??null})}oW(a,n);let s=JSON.stringify(n);return o8(s,"Workflow session data",2097152),!!(await i.workflowStepAttempt.updateMany({where:{id:e.id,status:{in:["RUNNING","WAITING"]}},data:{status:"SUCCEEDED",phase:"SUCCEEDED",outputJson:JSON.stringify({value:r.output,selectedHandles:r.selectedHandles,sessionPatch:r.sessionPatch}),error:null,finishedAt:new Date,claimOwner:null,claimExpiresAt:null}})).count&&(r.links?.length&&await i.workflowRunResourceLink.createMany({data:r.links.map(t=>({id:(0,b.randomUUID)(),runId:e.runId,attemptId:e.id,kind:t.kind.toUpperCase(),resourceId:t.resourceId,label:t.label??null,url:t.url??null,metadataJson:t.metadata?JSON.stringify(t.metadata):null}))}),await i.workflowRun.update({where:{id:e.runId},data:{sessionDataJson:s,sessionRevision:{increment:1}}}),await i.workflowRun.updateMany({where:{id:e.runId,status:{in:[...oK]}},data:{status:"RUNNING",phase:"SCHEDULING"}}),await i.workflowResourceLease.deleteMany({where:{attemptId:e.id}}),!0)})){if(i)try{await i()}catch(t){console.error(`Failed to append completion diagnostics for workflow attempt ${e.id}:`,t)}await this.appendEvent(e.runId,e.id,"STEP_SUCCEEDED",`Step ${t.name??t.id} completed`),o7(e.runId)}}async failAttempt(e,t,r,i={}){let a=await (0,t1.getPrismaClient)(),n=t??(await a.workflowRun.findUnique({where:{id:e.runId},include:{version:!0}}))?.version.definitionJson,s="string"==typeof n?(0,iC.parseWorkflowDefinition)(oJ(n)).nodes.find(({id:t})=>t===e.nodeId)??null:n,o=s?.retry,l=!!(o&&e.attempt+1<o.maxAttempts),c=o?Math.min(86400,"EXPONENTIAL"===o.strategy?o.delaySeconds*2**e.attempt:o.delaySeconds):0;await a.$transaction(async t=>{let a=await t.workflowRun.findUnique({where:{id:e.runId}});if(!a||oF.has(a.status))return!1;let n=(0,si.workflowSessionData)(a.sessionDataJson);if(!e.iterationKey){i.sessionPatch&&(n=(0,si.mergeSessionData)(n,i.sessionPatch));let t=`steps.${e.nodeId}`,a=oV((0,si.getSessionValue)(n,t));n=(0,si.setSessionValue)(n,t,{...a,status:"FAILED",error:r.message,...void 0!==i.output?{output:i.output}:{}})}oW(a,n);let s=JSON.stringify(n);return o8(s,"Workflow session data",2097152),!!(await t.workflowStepAttempt.updateMany({where:{id:e.id,status:{in:["RUNNING","WAITING"]}},data:{status:"FAILED",phase:l?"RETRY_SCHEDULED":"FAILED",error:r.message.slice(0,2e4),finishedAt:new Date,claimOwner:null,claimExpiresAt:null}})).count&&(l&&await t.workflowWait.create({data:{id:(0,b.randomUUID)(),runId:e.runId,attemptId:e.id,kind:"RETRY",resumeAfter:new Date(Date.now()+1e3*c)}}),await t.workflowRun.update({where:{id:e.runId},data:{sessionDataJson:s,sessionRevision:{increment:1}}}),await t.workflowRun.updateMany({where:{id:e.runId,status:{in:[...oK]}},data:{status:l?"WAITING":"RUNNING",phase:l?"RETRY_WAIT":"SCHEDULING"}}),await t.workflowResourceLease.deleteMany({where:{attemptId:e.id}}),!0)})&&(await this.appendEvent(e.runId,e.id,l?"STEP_RETRY_SCHEDULED":"STEP_FAILED",l?`Step failed and will retry in ${c} seconds`:`Step failed: ${r.message}`,{error:r.message,retry:l}),o7(e.runId))}async resolveDueWaits(){let e=await (0,t1.getPrismaClient)(),t=new Date,r=(t,r)=>e.workflowWait.updateMany({where:{id:t,status:"PENDING",run:{status:{in:[...oK]}}},data:r});for(let i of(await e.workflowWait.findMany({where:{status:"PENDING",run:{status:{in:[...oK]}},OR:[{resumeAfter:{lte:t}},{timeoutAt:{lte:t}}]},include:{attempt:{include:{run:{include:{version:!0}}}}},orderBy:{createdAt:"asc"},take:100}))){if(i.timeoutAt&&i.timeoutAt<=t&&"RETRY"!==i.kind&&"DELAY"!==i.kind){if(!(await r(i.id,{status:"TIMED_OUT",resolvedAt:t})).count)continue;await this.failAttempt(i.attempt,(0,iC.parseWorkflowDefinition)(oJ(i.attempt.run.version.definitionJson)).nodes.find(({id:e})=>e===i.attempt.nodeId)??null,Error("Workflow wait timed out"));continue}if("RETRY"===i.kind){let r=i.attempt.attempt+1;await e.$transaction(async e=>{if(!(await e.workflowWait.updateMany({where:{id:i.id,status:"PENDING",run:{status:{in:[...oK]}}},data:{status:"RESOLVED",resolvedAt:t}})).count)return!1;if(await e.workflowStepAttempt.create({data:{id:(0,b.randomUUID)(),runId:i.runId,nodeId:i.attempt.nodeId,kind:i.attempt.kind,generation:i.attempt.generation,iterationKey:i.attempt.iterationKey,attempt:r,status:"PENDING",phase:"RETRY_PENDING",inputJson:i.attempt.inputJson,requiredPathsJson:i.attempt.requiredPathsJson,providedPathsJson:i.attempt.providedPathsJson,idempotencyKey:`${i.runId}:${i.attempt.nodeId}:${i.attempt.generation}:${i.attempt.iterationKey}:${r}`,replayedFromId:i.attempt.id}}),!(await e.workflowRun.updateMany({where:{id:i.runId,status:{in:[...oK]}},data:{status:"RUNNING",phase:"SCHEDULING"}})).count)throw Error("Workflow lifecycle changed while resuming retry");return!0})&&o7(i.runId)}else if("DELAY"===i.kind){if(!(await r(i.id,{status:"RESOLVED",resolvedAt:t})).count)continue;await this.completeWaitingAttempt(i.attemptId,{delayed:!0},"TIMER")}else if("PREDICATE"===i.kind){let e=i.predicateJson?o5(oJ(i.predicateJson),"Wait predicate"):{},a=e.condition,n=(0,si.workflowSessionData)(i.attempt.run.sessionDataJson);if(a&&oT(a,n)){if(!(await r(i.id,{status:"RESOLVED",resultJson:JSON.stringify({matched:!0}),resolvedAt:t})).count)continue;await this.completeWaitingAttempt(i.attemptId,{matched:!0},"POLL")}else{let t=Math.max(1,Number(e.cadenceSeconds??15));await r(i.id,{resumeAfter:new Date(Date.now()+1e3*t)})}}else if(i.externalKey&&this.waitPollers.has(i.kind)){let e=await this.waitPollers.get(i.kind)(i.externalKey);if("COMMAND_RUN"!==i.kind||e.pending||await this.reconcileCommandOutputMatches(i.externalKey),e.pending){let t=(0,iC.parseWorkflowDefinition)(oJ(i.attempt.run.version.definitionJson)).nodes.find(({id:e})=>e===i.attempt.nodeId)?.config??{};await r(i.id,{resumeAfter:new Date(Date.now()+1e3*s4(t,e.pollAfterSeconds??15))})}else{if(!(await r(i.id,{status:e.error?"FAILED":"RESOLVED",resultJson:JSON.stringify(e.result??{}),resolvedAt:new Date})).count)continue;if(e.error){let t=(0,iC.parseWorkflowDefinition)(oJ(i.attempt.run.version.definitionJson)).nodes.find(({id:e})=>e===i.attempt.nodeId),r=this.attemptOutput(i.attempt),a=oV(e.result),n=a.sessionPatch&&"object"==typeof a.sessionPatch&&!Array.isArray(a.sessionPatch)?(0,si.mergeSessionData)(r.sessionPatch??{},a.sessionPatch):r.sessionPatch;await this.failAttempt(i.attempt,t??null,Error(e.error),{output:e.result??r.value,sessionPatch:n})}else await this.completeWaitingAttempt(i.attemptId,e.result??{},"POLL")}}}}async completeWaitingAttempt(e,t,r="PUSH"){let i=await (0,t1.getPrismaClient)(),a=await i.workflowStepAttempt.findUnique({where:{id:e},include:{run:{include:{version:!0}}}});if(!a||"WAITING"!==a.status)return;let n=(0,iC.parseWorkflowDefinition)(oJ(a.run.version.definitionJson)).nodes.find(({id:e})=>e===a.nodeId);if(!n)throw Error("Workflow step definition is missing");let s=this.attemptOutput(a),o=s.sessionPatch;if("TERMINAL_RUN"===n.kind&&t&&"object"==typeof t&&!Array.isArray(t)&&t.sessionData&&"object"==typeof t.sessionData&&!Array.isArray(t.sessionData)){let e=structuredClone(t.sessionData),r=(0,si.getSessionValue)((0,si.workflowSessionData)(a.run.sessionDataJson),"workflow");o=r?(0,si.setSessionValue)(e,"workflow",r):e}t&&"object"==typeof t&&!Array.isArray(t)&&t.sessionPatch&&"object"==typeof t.sessionPatch&&!Array.isArray(t.sessionPatch)&&(o=(0,si.mergeSessionData)(o??{},t.sessionPatch)),n.kind.startsWith("RUN_")&&t&&"object"==typeof t&&!Array.isArray(t)&&(o=(0,si.mergeSessionData)(o??{},(0,si.setSessionValue)({},`run.${n.id}`,t))),"BUILD_START"===n.kind&&t&&"object"==typeof t&&!Array.isArray(t)&&(o=(0,si.mergeSessionData)(o??{},(0,si.setSessionValue)({},"build",t))),"WORKTREE_WAIT_PUSH_READY"===n.kind&&t&&"object"==typeof t&&!Array.isArray(t)&&(o=(0,si.mergeSessionData)(o??{},(0,si.setSessionValue)({},"worktree",{id:t.id,pushStatus:t.pushStatus}))),"SKILL_APPLY"===n.kind&&t&&"object"==typeof t&&!Array.isArray(t)&&(o=(0,si.mergeSessionData)(o??{},(0,si.setSessionValue)({},`steps.${n.id}`,t))),("HUMAN_CONFIRM"===n.kind||"HUMAN_CHOICE"===n.kind)&&(o=(0,si.mergeSessionData)(o??{},(0,si.setSessionValue)({},`steps.${n.id}.answer`,t)));try{await this.completeAttempt(a,n,{output:t??s.value,selectedHandles:s.selectedHandles,sessionPatch:o},()=>this.appendWaitResolvedEvent(a,n,r))}catch(e){await this.failAttempt(a,n,e instanceof Error?e:Error(String(e)))}}async resolveExternalWait(e,t,r,i=null){let a=await (0,t1.getPrismaClient)(),n=await a.workflowWait.findMany({where:{kind:e,externalKey:t,status:"PENDING"},include:{attempt:{include:{run:{include:{version:!0}}}}}});for(let e of n)if(await a.workflowWait.update({where:{id:e.id},data:{status:i?"FAILED":"RESOLVED",resultJson:JSON.stringify(r),resolvedAt:new Date}}),i){let t=(0,iC.parseWorkflowDefinition)(oJ(e.attempt.run.version.definitionJson)).nodes.find(({id:t})=>t===e.attempt.nodeId);await this.failAttempt(e.attempt,t??null,Error(i))}else await this.completeWaitingAttempt(e.attemptId,r,"PUSH");return n.length}descendants(e,t){let r=new Map;for(let t of e.edges)r.set(t.source,[...r.get(t.source)??[],t.target]);let i=new Set([t]),a=[t];for(;a.length;){let e=a.shift();for(let t of r.get(e)??[])i.has(t)||(i.add(t),a.push(t))}return[...i]}async prepareReplay(e,t){let r=await (0,t1.getPrismaClient)(),i=await r.workflowRun.findUnique({where:{id:e},include:{version:!0,attempts:{include:{checkpoints:!0,resourceLinks:!0}}}});if(!i)throw Error("Workflow run not found");if(!new Set(["PAUSED","BLOCKED","FAILED","SUCCEEDED","CANCELLED"]).has(i.status))throw Error("Pause the workflow before replaying a step");let a=(0,iC.parseWorkflowDefinition)(oJ(i.version.definitionJson));if(!a.nodes.some(({id:e})=>e===t))throw Error("Workflow step not found");let n=this.descendants(a,t),s=i.attempts.filter(({generation:e,nodeId:t})=>e===i.generation&&n.includes(t)),o=s.filter(e=>e.nodeId===t).sort((e,t)=>t.attempt-e.attempt)[0],l=o?.checkpoints.slice().sort((e,t)=>e.createdAt.getTime()-t.createdAt.getTime())[0],c=s.flatMap(e=>e.resourceLinks.filter(({kind:e})=>"CHECKPOINT"!==e).map(({kind:e,resourceId:t,label:r,url:i})=>({kind:e,resourceId:t,label:r,url:i}))),u=null,d=null;if(l&&this.agentControl)try{u=await this.compareCheckpointWithAgent(l.id)}catch(e){d=`Git comparison unavailable: ${e instanceof Error?e.message:String(e)}`}return{runId:e,nodeId:t,affectedNodeIds:n,affectedAttemptIds:s.map(({id:e})=>e),externalEffects:c,checkpointId:l?.id??null,gitComparison:u,warning:[c.length?"External Jira, GitHub, build, deployment, and notification effects will not be undone.":null,d].filter(Boolean).join(" ")||null}}async replay(e,t,r={}){let i=await this.prepareReplay(e,t);if(r.restore){if(!i.checkpointId)throw Error("No restorable Git checkpoint is available for this step");this.checkpointRestorer?await this.checkpointRestorer(i.checkpointId,{stash:!!r.stash}):await this.restoreCheckpointWithAgent(i.checkpointId,{stash:!!r.stash})}let a=await (0,t1.getPrismaClient)(),n=await a.workflowRun.findUnique({where:{id:e},include:{version:!0,attempts:!0}});if(!n)throw Error("Workflow run not found");let s=(0,iC.parseWorkflowDefinition)(oJ(n.version.definitionJson)),o=n.attempts.filter(e=>e.generation===n.generation&&e.nodeId===t).sort((e,t)=>t.attempt-e.attempt)[0];if(!o)throw Error("Selected step has no execution history");let l=o.inputJson?o5(oJ(o.inputJson),"Step input snapshot"):(0,si.workflowSessionData)(n.sessionDataJson),c=n.generation+1,u=new Map;for(let e of n.attempts.filter(({generation:e,iterationKey:t})=>e===n.generation&&!t)){let t=u.get(e.nodeId);(!t||t.attempt<e.attempt)&&u.set(e.nodeId,e)}let d=(0,si.setSessionValue)(l,"workflow.replay",{generation:c,fromNodeId:t,replayedAt:new Date().toISOString()});return oW(n,d),await a.$transaction(async t=>{await t.workflowStepAttempt.updateMany({where:{runId:e,generation:n.generation,nodeId:{in:i.affectedNodeIds},supersededAt:null},data:{supersededAt:new Date}}),await t.workflowStepAttempt.createMany({data:s.nodes.map(t=>{let r=i.affectedNodeIds.includes(t.id),a=u.get(t.id);return{id:(0,b.randomUUID)(),runId:e,nodeId:t.id,kind:t.kind,generation:c,iterationKey:"",attempt:0,status:r?"PENDING":a?.status==="SKIPPED"?"SKIPPED":"SUCCEEDED",phase:r?"REPLAY_PENDING":"REUSED_FROM_PRIOR_GENERATION",inputJson:r?null:a?.inputJson,outputJson:r?null:a?.outputJson,error:null,startedAt:r?null:a?.startedAt,finishedAt:r?null:new Date,requiredPathsJson:JSON.stringify(le(t)),providedPathsJson:JSON.stringify(lt(t)),idempotencyKey:`${e}:${t.id}:${c}::0`,replayedFromId:a?.id??null}})}),await t.workflowWait.updateMany({where:{runId:e,status:"PENDING"},data:{status:"SUPERSEDED",resolvedAt:new Date}}),await t.workflowRun.update({where:{id:e},data:{generation:c,sessionDataJson:JSON.stringify(d),sessionRevision:{increment:1},status:n.worktreeId?"QUEUED":"RUNNING",phase:n.worktreeId?"WAITING_FOR_WORKTREE":"REPLAYING",queuedAt:n.worktreeId?new Date:n.queuedAt,blockedReason:null,error:null,pausedAt:null,finishedAt:null}})}),await this.appendEvent(e,null,"RUN_REPLAYED",`Replaying from step ${t}`,{generation:c,affectedNodeIds:i.affectedNodeIds}),n.worktreeId&&await this.startQueuedRuns(),o7(e),this.run(e)}async appendWaitResolvedEvent(e,t,r){let i,a,n,s=await (0,t1.getPrismaClient)(),o=await s.workflowWait.findFirst({where:{attemptId:e.id},orderBy:{createdAt:"desc"}});if(!o)return;let l=Math.max(0,(o.resolvedAt??new Date).getTime()-o.createdAt.getTime());await this.appendEvent(e.runId,e.id,"STEP_WAIT_RESOLVED",`Step ${t.name??t.id} resumed after waiting ${(a=Math.floor((i=Math.max(0,Math.round(l/1e3)))/3600),n=Math.floor(i%3600/60),a?`${a}h ${n}m`:n?`${n}m ${i%60}s`:`${i}s`)} for ${s8(o.kind)}`,{waitId:o.id,kind:o.kind,nodeId:t.id,externalKey:o.externalKey,waitedMs:l,resolvedBy:r})}async appendEvent(e,t,r,i,a=null){let n=await (0,t1.getPrismaClient)(),s=await n.$transaction(async n=>{let s=await n.workflowRunEvent.findFirst({where:{runId:e},orderBy:{sequence:"desc"},select:{sequence:!0}});return n.workflowRunEvent.create({data:{id:(0,b.randomUUID)(),runId:e,attemptId:t,sequence:(s?.sequence??-1)+1,type:r,message:i.slice(0,2e4),detailJson:a?JSON.stringify(a):null}})});return ie.agentEventBus.publish(oM(e),{workflowRunEventAdded:s}),s}subscribeWorkflows(){return ie.agentEventBus.iterate(oU)}subscribeRun(e){return ie.agentEventBus.iterate(oj(e))}subscribeRunEvents(e){return ie.agentEventBus.iterate(oM(e))}subscribeRunQuestions(e){return ie.agentEventBus.iterate(oq(e))}}let la=globalThis;e.s(["getServerServices",0,function(){var e,t,r,i,b,k,E,S,I,A,x,_,C,R,T,D,N;let O,P,L,B,U,j,M,q,$,F,G,K,H,V,W,J,z,Y,Z,Q,X,ee,et,er,ei,ea,en,es,eo,el,ec,eu,ed,ep,eh,em,ef,eg,ey;return la.serverServices??(O=new w.PrismaService,P=new t3.CredentialService,L=new oI,B=new a.AgentControlService,U=new n_(P),j=new nD,M=new il(B),(q=new n7(B,U)).startRuntime(),$=new n.CcusageService(B),F=new s.BuildDataService(B),G=new nr.TelemetryService,K=new nl(B,void 0,P),H=new n$,V=new nc.PushNotificationsService(void 0,P,j),(W=new nF.RunsService(U,B,M)).startReaper(),J=new o.BuildsService(B,G,U,M),z=new nt(B),Y=new l.CodebasesService(B,z),Z=new c.CodebaseToolsService(Y),Q=new f.JiraService(P,L),X=new g.JiraWebhookService(Q,P,L),ee=new y.IosDevicesService(void 0,P),et=new d.GitHubPipelineStatusService,er=new u.GitHubActionsNotificationsService(P,U,j,!0,L,void 0,et),ei=new p.GitHubService(!0,P,j,()=>er.configurationChanged(),et),en=new s$(B,ei,ea=new h.GitLabService(P,L,j,U)),es=new m.CacheServerService(P),eo=new it.WorktreesService(B,Q,ei,z,L,et,ea),el=new sr($,M,j),ec=new sm,eu=new sw,ed=new sT,ep=new aw(Z,J,{codebases:Y,telemetry:G,pushNotifications:V,agents:B,diskSpace:M,worktrees:eo,runs:W,commands:q,jira:Q,jiraWebhooks:X,github:ei,gitlab:ea,buildData:F,cacheServer:es,ccusage:$,credentials:P,iosDevices:ee,modelCosts:H,notifications:U,polling:j,signingAssets:K,skills:z,systemStatus:el,workflows:()=>em,worktreeAutomations:()=>ef},P),W.setMcpPresetResolver((e,t)=>ep.resolveRunMcpPresets(e,t)),em=new li(L,eh=new oB,void 0,P,B,U,W,eo,q,Q),ef=new az(eo,ei,Q,em,B,j),t=em,r=e={agentControl:B,jira:Q,github:ei,gitlab:ea,worktrees:eo,worktreeAutomations:ef,codebases:Y,builds:J,skills:z,runs:W,commands:q,notifications:U,pushNotifications:V,tools:ep,diskSpace:M,buildData:F,ccusage:$,iosDevices:ee,modelCosts:H,signingAssets:K},t.registerWaitPoller("AGENT_JOB",async e=>{let t=await r.agentControl.getJob(e);return t?new Set(["QUEUED","RUNNING"]).has(t.status)?{pending:!0,pollAfterSeconds:2}:{pending:!1,result:t.resultJson?{...s5(JSON.parse(t.resultJson),"Agent job result"),jobId:e}:{jobId:e,status:t.status},error:"SUCCEEDED"===t.status?null:t.error||`Agent job ${t.status.toLowerCase()}`}:{pending:!1,error:"Agent job disappeared"}}),t.registerWaitPoller("AGENT_JOBS",async e=>{let t=s5(JSON.parse(e),"Agent jobs wait"),i=Array.isArray(t.ids)?t.ids.map(e=>s9(e,"Agent job ID",500)):[];if(!i.length)return{pending:!1,result:{jobs:[]}};let a=await Promise.all(i.map(e=>r.agentControl.getJob(e)));if(a.some(e=>!e))return{pending:!1,error:"Agent job disappeared"};let n=a.filter(e=>!!e);if(n.some(e=>new Set(["QUEUED","RUNNING"]).has(e.status)))return{pending:!0,pollAfterSeconds:2};let s=n.map(e=>({id:e.id,status:e.status,error:e.error})),o=s.filter(({status:e})=>"SUCCEEDED"!==e);return{pending:!1,result:{jobs:s,sessionPatch:{signing:{jobs:s}}},error:o.length?o.map(({id:e,status:t,error:r})=>r?`${e}: ${r}`:`${e}: ${t.toLowerCase()}`).join("; "):null}}),t.registerWaitPoller("AGENT_RUN",async e=>{let t=await r.runs.get(e);return t?new Set(["QUEUED","IN_PROGRESS","PAUSED"]).has(t.status)?{pending:!0,pollAfterSeconds:3}:{pending:!1,result:{id:t.id,kind:t.kind,status:t.status,phase:t.phase,finalOutput:t.finalOutput,error:t.error,usage:{inputTokens:t.inputTokens,outputTokens:t.outputTokens,reasoningTokens:t.reasoningTokens,estimatedCost:t.estimatedCost}},error:"COMPLETED"===t.status?null:t.error||`Run ${t.status.toLowerCase()}`}:{pending:!1,error:"Plan or session disappeared"}}),t.registerWaitPoller("COMMAND_RUN",async e=>{let t=await r.commands.getRun(e);return t?new Set(["QUEUED","RUNNING","RESTARTING","CANCELLING"]).has(t.status)?{pending:!0,pollAfterSeconds:1}:{pending:!1,result:{id:t.id,displayNumber:t.displayNumber,status:t.status,exitCode:t.exitCode,signal:t.signal,error:t.error,sessionPatch:{command:{id:t.id,commandId:t.commandId,name:t.snapshotName,status:t.status,exitCode:t.exitCode,signal:t.signal,error:t.error,finishedAt:t.finishedAt?.toISOString()??null}}},error:"SUCCEEDED"===t.status?null:t.error||`Command run ${t.status.toLowerCase()}`}:{pending:!1,error:"Command run disappeared"}}),t.registerWaitPoller("BUILD",async e=>{let t=await r.builds.getBuild(e);return t?new Set(["QUEUED","PREPARING","RUNNING"]).has(t.status)?{pending:!0,pollAfterSeconds:3}:{pending:!1,result:{id:t.id,status:t.status,action:t.action,sessionPatch:{build:{id:t.id,status:t.status,action:t.action,error:t.error}}},error:"SUCCEEDED"===t.status?null:t.error||`Build ${t.status.toLowerCase()}`}:{pending:!1,error:"Build disappeared"}}),t.registerWaitPoller("BUILD_DATA_COLLECTION",async e=>{let t=await r.buildData.getCollection(e);return t?"COMPLETED"!==t.status?{pending:!0,pollAfterSeconds:2}:{pending:!1,result:{...t,sessionPatch:{buildData:t}}}:{pending:!1,error:"Build-data collection disappeared"}}),t.registerWaitPoller("SIGNING_OPERATIONS",async e=>{let t=s5(JSON.parse(e),"Signing operations wait"),i=Array.isArray(t.ids)?t.ids.map(e=>s9(e,"Signing operation ID",500)):[];if(!i.length)return{pending:!1,result:{operations:[]}};let a=(await r.signingAssets.operations(200)).filter(({id:e})=>i.includes(e));if(a.length!==i.length)return{pending:!1,error:"Signing operation disappeared"};let n=new Set(["SUCCEEDED","FAILED","CANCELLED","TIMED_OUT"]);if(a.some(({status:e})=>!n.has(e)))return{pending:!0,pollAfterSeconds:2};let s=a.filter(({status:e})=>"SUCCEEDED"!==e);return{pending:!1,result:{operations:a,sessionPatch:{signing:{operations:a}}},error:s.length?s.map(({id:e,error:t,status:r})=>t?`${e}: ${t}`:`${e}: ${r.toLowerCase()}`).join("; "):null}}),t.registerWaitPoller("SKILL_RUN",async e=>{let t=await r.skills.getRun(e);return t?("READY"===t.status&&(t=await r.skills.applyRun(e)),new Set(["PREPARING","READY","APPLYING"]).has(t?.status??""))?{pending:!0,pollAfterSeconds:3}:{pending:!1,result:{id:e,status:t?.status},error:t?.status==="SUCCEEDED"?null:t?.error||`Skill run ${t?.status?.toLowerCase()}`}:{pending:!1,error:"Skill run disappeared"}}),t.registerWaitPoller("WORKTREE_MOVE",async e=>{let t=await r.worktrees.getMove(e);if(!t)return{pending:!1,error:"Worktree move disappeared"};if(new Set(["PUSHING","CHECKING_OUT","DELETING_SOURCE"]).has(t.status))return{pending:!0,pollAfterSeconds:3};let i=t.targetWorktreeId?await r.worktrees.workflowSessionDataForWorktree(t.targetWorktreeId,{includeMissing:!0}):{};return{pending:!1,result:{id:t.id,status:t.status,targetWorktreeId:t.targetWorktreeId,sessionPatch:i},error:"SUCCEEDED"===t.status?null:t.error||`Worktree move ${t.status.toLowerCase()}`}}),t.registerWaitPoller("WORKTREE_PUSH_READY",async e=>{let t=await (0,t1.getPrismaClient)(),i=await t.worktree.findUnique({where:{id:e}});if(!i)return{pending:!1,error:"Worktree disappeared"};if("READY"!==i.pushStatus)return{pending:!0,pollAfterSeconds:5};let a=await r.worktrees.workflowSessionDataForWorktree(i.id,{includeMissing:!0});return{pending:!1,result:{id:i.id,pushStatus:i.pushStatus,sessionPatch:a}}}),t.registerWaitPoller("WORKFLOW_RUN",async e=>{let r=await t.run(e);return r?new Set(["SUCCEEDED","FAILED","CANCELLED"]).has(r.status)?{pending:!1,result:{id:r.id,status:r.status,sessionData:JSON.parse(r.sessionDataJson)},error:"SUCCEEDED"===r.status?null:r.error||`Sub-workflow ${r.status.toLowerCase()}`}:{pending:!0,pollAfterSeconds:3}:{pending:!1,error:"Sub-workflow disappeared"}}),t.registerWaitPoller("RUN_ANSWER_REVISION",async e=>{let t=s5(JSON.parse(e),"Answer revision wait"),i=s9(t.batchId,"Question batch ID",500),a=await r.runs.questionBatch(i);if(!a)return{pending:!1,error:"Question batch disappeared"};if(!a.revisionPreparedAt)return{pending:!0,pollAfterSeconds:2};let n=await r.runs.reviseAnswer(i,t.answers??{},!0===t.stash,!1!==t.rollback);return n?{pending:!1,result:{id:n.id,kind:n.kind,status:n.status,phase:n.phase,parentRunId:n.parentRunId,followUpMode:n.followUpMode}}:{pending:!1,error:"Answer revision failed"}}),t.registerWaitPoller("GITHUB_CHECKS",async e=>{let t=s5(JSON.parse(e),"GitHub checks wait"),i=await r.github.autoRetryRun(s9(t.repositoryId,"Repository ID"),s9(t.workflowRunId,"Workflow run ID"),!0,"WORKFLOW_AUTOMATION");return new Set(["SUCCESS","FAILURE","CANCELLED","SKIPPED","TIMED_OUT","ACTION_REQUIRED","ERROR","NEUTRAL","STALE","STARTUP_FAILURE"]).has(i.status)?{pending:!1,result:{runId:i.id,status:i.status,jobs:i.jobs,sessionPatch:{pipeline:{runId:i.id,status:i.status,conclusion:i.status,jobs:i.jobs}}},error:"SUCCESS"===i.status?null:`GitHub checks concluded ${i.status.toLowerCase()}`}:{pending:!0,pollAfterSeconds:10}}),t.registerWaitPoller("GITLAB_PIPELINE",async e=>{let t=s5(JSON.parse(e),"GitLab pipeline wait"),i=await r.gitlab.pipeline(s9(t.projectId,"GitLab project ID",500),s9(t.pipelineId,"GitLab pipeline ID",500));return new Set(["SUCCESS","FAILED","CANCELED","SKIPPED","MANUAL"]).has(i.status)?{pending:!1,result:{id:i.id,projectId:i.projectId,status:i.status,webUrl:i.webUrl,sessionPatch:{pipeline:{id:i.id,projectId:i.projectId,status:i.status,webUrl:i.webUrl}}},error:"SUCCESS"===i.status?null:`GitLab pipeline concluded ${i.status.toLowerCase()}`}:{pending:!0,pollAfterSeconds:10}}),t.registerWaitPoller("DISK_SPACE_REPORT",async e=>{let t=s5(JSON.parse(e),"Disk-space report wait"),i=s9(t.agentId,"Agent ID",500),a=await r.diskSpace.snapshot(i);if(!a.disk.enabled)return{pending:!1,error:"Disk-space monitoring was disabled while awaiting a report"};let n=a.disk.lastReportedAt,s="string"==typeof t.previousReportedAt?t.previousReportedAt:null;return(s9(t.requestedAt,"Requested timestamp",100),n&&(!s||Date.parse(n)>Date.parse(s)))?{pending:!1,result:{...a,sessionPatch:a}}:{pending:!0,pollAfterSeconds:2}}),i=eh,b=e,i.register("JIRA_LOAD_TICKET",async e=>{let t=op(await b.jira.ticket(om(e),!0===e.node.config.force));return{output:t,sessionPatch:{ticket:t},links:[on(String(t.key),String(t.title??t.key))]}}),i.register("JIRA_TRANSITION",async e=>{let t=op(await b.jira.transitionTicket(om(e),s9(e.node.config.transitionId,"Jira transition ID",200)));return{output:t,sessionPatch:{ticket:t},links:[on(String(t.key),String(t.title??t.key))]}}),i.register("JIRA_COMMENT",async e=>{let t=op(await b.jira.addComment(om(e),{value:s9(e.node.config.content,"Jira comment",1e5),format:"JIRA_WIKI"===e.node.config.format?"JIRA_WIKI":"MARKDOWN"}));return{output:t,sessionPatch:{ticket:t},links:[on(String(t.key),String(t.title??t.key))]}}),i.register("JIRA_ASSIGN",async e=>{let t=null===e.node.config.accountId?null:s9(e.node.config.accountId,"Jira account ID",500),r=op(await b.jira.assignTicket(om(e),t));return{output:r,sessionPatch:{ticket:r},links:[on(String(r.key),String(r.title??r.key))]}}),i.register("JIRA_UPDATE_FIELDS",async e=>{let t=s5(e.node.config.fields??{},"Jira fields"),r=op(await b.jira.updateTicket({issueKey:om(e),...t}));return{output:r,sessionPatch:{ticket:r},links:[on(String(r.key),String(r.title??r.key))]}}),i.register("JIRA_RESOLVE_BRANCH",async e=>{let t=await b.worktrees.previewTicketBranch({codebaseId:s9(e.node.config.codebaseId??(0,si.getSessionValue)(e.sessionData,"codebase.id"),"Codebase ID",200),worktreeId:"string"==typeof(0,si.getSessionValue)(e.sessionData,"worktree.id")?String((0,si.getSessionValue)(e.sessionData,"worktree.id")):null,ticketKey:om(e)});return{output:t,sessionPatch:{worktree:{branch:t.branchName},ticket:{key:t.ticketKey,title:t.ticketTitle,type:t.ticketType}},links:[on(t.ticketKey,t.ticketTitle)]}}),k=eh,E=e,k.register("GITHUB_LOAD_PR",async e=>{let t=od(e),r=await E.github.pullRequest(t.owner,t.name,og(e),"WORKFLOW_AUTOMATION");if(!r)throw Error("Pull request was not found");let i=oh(r);return{output:i,sessionPatch:{pr:i},links:[oa("PULL_REQUEST",sF(t.owner,t.name,r.number),r.title,r.url)]}}),k.register("GITHUB_MERGE_PR",async e=>{let t=od(e),r=og(e),i=await E.github.pullRequestMergeOptions(t.owner,t.name,r,"WORKFLOW_AUTOMATION");if(!i.canMerge)throw Error(i.blockedReason||"Pull request cannot be merged");let a=await E.github.mergePullRequest({...t,number:r,method:"MERGE"===e.node.config.method||"REBASE"===e.node.config.method?e.node.config.method:"SQUASH",commitHeadline:"string"==typeof e.node.config.commitHeadline?e.node.config.commitHeadline:i.defaultCommitHeadline,commitBody:"string"==typeof e.node.config.commitBody?e.node.config.commitBody:i.defaultCommitBody,authorEmail:"string"==typeof e.node.config.authorEmail?e.node.config.authorEmail:null},"WORKFLOW_AUTOMATION");return{output:a,sessionPatch:{pr:{state:a.state}},links:[os(e)]}}),k.register("GITHUB_COLLECT_REVIEW_THREADS",async e=>{let t=od(e),r=await E.github.pullRequest(t.owner,t.name,og(e),"WORKFLOW_AUTOMATION");if(!r)throw Error("Pull request was not found");let i=r.reviewThreads.filter(({isResolved:e})=>!e);return{output:i,sessionPatch:{pr:{unresolvedThreads:i}},links:[os(e,r.title,r.url)]}}),k.register("GITHUB_REPLY_REVIEW_THREAD",async e=>{let t=await E.github.replyToReviewThread(s9(e.node.config.threadId,"Review thread ID",500),s9(e.node.config.body,"Review reply",1e5),"WORKFLOW_AUTOMATION"),r=oo(e);return{output:t,links:r?[r]:void 0}}),k.register("GITHUB_SET_REVIEW_THREAD_RESOLVED",async e=>{let t=await E.github.setReviewThreadResolved(s9(e.node.config.threadId,"Review thread ID",500),!1!==e.node.config.resolved,"WORKFLOW_AUTOMATION"),r=oo(e);return{output:t,links:r?[r]:void 0}}),k.register("GITHUB_CREATE_PR",async e=>{let t=od(e),r=await E.github.createPullRequest({...t,baseRefName:s9(e.node.config.baseRefName??(0,si.getSessionValue)(e.sessionData,"worktree.baseBranch"),"Base branch",500),headRefName:s9(e.node.config.headRefName??(0,si.getSessionValue)(e.sessionData,"worktree.branch"),"Head branch",500),title:s9(e.node.config.title??(0,si.getSessionValue)(e.sessionData,"ticket.title"),"Pull request title",500),body:"string"==typeof e.node.config.body?e.node.config.body:null,draft:!0===e.node.config.draft});await E.worktrees.attachPullRequestForBranch(`github.com/${t.owner}/${t.name}`,r.headRefName,r);let i=oh(r);return{output:i,sessionPatch:{pr:i},links:[oa("PULL_REQUEST",sF(t.owner,t.name,r.number),r.title,r.url)]}}),k.register("GITHUB_SET_PR_LABELS",async e=>{let t=od(e),r=Array.isArray(e.node.config.labels)?e.node.config.labels.map(String):[],i=await E.github.setPullRequestLabels({...t,number:og(e),labels:r});return{output:i.labels,sessionPatch:{pr:{labels:i.labels}},links:[os(e)]}}),k.register("GITHUB_RETRY_PIPELINE",async e=>{let t=await E.github.retryPipeline(s9(e.node.config.repositoryId??(0,si.getSessionValue)(e.sessionData,"pr.repositoryGithubId"),"GitHub repository ID",500),s9(e.node.config.checkSuiteId??(0,si.getSessionValue)(e.sessionData,"pipeline.checkSuiteId"),"Check suite ID",500),"WORKFLOW_AUTOMATION",{actor:"workflow",ipAddress:null}),r=ol(e);return{output:t,sessionPatch:{pipeline:{status:t.status}},links:r?[r]:void 0}}),k.register("GITHUB_RETRY_JOB",async e=>{let t=await E.github.retryWorkflowJob(s9(e.node.config.repositoryId,"GitHub repository ID",500),s9(e.node.config.checkSuiteId,"Check suite ID",500),s9(e.node.config.jobId,"Workflow job ID",500),"WORKFLOW_AUTOMATION",{actor:"workflow",ipAddress:null}),r=ol(e);return{output:t,links:r?[r]:void 0}}),k.register("GITHUB_CANCEL_WORKFLOW_RUN",async e=>{let t=await E.github.cancelActionsWorkflowRun(s9(e.node.config.codebaseRepositoryId??(0,si.getSessionValue)(e.sessionData,"repo.id"),"Codebase repository ID",500),s9(e.node.config.workflowRunId??(0,si.getSessionValue)(e.sessionData,"pipeline.runId"),"Workflow run ID",500),!0===e.node.config.force,"WORKFLOW_AUTOMATION",{actor:"workflow",ipAddress:null}),r=ol(e);return{output:t,sessionPatch:{pipeline:{status:"CANCELLED"}},links:r?[r]:void 0}}),k.register("GITHUB_SAVE_AUTO_RETRY",async e=>({output:await E.github.saveAutoRetryRule(s5(e.node.config.input,"Auto-retry rule"))})),k.register("GITHUB_WAIT_CHECKS",async e=>{let t=s9(e.node.config.repositoryId??(0,si.getSessionValue)(e.sessionData,"repo.id"),"Repository ID",500),r=s9(e.node.config.workflowRunId??(0,si.getSessionValue)(e.sessionData,"pipeline.runId"),"Workflow run ID",500),i=ol(e);return{links:i?[i]:void 0,wait:{kind:"GITHUB_CHECKS",externalKey:JSON.stringify({repositoryId:t,workflowRunId:r}),resumeAfter:s6(e.node.config),timeoutAt:s3(e.node.config)}}}),S=eh,I=e,S.register("WORKTREE_CREATE",async e=>{let t=ob(e),r=await I.worktrees.createWorktree({codebaseId:ow(e),selection:t,requestId:ot(e,"create")});return oi(e,r,{worktree:{branch:t.branchName,baseBranch:t.baseBranch}})}),S.register("WORKTREE_CHANGE_BRANCH",async e=>{let t=oy(e),r=ob(e),i=await I.worktrees.changeWorktreeBranch({worktreeId:t,selection:r,requestId:ot(e,"change-branch"),stashOnFailure:!0===e.node.config.stashOnFailure});return oi(e,i,{worktree:{branch:r.branchName,baseBranch:r.baseBranch}},[oa("WORKTREE",t,"Worktree")])}),S.register("WORKTREE_COMMIT",async e=>{let t=oy(e),r=!1!==e.node.config.stageAll,i=e.node.config.paths,a=Array.isArray(i)?i.map(e=>s9(e,"Selected path",2e3)):[],n=await I.worktrees.commitWorktree({worktreeId:t,message:s9(e.node.config.message,"Commit message",5e4),signed:"boolean"==typeof e.node.config.signed?e.node.config.signed:null,stageAll:r,paths:a,requestId:ot(e,"commit")});return oi(e,n,void 0,[oa("WORKTREE",t,"Worktree")])}),S.register("WORKTREE_REFRESH_PULL_REQUEST",async e=>{let t=oy(e),r=(await I.worktrees.refreshPullRequest(t)).pullRequest,i=r?oh(r):null,a=[oa("WORKTREE",t,"Worktree")];if(r){let[e,t]=r.repositoryNameWithOwner.split("/");e&&t&&a.push(oa("PULL_REQUEST",sF(e,t,r.number),r.title,r.url))}return{output:{found:!!r,pullRequest:r},sessionPatch:{pr:i},links:a}}),S.register("WORKTREE_OPERATION",async e=>{let t=String(e.node.config.operation??"SYNC").toUpperCase();if("OPEN_EDITOR"===t||!i0.WORKTREE_OPERATIONS.includes(t))throw Error("Worktree operation is invalid for workflow execution");let r=oy(e),i=await I.worktrees.runOperation(r,t,ot(e,t.toLowerCase()),!0===e.node.config.forcePreparations);return oi(e,i,void 0,[oa("WORKTREE",r,"Worktree")])}),S.register("WORKTREE_PREPARATION",async e=>{let t=oy(e),r=String(e.node.config.action??"INSPECT").toUpperCase();if(!i0.WORKTREE_PREPARATION_ACTIONS.includes(r))throw Error("Worktree preparation action is invalid");let i=await I.worktrees.runPreparations([t],r,ot(e,`preparation-${r.toLowerCase()}`)),a=i.jobs[0];if(!a)throw Error(i.skipped[0]?.reason??"Worktree preparation was not dispatched");return oi(e,a,void 0,[oa("WORKTREE",t,"Worktree")])}),S.register("WORKTREE_SET_AUTO_SYNC",async e=>{let t=oy(e),r=String(e.node.config.action??"ENABLE").toUpperCase();if("FORCE"===r){let r=await I.worktreeAutomations.forceAutoSync(t,ot(e,"force-auto-sync"));return oi(e,r,void 0,[oa("WORKTREE",t,"Worktree")])}let i="CANCEL"===r?{cancelled:await I.worktreeAutomations.cancelAutoSync(t)}:"RETRY"===r?await I.worktreeAutomations.retryAutoSync(t):"ENABLE"===r?await I.worktreeAutomations.configureAutoSync({worktreeId:t,conflictWorkflowId:s7(e.node.config.conflictWorkflowId,500),conflictWorkflowChoice:s7(e.node.config.conflictWorkflowChoice,500)}):null;if(!i)throw Error("Unknown Auto Sync action");return{output:i,sessionPatch:{worktree:{autoSync:i}},links:[oa("WORKTREE",t,"Worktree")]}}),S.register("WORKTREE_SET_AUTO_MERGE",async e=>{let t,r=oy(e),i=String(e.node.config.action??"ENABLE").toUpperCase();if("CANCEL"===i)t={cancelled:await I.worktreeAutomations.cancelAutoMerge(r)};else if("RETRY"===i)t=await I.worktreeAutomations.retryAutoMerge(r);else if("ENABLE"===i){let i=Number(e.node.config.pullRequestNumber??(0,si.getSessionValue)(e.sessionData,"pr.number"));if(!Number.isInteger(i)||i<1)throw Error("Pull request number must be a positive integer");let a=String(e.node.config.method??"SQUASH").toUpperCase();if(!["MERGE","REBASE","SQUASH"].includes(a))throw Error("Merge method is invalid");t=await I.worktreeAutomations.configureAutoMerge({worktreeId:r,repositoryNameWithOwner:s9(e.node.config.repositoryNameWithOwner??(0,si.getSessionValue)(e.sessionData,"repo.nameWithOwner"),"Repository",500),pullRequestNumber:i,method:a,commitHeadline:s9(e.node.config.commitHeadline??(0,si.getSessionValue)(e.sessionData,"pr.title"),"Commit headline",1e3),commitBody:String(e.node.config.commitBody??""),authorEmail:s7(e.node.config.authorEmail,500),deleteWorktree:!0===e.node.config.deleteWorktree,moveTicketToDone:!0===e.node.config.moveTicketToDone})}else throw Error("Unknown Auto Merge action");return{output:t,sessionPatch:{worktree:{autoMerge:t}},links:[oa("WORKTREE",r,"Worktree")]}}),S.register("WORKTREE_DELETE",async e=>{let t=await I.worktrees.deleteWorktree({worktreeId:oy(e),deleteRemoteBranch:!0===e.node.config.deleteRemoteBranch,requestId:ot(e,"delete")});return oi(e,t)}),S.register("WORKTREE_MOVE",async e=>{let t=await I.worktrees.moveWorktree({sourceWorktreeId:oy(e),targetCodebaseId:s9(e.node.config.targetCodebaseId,"Target codebase ID",500),targetWorktreeId:s7(e.node.config.targetWorktreeId,500),deleteSource:!0===e.node.config.deleteSource,requestId:ot(e,"move")}),r=t.targetWorktreeId??(!0===e.node.config.deleteSource?null:oy(e));return{output:t,links:[...r?[oa("WORKTREE",r,"Worktree")]:[],{kind:"WORKTREE_MOVE",resourceId:t.id,label:"Worktree move"}],wait:{kind:"WORKTREE_MOVE",externalKey:t.id,resumeAfter:s6(e.node.config),timeoutAt:s3(e.node.config)}}}),S.register("WORKTREE_INSPECT",async e=>{let t=oy(e),r=await I.worktrees.inspect(t,ot(e,"inspect"));return{output:r,sessionPatch:{worktree:{commits:r.commits,changes:r.changes,branchChanges:r.branchChanges}},links:[oa("WORKTREE",t,"Worktree")]}}),S.register("WORKTREE_INSPECT_GIT",async e=>{let t=oy(e),r=await I.worktrees.inspectGitState(t,ot(e,"inspect-git"));return{output:r,sessionPatch:{worktree:{...r}},links:[oa("WORKTREE",t,"Worktree")]}}),S.register("WORKTREE_GIT_OPERATION",async e=>{let t=String(e.node.config.operation??"PULL_BRANCH").toUpperCase();if(!i0.WORKTREE_GIT_OPERATIONS.includes(t))throw Error("Worktree Git operation is invalid");let r=oy(e),i=await I.worktrees.runGitOperation({worktreeId:r,operation:t,branch:s7(e.node.config.branch,500),stashOid:s7(e.node.config.stashOid,200),stashChanges:!0===e.node.config.stashChanges,requestId:ot(e,t.toLowerCase())});return oi(e,i,void 0,[oa("WORKTREE",r,"Worktree")])}),S.register("WORKTREE_WAIT_PUSH_READY",async e=>{let t=oy(e);return{links:[oa("WORKTREE",t,"Worktree")],wait:{kind:"WORKTREE_PUSH_READY",externalKey:t,resumeAfter:s6(e.node.config),timeoutAt:s3(e.node.config)}}}),A=eh,x=e,A.register("CODEBASE_FETCH_REFRESH",async e=>{let t=ow(e),r="REFRESH"===e.node.config.operation?rg.CODEBASE_REFRESH_JOB_KIND:rg.CODEBASE_FETCH_JOB_KIND,i=await x.codebases.runOperation(r,[t],ot(e,r)),a=i.jobs[0];if(!a)throw Error(i.skipped[0]?.reason??"Codebase operation was skipped");return oi(e,a,void 0,[oa("CODEBASE",t,"Codebase")])}),A.register("CODEBASE_INSPECT_GIT",async e=>{let t=ow(e),r=await x.codebases.inspectGitState(t,ot(e,"inspect-git"));return{output:r,sessionPatch:{codebase:{...r}},links:[oa("CODEBASE",t,"Codebase")]}}),A.register("CODEBASE_GIT_OPERATION",async e=>{let t=String(e.node.config.operation??"PULL_BRANCH").toUpperCase();if(!rg.CODEBASE_GIT_OPERATIONS.includes(t))throw Error("Codebase Git operation is invalid");let r=ow(e),i=await x.codebases.runGitOperation({codebaseId:r,operation:t,branch:s7(e.node.config.branch,500),stashOid:s7(e.node.config.stashOid,200),stashChanges:!0===e.node.config.stashChanges,requestId:ot(e,t.toLowerCase())});return oi(e,i,void 0,[oa("CODEBASE",r,"Codebase")])}),_=eh,C=e,_.register("BUILD_START",async e=>{let t=String(e.node.config.action??"BUILD").toUpperCase();if(!v.BUILD_ACTIONS.includes(t))throw Error("Build action is invalid");let r=await C.builds.startBuild({worktreeId:oy(e),configurationId:s9(e.node.config.configurationId,"Build configuration ID",500),destination:e.node.config.destination,scriptIds:Array.isArray(e.node.config.scriptIds)?e.node.config.scriptIds.map(String):[],action:t,advancedSettings:e.node.config.advancedSettings,exportWhenComplete:!0===e.node.config.exportWhenComplete,exportSettings:e.node.config.exportSettings,worktreeCoverage:!0===e.node.config.worktreeCoverage,requestId:ot(e,"build"),telemetryRequestOrigin:"workflow"});return{output:r,sessionPatch:{build:{id:r.id,status:r.status,action:r.action}},links:[{kind:"BUILD",resourceId:r.id,label:`${r.action} build`,url:`/builds/${r.id}`}],wait:{kind:"BUILD",externalKey:r.id,resumeAfter:s6(e.node.config),timeoutAt:s3(e.node.config)}}}),_.register("BUILD_READ_TEST_RESULTS",async e=>{let t,r=ov(e),i=(await C.builds.reportsForBuild(r)).filter(({kind:e,status:t})=>"TEST_RESULTS"===e&&"READY"===t).at(-1);if(!i)throw Error("Test results are not ready");let a=s5(JSON.parse(i.summaryJson),"Test summary"),n=s5(JSON.parse(i.dataJson),"Test results");return{output:{summary:a,tests:n.tests??[]},sessionPatch:{build:{testSummary:a,tests:n.tests??[]}},links:[oa("BUILD",r,"Build",t)]}}),_.register("BUILD_READ_COVERAGE",async e=>{let t=ov(e),r=(await C.builds.reportsForBuild(t)).filter(({kind:e,status:t})=>"CODE_COVERAGE"===e&&"READY"===t).at(-1);if(!r)throw Error("Coverage results are not ready");let i=s5(JSON.parse(r.summaryJson),"Coverage summary"),a=s5(JSON.parse(r.dataJson),"Coverage results");return{output:{summary:i,files:a.files??[],changedFiles:a.changedFiles??[]},sessionPatch:{build:{coverageSummary:i,coverageFiles:a.files??[],changedCoverageFiles:a.changedFiles??[]}},links:[oa("BUILD",t,"Build",`/builds/${t}/coverage`)]}}),_.register("BUILD_IMPORT_COVERAGE",async e=>{let t=oy(e),r=await C.builds.importCoverageReport({worktreeId:t,buildName:s7(e.node.config.buildName,200)??s7((0,si.getSessionValue)(e.sessionData,"workflow.name"),200)??"Coverage report",reportPath:s9(e.node.config.reportPath??"coverage/lcov.info","Coverage file",4e3),format:s7(e.node.config.format)??"AUTO",requestId:ot(e,"coverage-import")}),i=[oa("WORKTREE",t,"Worktree"),oa("BUILD",r.id,"Build",`/builds/${r.id}`)];return"jobId"in r&&"string"==typeof r.jobId?oi(e,{id:r.jobId,timeoutSeconds:300},{build:{id:r.id}},i):{output:r,sessionPatch:{build:{id:r.id}},links:i}}),_.register("BUILD_EXPORT",async e=>{let t,r,i=ov(e),a=await C.builds.exportArchive({buildId:i,requestId:ot(e,"export"),settings:s5(e.node.config.settings,"Export settings")});return a.jobId?oi(e,{id:a.jobId,timeoutSeconds:3600},{build:{exportId:a.id}},[oa("BUILD",i,"Build",t)]):{output:a,links:[oa("BUILD",i,"Build",r)]}}),_.register("BUILD_DEPLOY",async e=>{let t,r,i=ov(e),a=await C.builds.runBuild({buildId:i,destinations:Array.isArray(e.node.config.destinations)?e.node.config.destinations:[],requestId:ot(e,"deploy")}),n=a.find(({jobId:e})=>!!e)?.jobId;return n?oi(e,{id:n,timeoutSeconds:3600},void 0,[oa("BUILD",i,"Build",t)]):{output:a,links:[oa("BUILD",i,"Build",r)]}}),_.register("BUILD_CANCEL",async e=>{let t,r=ov(e),i=await C.builds.cancelBuild(r);return{output:i,sessionPatch:{build:{id:i?.id,status:i?.status}},links:[oa("BUILD",r,"Build",t)]}}),R=eh,T=e,ey=async e=>{let t=await T.diskSpace.snapshot(e);return{output:t,sessionPatch:t,links:[oa("AGENT",e,t.agent.name,`/agents/${encodeURIComponent(e)}`)]}},R.register("DISK_SPACE_LOAD",async e=>ey(ok(e))),R.register("DISK_SPACE_REFRESH",async e=>{let t=ok(e),r=await T.diskSpace.requestRefresh(t);return{output:r,links:[oa("AGENT",t,"Agent",`/agents/${encodeURIComponent(t)}`)],wait:{kind:"DISK_SPACE_REPORT",externalKey:JSON.stringify(r),resumeAfter:s6(e.node.config,2),timeoutAt:s3(e.node.config,180)}}}),R.register("DISK_SPACE_UPDATE_THRESHOLDS",async e=>{let t=await T.diskSpace.updateSettings({normalThresholdGiB:Number(e.node.config.normalThresholdGiB),pressureThresholdGiB:Number(e.node.config.pressureThresholdGiB)});return{output:t,sessionPatch:{disk:t}}}),R.register("DISK_SPACE_SET_MONITORING",async e=>{let t=ok(e);return await T.diskSpace.setMonitoring(t,!0===e.node.config.enabled),ey(t)}),R.register("DISK_SPACE_SET_PRESSURE_MODE",async e=>{let t=ok(e);return await T.diskSpace.setManualPressureMode(t,!0===e.node.config.enabled),ey(t)}),function(e,t){for(let[r,i]of(e.register("RUN_CREATE_PLAN",async e=>{let r=await t.runs.create(oS(e,"PLAN"));if(!r)throw Error("Plan could not be created");return or(e,r,!0)}),e.register("RUN_CREATE_SESSION",async e=>{let r=await t.runs.create(oS(e,"SESSION"));if(!r)throw Error("Session could not be created");return or(e,r,!0)}),e.register("RUN_PLAY_PLAN",async e=>{let r=e.node.config.worktreeConcurrencyLimit,i=await t.runs.playPlan(oE(e),Array.isArray(e.node.config.mcpPresetIds)?e.node.config.mcpPresetIds.map(String):[],"number"==typeof r?r:void 0,e.run.id);if(!i)throw Error("Plan could not be played");return or(e,i,!0)}),e.register("RUN_FOLLOW_UP",async e=>{let r=oS(e,"SESSION"),i=await t.runs.followUp(oE(e),{...r,followUpMode:s9(e.node.config.followUpMode??"RESUME","Follow-up mode",50),contextMode:s7(e.node.config.contextMode,50)});if(!i)throw Error("Follow-up could not be created");return or(e,i,!0)}),e.register("RUN_STEER",async e=>{let r=await t.runs.steer(oE(e),s9(e.node.config.prompt,"Steering prompt",2e5),Array.isArray(e.node.config.attachmentIds)?e.node.config.attachmentIds.map(String):[]);if(!r)throw Error("Run could not be steered");return or(e,r)}),e.register("RUN_ANSWER",async e=>{let r=await t.runs.answerQuestion(s9(e.node.config.batchId,"Question batch ID",500),e.node.config.answers??{});if(!r)throw Error("Question could not be answered");return or(e,r)}),[["RUN_PAUSE","PAUSE"],["RUN_CONTINUE","CONTINUE"],["RUN_CANCEL","CANCEL"]]))e.register(r,async e=>{let r=await t.runs.lifecycle(oE(e),i);if(!r)throw Error("Run lifecycle operation failed");return or(e,r)});e.register("RUN_REVISE_ANSWER",async e=>{let r=s9(e.node.config.batchId,"Question batch ID",500),i=await t.runs.questionBatch(r);if(!i)throw Error("Question batch was not found");if(i.revisionPreparedAt){let i=await t.runs.reviseAnswer(r,e.node.config.answers??{},!0===e.node.config.stash,!1!==e.node.config.rollback);if(!i)throw Error("Answer revision failed");return or(e,i)}await t.runs.prepareAnswerRevision(r);let a=oc(e);return{links:a?[a]:void 0,wait:{kind:"RUN_ANSWER_REVISION",externalKey:JSON.stringify({batchId:r,answers:e.node.config.answers??{},stash:!0===e.node.config.stash,rollback:!1!==e.node.config.rollback}),resumeAfter:s6(e.node.config),timeoutAt:s3(e.node.config)}}}),e.register("RUN_READ_RESULT",async e=>{let r=await t.runs.get(oE(e));if(!r)throw Error("Run was not found");let[i,a,n,s]=await Promise.all([t.runs.events({runId:r.id,first:500}),t.runs.questions({runId:r.id,first:200}),t.runs.usage(r.id),t.runs.linkedItems(r.id)]);return or(e,{...r,events:i,questions:a,usage:n,links:s})}),e.register("RUN_CAPTURE_CHECKPOINT",async e=>{let t=await (0,t1.getPrismaClient)(),r=await t.runCheckpoint.findFirst({where:{runId:oE(e)},orderBy:{createdAt:"desc"}});if(!r)throw Error("Run has no captured checkpoint");let i=oc(e);return{output:r,sessionPatch:{steps:{[e.node.id]:{snapshotId:r.id}}},links:[...i?[i]:[],{kind:"CHECKPOINT",resourceId:r.id,label:`${r.kind} checkpoint`}]}}),e.register("RUN_ARCHIVE_DELETE",async e=>{let r=oE(e),i=!0===e.node.config.delete,a=i?await t.runs.deleteRuns([r]):await t.runs.archive([r],!1!==e.node.config.archived),n=i?null:oc(e);return{output:{id:r,affected:a},links:n?[n]:void 0}})}(eh,e),D=eh,N=e,D.register("SAVED_COMMAND",async e=>{let t=s9(e.node.config.commandId,"Saved command",500),r=await N.commands.getDefinition(t);if(!r||r.archivedAt)throw Error("Saved command is unavailable");let i="FIRE_AND_FORGET"===e.node.config.completionMode?"FIRE_AND_FORGET":"WAIT_FOR_EXIT",a=(0,sQ.commandOutputPattern)(e.node.config),n=(0,sQ.commandOutputMatchMode)(e.node.config),s=Array.isArray((0,si.getSessionValue)(e.sessionData,`steps.${e.node.id}.matches`))?(0,si.getSessionValue)(e.sessionData,`steps.${e.node.id}.matches`):[];if(a&&(s1(a),"WAIT_FOR_EXIT"!==i))throw Error("Output matching requires Wait for exit completion");if("WAIT_FOR_EXIT"===i&&"ALWAYS"===r.restartPolicy)throw Error("Always-restart commands require fire and forget");let o=String(e.node.config.targetMode??"CONTEXT"),l=null,c=null,u=new Set(["ANY_AGENT_HOME","SPECIFIC_AGENT_HOME"]).has(r.targetKind);if("FIXED_AGENT"===o)l=s9(e.node.config.agentId,"Fixed agent",500);else if("FIXED_WORKTREE"===o)c=s9(e.node.config.worktreeId,"Fixed worktree",500);else if(u){let t=(0,si.getSessionValue)(e.sessionData,"agent.id")??(0,si.getSessionValue)(e.sessionData,"codebase.agentId");if("string"==typeof t&&(l=t),!l){let t=(0,si.getSessionValue)(e.sessionData,"worktree.id");if("string"==typeof t){let e=await (0,t1.getPrismaClient)(),r=await e.worktree.findUnique({where:{id:t},select:{codebase:{select:{agentId:!0}}}});l=r?.codebase.agentId??null}}}else{let t=(0,si.getSessionValue)(e.sessionData,"worktree.id");"string"==typeof t&&(c=t)}let d=await N.commands.startRun({commandId:t,agentId:l,worktreeId:c,origin:"WORKFLOW",idempotencyKey:e.attempt.idempotencyKey,blocksGitOperations:e.run.blocksGitOperations});if(!d)throw Error("Command run could not be created");return{output:{id:d.id,displayNumber:d.displayNumber,status:d.status},sessionPatch:{steps:{[e.node.id]:{commandRunId:d.id,displayNumber:d.displayNumber,matches:s,latestMatch:s.at(-1)??null}}},links:[{kind:"COMMAND_RUN",resourceId:d.id,label:`Command #${d.displayNumber}`,url:`/commands/runs/${d.id}`}],wait:"WAIT_FOR_EXIT"===i?{kind:"COMMAND_RUN",externalKey:d.id,predicate:a?{outputMatch:{pattern:a,mode:n,matchCount:s.length,matched:"ONCE"===n&&s.length>0,scanAttempt:1,scanCharacterOffset:0,observedAttempt:0,observedSequence:-1}}:void 0,resumeAfter:s6(e.node.config),timeoutAt:s3(e.node.config)}:void 0}}),D.register("CUSTOM_COMMAND",async e=>{let t=s9(e.node.config.script,"Custom command",1e6),r="FIRE_AND_FORGET"===e.node.config.completionMode?"FIRE_AND_FORGET":"WAIT_FOR_EXIT",i=(0,sQ.commandOutputPattern)(e.node.config),a=(0,sQ.commandOutputMatchMode)(e.node.config),n=Array.isArray((0,si.getSessionValue)(e.sessionData,`steps.${e.node.id}.matches`))?(0,si.getSessionValue)(e.sessionData,`steps.${e.node.id}.matches`):[];if(i&&(s1(i),"WAIT_FOR_EXIT"!==r))throw Error("Output matching requires Wait for exit completion");let s=String(e.node.config.targetMode??"CONTEXT"),o=null,l=null;if("FIXED_AGENT"===s)o=s9(e.node.config.agentId,"Fixed agent",500);else if("FIXED_WORKTREE"===s)l=s9(e.node.config.worktreeId,"Fixed worktree",500);else{let t=(0,si.getSessionValue)(e.sessionData,"worktree.id");if("string"==typeof t)l=t;else{let t=(0,si.getSessionValue)(e.sessionData,"agent.id")??(0,si.getSessionValue)(e.sessionData,"codebase.agentId");"string"==typeof t&&(o=t)}}if(!o&&!l)throw Error("Custom command context has no agent or worktree target");let c=await N.commands.startCustomRun({script:t,agentId:o,worktreeId:l,origin:"WORKFLOW",idempotencyKey:e.attempt.idempotencyKey,blocksGitOperations:e.run.blocksGitOperations});if(!c)throw Error("Custom command run could not be created");return{output:{id:c.id,displayNumber:c.displayNumber,status:c.status},sessionPatch:{steps:{[e.node.id]:{commandRunId:c.id,displayNumber:c.displayNumber,matches:n,latestMatch:n.at(-1)??null}}},links:[{kind:"COMMAND_RUN",resourceId:c.id,label:`Command #${c.displayNumber}`,url:`/commands/runs/${c.id}`}],wait:"WAIT_FOR_EXIT"===r?{kind:"COMMAND_RUN",externalKey:c.id,predicate:i?{outputMatch:{pattern:i,mode:a,matchCount:n.length,matched:"ONCE"===a&&n.length>0,scanAttempt:1,scanCharacterOffset:0,observedAttempt:0,observedSequence:-1}}:void 0,resumeAfter:s6(e.node.config),timeoutAt:s3(e.node.config)}:void 0}}),D.register("SKILL_APPLY",async e=>{let t=await N.skills.prepareSync(e.node.config.groupId?"GROUP":"ALL",s7(e.node.config.groupId,500),!1);if(!t)throw Error("Skill sync could not be prepared");return{output:t,links:[{kind:"SKILL_RUN",resourceId:t.id,label:"Skill sync",url:`/skills/sync/${t.id}`}],wait:{kind:"SKILL_RUN",externalKey:t.id,resumeAfter:s6(e.node.config),timeoutAt:s3(e.node.config)}}}),D.register("NOTIFICATION_SEND",async e=>{let t=await (0,t1.getPrismaClient)(),r=await t.$transaction(t=>N.notifications.recordInTransaction(t,{dedupeKey:`${e.run.id}:${e.node.id}:${e.attempt.generation}`,typeKey:"WORKFLOW_MESSAGE",title:s9(e.node.config.title,"Notification title",240),body:s9(e.node.config.body,"Notification body",1e3),href:"string"==typeof e.node.config.href?e.node.config.href:`/workflows/runs/${e.run.id}`,resourceKind:"WORKFLOW_RUN",resourceId:e.run.id,worktreeId:"string"==typeof(0,si.getSessionValue)(e.sessionData,"worktree.id")?String((0,si.getSessionValue)(e.sessionData,"worktree.id")):null}));return N.notifications.created(r),{output:r}}),D.register("IOS_PUSH_SEND",async e=>({output:await N.pushNotifications.send({requestId:ot(e,"ios-push"),editor:e.node.config.editor,targetMode:s9(e.node.config.targetMode??"ALL","Push target mode",50),registrationIds:Array.isArray(e.node.config.registrationIds)?e.node.config.registrationIds.map(String):[],channelId:s7(e.node.config.channelId,500),directToken:s7(e.node.config.directToken,2e4),directTokenEncoding:"BASE64"===e.node.config.directTokenEncoding?"BASE64":"HEX",directEnvironment:"PRODUCTION"===e.node.config.directEnvironment?"PRODUCTION":"SANDBOX"})})),D.register("MCP_CALL",async e=>{let t=await N.tools.callTool({groupId:s9(e.node.config.groupId,"MCP tool group",500),name:s9(e.node.config.name,"MCP tool name",500),arguments:s5(e.node.config.arguments??{},"MCP arguments")},{caller:`workflow:${e.run.id}`,correlationId:e.attempt.id,source:"WORKFLOW"});return{output:t,sessionPatch:{steps:{[e.node.id]:{output:t}}}}}),function(e,t){let r=async(e,r,i,a,n={})=>{let s=s5(await t.tools.callTool({groupId:r,name:i,arguments:a},{caller:`workflow:${e.run.id}`,correlationId:e.attempt.id,source:"WORKFLOW"}),`${i} tool result`),o=s5(s.structuredContent,`${i} structured content`),l=n.sessionPatch?await n.sessionPatch(o):{};return{output:o,sessionPatch:{steps:{[e.node.id]:{output:o}},...l},wait:n.wait?.(o)}},i=(e,t,r,i)=>({kind:t,externalKey:r,resumeAfter:s6(e.node.config),timeoutAt:s3(e.node.config,i)}),a=(e,t,r,i)=>oe(e,t,r,i),n=e=>({projectId:a(e,"projectId","pr.projectId","GitLab project ID"),iid:Number(e.node.config.iid??(0,si.getSessionValue)(e.sessionData,"pr.iid")??(0,si.getSessionValue)(e.sessionData,"pr.number"))}),s=e=>({pr:s5(e.mergeRequest,"GitLab merge request output")});for(let[o,l]of(e.register("COMMAND_RERUN",async e=>{let t=a(e,"commandRunId","command.id","Command run ID");return r(e,"builtin:commands","rerun_command",{id:t},{sessionPatch:e=>({command:s5(e.run,"Command run output")}),wait:t=>i(e,"COMMAND_RUN",s9(s5(t.run,"Command run output").id,"Command run ID",500))})}),e.register("COMMAND_TERMINATE",async e=>{let t=a(e,"commandRunId","command.id","Command run ID");return r(e,"builtin:commands","terminate_command_run",{id:t},{sessionPatch:e=>({command:s5(e.run,"Command run output")})})}),e.register("COMMAND_READ_OUTPUT",async e=>{let t=a(e,"commandRunId","command.id","Command run ID");return r(e,"builtin:commands","get_command_run_output",{runId:t,first:Number(e.node.config.first??1e3)},{sessionPatch:e=>({command:{id:t,output:e.chunks}})})}),e.register("WORKTREE_INSPECT_DIFF",async e=>{let t=a(e,"worktreeId","worktree.id","Worktree ID");return r(e,"builtin:worktrees","inspect_worktree_diff",{worktreeId:t,scope:s9(e.node.config.scope,"Diff scope",100),path:e.node.config.path,previousPath:e.node.config.previousPath,commitSha:e.node.config.commitSha,requestId:ot(e,"diff")},{sessionPatch:e=>({worktree:{id:t,diff:e.inspection}})})}),e.register("WORKTREE_UPDATE_METADATA",async e=>{let i=a(e,"worktreeId","worktree.id","Worktree ID");return r(e,"builtin:worktrees","update_worktree_metadata",{id:i,baseBranch:e.node.config.baseBranch,highlightColor:e.node.config.highlightColor},{sessionPatch:async e=>(0,si.mergeSessionData)(await t.worktrees.workflowSessionDataForWorktree(i,{includeMissing:!0}),{worktree:s5(e.worktree,"Worktree output")})})}),e.register("WORKTREE_MOVE_CONTROL",e=>r(e,"builtin:worktrees","CANCEL"===e.node.config.operation?"cancel_worktree_move":"retry_worktree_move_with_stash",{id:s9(e.node.config.moveId,"Move ID",500)},{sessionPatch:async e=>{let r=s5(e.move,"Worktree move output"),i="string"==typeof r.targetWorktreeId&&r.targetWorktreeId||"string"==typeof r.sourceWorktreeId&&r.sourceWorktreeId||null,a=i?await t.worktrees.workflowSessionDataForWorktree(i,{includeMissing:!0}):{};return(0,si.mergeSessionData)(a,{worktree:{move:r}})}})),e.register("BUILD_REBUILD",async e=>{let t=a(e,"buildId","build.id","Build ID");return r(e,"builtin:builds","rebuild_build",{buildId:t,requestId:ot(e,"rebuild")},{sessionPatch:e=>({build:s5(e.build,"Build output")}),wait:t=>i(e,"BUILD",s9(s5(t.build,"Build output").id,"Build ID",500))})}),e.register("BUILD_GENERATE_REPORT",async e=>{let t=a(e,"buildId","build.id","Build ID");return r(e,"builtin:builds","generate_build_report",{buildId:t,kind:"TEST_RESULTS"===e.node.config.reportKind?"TEST_RESULTS":"CODE_COVERAGE",requestId:ot(e,"report")},{sessionPatch:e=>({build:{id:t,report:e.report}})})}),e.register("BUILD_DELETE",e=>{let t=Array.isArray(e.node.config.buildIds)?e.node.config.buildIds.map(String):[a(e,"buildId","build.id","Build ID")];return r(e,"builtin:builds","delete_builds",{ids:t},{sessionPatch:e=>({build:{ids:t,deletedCount:e.count}})})}),e.register("SKILL_PREPARE_SYNC",e=>r(e,"builtin:skills","prepare_skill_sync",{kind:String(e.node.config.syncKind??"ALL"),groupId:e.node.config.groupId},{sessionPatch:e=>({skillSync:s5(e.run,"Skill sync output")})})),e.register("SKILL_RESOLVE_SYNC",e=>r(e,"builtin:skills","resolve_skill_sync_conflict",{input:{runId:a(e,"runId","skillSync.id","Skill sync run ID"),itemId:s9(e.node.config.itemId,"Conflict item ID",500),resolution:String(e.node.config.resolution??"SKIP")}},{sessionPatch:e=>({skillSync:s5(e.run,"Skill sync output")})})),e.register("SKILL_SKIP_SYNC",e=>r(e,"builtin:skills","skip_skill_sync",{runId:a(e,"runId","skillSync.id","Skill sync run ID")},{sessionPatch:e=>({skillSync:s5(e.run,"Skill sync output")})})),e.register("BUILD_DATA_REFRESH",e=>r(e,"builtin:build-data","refresh_build_data",{requestId:ot(e,"build-data")},{sessionPatch:e=>({buildData:s5(e.collection,"Build-data collection output")}),wait:t=>{let r=s5(t.collection,"Build-data collection output");return"COMPLETED"===r.status?void 0:i(e,"BUILD_DATA_COLLECTION",s9(r.id,"Build-data collection ID",500),90)}})),e.register("BUILD_DATA_DELETE",e=>r(e,"builtin:build-data","delete_build_data_entries",{collectionId:a(e,"collectionId","buildData.id","Build-data collection ID"),entryIds:Array.isArray(e.node.config.entryIds)?e.node.config.entryIds.map(String):[],requestId:ot(e,"build-data-delete"),overrideProtection:!0===e.node.config.overrideProtection},{sessionPatch:e=>({buildData:s5(e.collection,"Build-data collection output")})})),e.register("BUILD_DATA_SET_LOCK",e=>{let t=a(e,"collectionId","buildData.id","Build-data collection ID");return r(e,"builtin:build-data","set_build_data_lock",{collectionId:t,entryId:s9(e.node.config.entryId,"Entry ID",500),locked:!0===e.node.config.locked},{sessionPatch:e=>({buildData:{id:t,entry:e.entry}})})}),e.register("SIGNING_REFRESH",e=>r(e,"builtin:signing-assets","refresh_signing_assets",{agentIds:Array.isArray(e.node.config.agentIds)?e.node.config.agentIds.map(String):void 0},{sessionPatch:e=>({signing:{jobs:e.operation}}),wait:t=>{let r=Array.isArray(t.operation)?t.operation.flatMap(e=>{if(!e||"object"!=typeof e||Array.isArray(e))return[];let t=e.id;return"string"==typeof t&&t?[t]:[]}):[];return r.length?i(e,"AGENT_JOBS",JSON.stringify({ids:r}),90):void 0}})),e.register("SIGNING_SYNC_PROFILE",e=>r(e,"builtin:signing-assets","sync_signing_profile",{uuid:a(e,"uuid","signingProfile.id","Profile UUID"),sourceAgentId:s9(e.node.config.sourceAgentId,"Source agent ID",500),targetAgentIds:Array.isArray(e.node.config.targetAgentIds)?e.node.config.targetAgentIds.map(String):[]},{sessionPatch:e=>({signing:{operation:e.operation}}),wait:t=>i(e,"SIGNING_OPERATIONS",JSON.stringify({ids:[s9(s5(t.operation,"Signing operation output").id,"Signing operation ID",500)]}),300)})),e.register("SIGNING_DELETE_EXPIRED",e=>r(e,"builtin:signing-assets","delete_expired_signing_profiles",{agentIds:Array.isArray(e.node.config.agentIds)?e.node.config.agentIds.map(String):void 0},{sessionPatch:e=>({signing:{operations:e.operation}}),wait:t=>{let r=Array.isArray(t.operation)?t.operation.flatMap(e=>{if(!e||"object"!=typeof e||Array.isArray(e))return[];let t=e.id;return"string"==typeof t&&t?[t]:[]}):[];return r.length?i(e,"SIGNING_OPERATIONS",JSON.stringify({ids:r}),300):void 0}})),e.register("IOS_DEVICE_REGISTER",e=>r(e,"builtin:ios-devices","register_ios_device",{id:a(e,"deviceId","device.id","Device ID")},{sessionPatch:e=>({device:s5(e.device,"iOS device output")})})),e.register("IOS_DEVICE_REJECT",e=>r(e,"builtin:ios-devices","reject_ios_device",{id:a(e,"deviceId","device.id","Device ID")},{sessionPatch:e=>({device:s5(e.device,"iOS device output")})})),e.register("AGENT_RECONCILE",async e=>{let r=Array.isArray(e.node.config.agentIds)?e.node.config.agentIds.map(String):(await t.agentControl.listAgents()).map(({id:e})=>e),i=await t.agentControl.requestCodebaseReconcile(r);return{output:{requested:i},sessionPatch:{agent:{requested:i}}}}),e.register("AGENT_UPDATE_CADENCE",async e=>{let r=await t.agentControl.updateCadenceSettings(a(e,"agentId","agent.id","Agent ID"),s5(e.node.config.settings,"Cadence settings"));return{output:r,sessionPatch:{agent:s5(r,"Agent output")}}}),e.register("CCUSAGE_COLLECT",async e=>{let r=await t.ccusage.collect(ot(e,"ccusage"));return{output:r,sessionPatch:{usage:r}}}),e.register("MODEL_COST_REFRESH",async()=>{let e=await t.modelCosts.refresh();return{output:e,sessionPatch:{modelCosts:e}}}),e.register("GITLAB_LOAD_MR",e=>r(e,"builtin:gitlab","gitlab_get_merge_request",n(e),{sessionPatch:s})),e.register("GITLAB_CREATE_MR",e=>r(e,"builtin:gitlab","gitlab_create_merge_request",{projectId:a(e,"projectId","repo.gitlabProjectId","GitLab project ID"),sourceBranch:a(e,"sourceBranch","worktree.branch","Source branch"),targetBranch:a(e,"targetBranch","worktree.baseBranch","Target branch"),title:s9(e.node.config.title??(0,si.getSessionValue)(e.sessionData,"ticket.title"),"Merge request title",500),description:s7(e.node.config.description),removeSourceBranch:!0===e.node.config.removeSourceBranch,squash:!0===e.node.config.squash,reviewerIds:Array.isArray(e.node.config.reviewerIds)?e.node.config.reviewerIds.map(String):[],labels:Array.isArray(e.node.config.labels)?e.node.config.labels.map(String):[]},{sessionPatch:s})),e.register("GITLAB_UPDATE_MR",e=>r(e,"builtin:gitlab","gitlab_update_merge_request",{...n(e),title:s7(e.node.config.title),description:s7(e.node.config.description),stateEvent:s7(e.node.config.stateEvent),reviewerIds:Array.isArray(e.node.config.reviewerIds)?e.node.config.reviewerIds.map(String):void 0,labels:Array.isArray(e.node.config.labels)?e.node.config.labels.map(String):void 0},{sessionPatch:s})),e.register("GITLAB_SUBMIT_REVIEW",e=>r(e,"builtin:gitlab","gitlab_submit_review",{...n(e),outcome:String(e.node.config.outcome??"COMMENT"),body:s7(e.node.config.body)})),e.register("GITLAB_REPLY_DISCUSSION",e=>r(e,"builtin:gitlab","gitlab_reply_discussion",{...n(e),discussionId:s9(e.node.config.discussionId,"Discussion ID",500),body:s9(e.node.config.body,"Discussion reply",1e5)})),e.register("GITLAB_SET_DISCUSSION_RESOLVED",e=>r(e,"builtin:gitlab","gitlab_set_discussion_resolved",{...n(e),discussionId:s9(e.node.config.discussionId,"Discussion ID",500),resolved:!1!==e.node.config.resolved})),e.register("GITLAB_MERGE_MR",e=>r(e,"builtin:gitlab","gitlab_merge_merge_request",{...n(e),squash:!0===e.node.config.squash,removeSourceBranch:!0===e.node.config.removeSourceBranch,autoMerge:!0===e.node.config.autoMerge,sha:s7(e.node.config.sha)},{sessionPatch:s})),[["GITLAB_SET_MR_LABELS","labels"],["GITLAB_REQUEST_REVIEWERS","reviewerIds"]]))e.register(o,e=>r(e,"builtin:gitlab","gitlab_update_merge_request",{...n(e),[l]:Array.isArray(e.node.config[l])?e.node.config[l].map(String):[]},{sessionPatch:s}));for(let[t,i,n,s]of(e.register("GITLAB_CREATE_PIPELINE",e=>r(e,"builtin:gitlab","gitlab_create_pipeline",{projectId:a(e,"projectId","repo.gitlabProjectId","GitLab project ID"),ref:a(e,"ref","worktree.branch","Git ref"),variables:Array.isArray(e.node.config.variables)?e.node.config.variables:[]},{sessionPatch:e=>({pipeline:e.pipeline})})),[["GITLAB_RETRY_PIPELINE","gitlab_retry_pipeline","pipelineId","pipeline.id"],["GITLAB_CANCEL_PIPELINE","gitlab_cancel_pipeline","pipelineId","pipeline.id"],["GITLAB_RETRY_JOB","gitlab_retry_job","jobId","job.id"]]))e.register(t,e=>r(e,"builtin:gitlab",i,{projectId:a(e,"projectId","repo.gitlabProjectId","GitLab project ID"),[n]:a(e,n,s,n)},{sessionPatch:e=>"jobId"===n?{job:e.job}:{pipeline:e.pipeline}}));e.register("GITLAB_SAVE_AUTO_RETRY",e=>r(e,"builtin:gitlab","gitlab_save_auto_retry_rule",s5(e.node.config.input,"GitLab auto-retry rule"))),e.register("GITLAB_WAIT_PIPELINE",e=>Promise.resolve({wait:{kind:"GITLAB_PIPELINE",externalKey:JSON.stringify({projectId:a(e,"projectId","repo.gitlabProjectId","GitLab project ID"),pipelineId:a(e,"pipelineId","pipeline.id","GitLab pipeline ID")}),resumeAfter:s6(e.node.config),timeoutAt:s3(e.node.config)}}));let o=async(e,t,i)=>{let a=await r(e,"builtin:github",t,i),n=s5(a.output,"GitHub tool output"),s=oh(s5(n.pullRequest,"Pull request output"));return{...a,sessionPatch:{...a.sessionPatch,pr:s}}},l=e=>({owner:s9(e.node.config.owner??(0,si.getSessionValue)(e.sessionData,"repo.owner"),"Repository owner",200),name:s9(e.node.config.name??(0,si.getSessionValue)(e.sessionData,"repo.name"),"Repository name",200),number:Number(e.node.config.number??(0,si.getSessionValue)(e.sessionData,"pr.number"))});e.register("GITHUB_UPDATE_PR",e=>o(e,"update_pull_request",{...l(e),title:s7(e.node.config.title),body:"string"==typeof e.node.config.body?e.node.config.body:void 0,draft:"boolean"==typeof e.node.config.draft?e.node.config.draft:void 0})),e.register("GITHUB_SUBMIT_REVIEW",e=>o(e,"submit_pull_request_review",{...l(e),event:String(e.node.config.event??"COMMENT"),body:"string"==typeof e.node.config.body?e.node.config.body:void 0})),e.register("GITHUB_REQUEST_REVIEWERS",e=>o(e,"request_pull_request_reviewers",{...l(e),reviewers:Array.isArray(e.node.config.reviewers)?e.node.config.reviewers.map(String):[],teamReviewers:Array.isArray(e.node.config.teamReviewers)?e.node.config.teamReviewers.map(String):[]})),e.register("GITHUB_DISPATCH_WORKFLOW",e=>r(e,"builtin:github","dispatch_github_workflow",{repositoryId:a(e,"repositoryId","repo.id","Repository ID"),workflowId:s9(e.node.config.workflowId,"Workflow ID",500),ref:s9(e.node.config.ref,"Git ref",500),inputs:e.node.config.inputs?s5(e.node.config.inputs,"Workflow inputs"):void 0},{sessionPatch:e=>({pipeline:e})}));let c=async(e,t,i)=>{let a=await r(e,"builtin:jira",t,i),n=s5(a.output,"Jira tool output"),s=op(s5(n.ticket,"Jira ticket output"));return{...a,sessionPatch:{...a.sessionPatch,ticket:s}}};e.register("JIRA_CREATE_TICKET",e=>c(e,"create_jira_ticket",{projectKey:s9(e.node.config.projectKey,"Project key",100),issueTypeId:s9(e.node.config.issueTypeId,"Issue type ID",100),summary:s9(e.node.config.summary,"Summary"),description:"string"==typeof e.node.config.description?{format:"MARKDOWN",value:e.node.config.description}:void 0,fields:e.node.config.fields?s5(e.node.config.fields,"Additional Jira fields"):void 0})),e.register("JIRA_ADD_WORKLOG",e=>c(e,"add_jira_worklog",{issueKey:a(e,"issueKey","ticket.key","Issue key"),timeSpentSeconds:Number(e.node.config.timeSpentSeconds),startedAt:s7(e.node.config.startedAt,100),comment:"string"==typeof e.node.config.comment?{format:"MARKDOWN",value:e.node.config.comment}:void 0})),e.register("JIRA_LINK_TICKETS",e=>c(e,"link_jira_tickets",{inwardIssueKey:a(e,"inwardIssueKey","ticket.key","Inward issue key"),outwardIssueKey:s9(e.node.config.outwardIssueKey,"Outward issue key",100),linkType:s9(e.node.config.linkType,"Link type",100)}))}(eh,e),(eg=new oC(L,B,eo,M,{buildData:F,commands:q,credentials:P,iosDevices:ee,polling:j,pushNotifications:V,signingAssets:K,skills:z})).start(),em.startRuntime(),ef.startRuntime(),el.startRuntime(),la.serverServices={prismaService:O,credentialService:P,agentControlService:B,ccusageService:$,buildDataService:F,buildsService:J,codebasesService:Y,codebaseToolsService:Z,jiraService:Q,jiraWebhookService:X,iosDevicesService:ee,gitHubService:ei,gitLabService:ea,gitHubPipelineStatusService:et,gitHubActionsNotificationsService:er,cacheServerService:es,worktreesService:eo,worktreeAutomationService:ef,skillsService:z,telemetryService:G,signingAssetsService:K,pushNotificationsService:V,notificationsService:U,pollingService:j,modelCostsService:H,runsService:W,commandsService:q,diskSpaceService:M,systemStatusService:el,actionCenterService:ec,appsService:eu,globalSearchService:ed,cliHealthService:en,toolsService:ep,workflowEventsService:L,workflowsService:em,workflowEventBridge:eg})}],887394)}];
811
811
 
812
812
  //# sourceMappingURL=_0ssmikd._.js.map