@ai-development-environment/server 0.0.100 → 0.0.101
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.
- package/package.json +1 -1
- package/standalone/.next/BUILD_ID +1 -1
- package/standalone/.next/build-manifest.json +3 -3
- package/standalone/.next/prerender-manifest.json +3 -3
- package/standalone/.next/server/app/[locale]/(dashboard)/builds/[buildId]/output/route.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/(dashboard)/commands/runs/[runId]/output/route.js.nft.json +1 -1
- package/standalone/.next/server/app/_global-error.html +1 -1
- package/standalone/.next/server/app/_global-error.rsc +1 -1
- package/standalone/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
- package/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/standalone/.next/server/app/_not-found.html +1 -1
- package/standalone/.next/server/app/_not-found.rsc +1 -1
- package/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +1 -1
- package/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
- package/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
- package/standalone/.next/server/app/api/agent/build-artifact-transfers/[transferId]/complete/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/agent/build-artifact-transfers/[transferId]/download/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/agent/build-artifact-transfers/[transferId]/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/agent/build-artifact-transfers/[transferId]/upload/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/agent/run-attachments/[attachmentId]/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/build-artifact-uploads/[uploadId]/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/codebases/by-path/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/codebases/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/graphql/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/ios/apns-devices/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/ios/devices/export.tsv/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/ios/enrollment/start/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/ios/notification-devices/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/mcp/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/public/builds/[buildId]/artifacts/[artifactId]/manifest.plist/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/public/builds/[buildId]/artifacts/[artifactId]/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/public/github/webhook/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/public/gitlab/webhook/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/public/ios/enrollment-profile/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/public/ios/profile-response/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/public/jira/webhook/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/public/sse/[token]/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/sse/history/export/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/telemetry/analytics-events/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/telemetry/console-logs/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/telemetry/export/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/tools/call/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/tools/catalog/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/worktrees/[worktreeId]/diff-image/route.js.nft.json +1 -1
- package/standalone/.next/server/chunks/[root-of-the-server]__03aos_4._.js +1 -1
- package/standalone/.next/server/chunks/_0e8lp3p._.js +1 -1
- package/standalone/.next/server/chunks/_0fwwxlu._.js +1 -1
- package/standalone/.next/server/chunks/_0h78qjg._.js +1 -1
- package/standalone/.next/server/chunks/_0ndnc91._.js +1 -1
- package/standalone/.next/server/chunks/_0wpfe7q._.js +1 -1
- package/standalone/.next/server/chunks/_1-vdyhc._.js +1 -1
- package/standalone/.next/server/chunks/_1gt6607._.js +1 -1
- package/standalone/.next/server/chunks/_1jwsn5v._.js +1 -1
- package/standalone/.next/server/chunks/_1qjb83a._.js +1 -1
- package/standalone/.next/server/chunks/_1zwfwcs._.js +1 -1
- package/standalone/.next/server/middleware-build-manifest.js +3 -3
- package/standalone/.next/server/pages/404.html +1 -1
- package/standalone/.next/server/pages/500.html +1 -1
- package/standalone/.next/server/server-reference-manifest.js +1 -1
- package/standalone/.next/server/server-reference-manifest.json +1 -1
- /package/standalone/.next/static/{iNH0xq2KlqMDpWuRmdLMn → y9Hi8CBWpu_MxfgH-bM8Z}/_buildManifest.js +0 -0
- /package/standalone/.next/static/{iNH0xq2KlqMDpWuRmdLMn → y9Hi8CBWpu_MxfgH-bM8Z}/_clientMiddlewareManifest.js +0 -0
- /package/standalone/.next/static/{iNH0xq2KlqMDpWuRmdLMn → y9Hi8CBWpu_MxfgH-bM8Z}/_ssgManifest.js +0 -0
|
@@ -63,7 +63,7 @@ ${i}
|
|
|
63
63
|
${t}`}splitMarkdownIntoSections(e){let t=e.split(/(?=^#{1,6}\s)|(?:\n\s*\n)/m).filter(e=>e.trim().length>0);return t.length>0?t:[e]}async parseMarkdownSection(e){try{let t=[this.createTextFallback(e)];return{success:!0,data:{version:1,type:"doc",content:t},warnings:[]}}catch(e){return{success:!1,error:e,warnings:[]}}}createTextFallback(e){return{type:"paragraph",content:[{type:"text",text:e.trim()}]}}createPlaceholder(e){return e.operation.includes("adfToMarkdown")?`[Error converting ADF to Markdown: ${e.operation}]`:e.operation.includes("markdownToAdf")?{version:1,type:"doc",content:[{type:"paragraph",content:[{type:"text",text:`[Error converting Markdown to ADF: ${e.operation}]`}]}]}:`[Error in operation: ${e.operation}]`}},S2=class{constructor(e){(0,g6.__publicField)(this,"mdToAdfEngine"),(0,g6.__publicField)(this,"adfToMdEngine"),(0,g6.__publicField)(this,"options"),(0,g6.__publicField)(this,"errorRecovery"),(0,g6.__publicField)(this,"remarkProcessor"),(0,g6.__publicField)(this,"registry");try{this.options=e||{},this.mdToAdfEngine=new Sw(this.options),this.adfToMdEngine=new S0(this.options),this.errorRecovery=new S1({maxRetries:e?.maxRetries||3,retryDelay:e?.retryDelay||100,fallbackStrategy:e?.fallbackStrategy||"best-effort",enableLogging:e?.enableLogging||!1,onError:e?.onError,onRecovery:e?.onRecovery}),this.remarkProcessor=yy().use(wF).use(bq,["yaml"]).use(EK).use(E2,{strict:e?.strict||!1}).use(b_),this.registry=new E7,this.registerConverters()}catch(e){throw new E6("Failed to initialize Parser","INIT_ERROR")}}adfToMarkdown(e,t){return t&&Object.keys(t).length>0?new S0({...this.options,...t}).convert(e):this.adfToMdEngine.convert(e)}async adfToMarkdownWithRecovery(e,t){let r=await this.errorRecovery.executeWithRecovery(()=>this.adfToMarkdown(e,t),{operation:"adfToMarkdown",input:e,nodeType:e.type});if(!r.success)throw r.error||Error("ADF to Markdown conversion failed");return r.data}markdownToAdf(e,t){return t&&Object.keys(t).length>0?new Sw({...this.options,...t}).convert(e):this.mdToAdfEngine.convert(e)}async markdownToAdfWithRecovery(e,t){let r=await this.errorRecovery.executeWithRecovery(()=>this.markdownToAdf(e,t),{operation:"markdownToAdf",input:e});if(!r.success)throw r.error||Error("Markdown to ADF conversion failed");return r.data}async markdownToAdfAsync(e,t){return await this.mdToAdfEngine.convertAsync(e)}async markdownToAdfAsyncWithRecovery(e,t){let r=await this.errorRecovery.executeWithRecovery(async()=>this.markdownToAdfAsync(e,t),{operation:"markdownToAdfAsync",input:e});if(!r.success)throw r.error||Error("Async Markdown to ADF conversion failed");return r.data}async validateMarkdownAsync(e){let t=await this.mdToAdfEngine.validate(e);return{valid:t.valid,errors:t.errors.map(e=>({message:e})),warnings:t.warnings}}async getStats(e){return await this.mdToAdfEngine.getStats(e)}stringify(e,t){return this.adfToMarkdown(e,t)}async stringifyAsync(e,t){return this.adfToMarkdownWithRecovery(e,t)}validateAdf(e){return new E4().validate(e)}validateMarkdown(e){return new E5().validate(e)}getErrorRecovery(){return this.errorRecovery}registerConverters(){this.registry.registerNodes([new Sb,new SE,new SS,new Sv,new SI,new SA,new Sk,new S_,new ST,new SC,new SR,new SN,new SO,new SD,new SP,new Sx,new SL,new SU,new SB,new SM,new Sq,new Sj,new S$,new SG,new SF,new Sz]),this.registry.registerMarks([new SH,new SV,new SK,new SW,new SJ,new SY,new SQ,new SZ,new SX])}convertAdfToMarkdown(e){return this.adfToMdEngine.convert(e)}convertMdastToAdf(e){return this.mdToAdfEngine.convert(e)}fallbackConversion(e){return this.mdToAdfEngine.convert(e)}countNodes(e){let t=0;for(let r of e)t++,r.content&&Array.isArray(r.content)&&(t+=this.countNodes(r.content));return t}postProcessAdfFenceBlocks(e){return e}parseAdfLanguageString(e,t){return{}}},S3=e.i(378731);let S4=[/^h[1-6]\.\s/m,/^bq\.\s/m,/\{code(?::[^}]+)?\}/i,/\{noformat\}/i,/\{\{[^}\n]+\}\}/,/^\|\|.+\|\|\s*$/m,/\[[^\]\n]+\|https?:\/\//i,/\[~[^\]\n]+\]/,/\[\^[^\]\n]+\]/,/![^!\n]+!/];function S5(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&"doc"===e.type&&1===e.version&&Array.isArray(e.content)}function S6(e,t){return S3.default.to_markdown(e.replace(/\[~([^\]\n]+)\]/g,"@$1").replace(/\[\^([^\]\n]+)\]/g,"[Attachment: $1]").replace(/\[([A-Z][A-Z0-9_]*-\d+)\]/g,(e,r)=>t?`[${r}](${t}/browse/${r})`:`**${r}**`))}let S8=new S2;function S9(e,t){if(null==e)return null;let r=function(e){if(S5(e))return"ADF";let t="string"==typeof e?e:"";return S4.some(e=>e.test(t))?"JIRA_WIKI":"MARKDOWN"}(e),i="string"==typeof e?e:null==e?"":JSON.stringify(e,null,2),a="ADF"===r?function(e){try{return S8.adfToMarkdown(e)}catch{return function e(t){return t&&"object"==typeof t?["string"==typeof t.text?t.text:"",...Array.isArray(t.content)?t.content.map(e).filter(Boolean):[]].filter(Boolean).join("\n"):""}(e)}}(e):"JIRA_WIKI"===r?S6(i,t):i;return{format:r,raw:e,rawText:i,markdown:a,wikiMarkup:"JIRA_WIKI"===r?i:S3.default.to_jira(a)}}function S7(e){let t=e.value.trim(),r="JIRA_WIKI"===e.format?S6(t):t,i=S8.markdownToAdf(r);if(!S5(i))throw Error("The Jira text could not be converted to valid ADF");return i}let ve="default",vt=["summary","status","issuetype","priority","assignee","project","updated"],vr=[{window:"5m",milliseconds:3e5},{window:"10m",milliseconds:6e5},{window:"1h",milliseconds:36e5},{window:"24h",milliseconds:864e5}];function vi(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function va(e){return vi(e)?e:{}}function vn(e){return Array.isArray(e)?e:[]}function vs(e){return e instanceof Date&&!Number.isNaN(e.getTime())?e.toISOString():"string"==typeof e&&e.length>0?e:null}function vo(e){let t=(e.warnings??[]).flatMap(e=>{let t=va(e),r=vs(t.message);if(r)return[r];let i=vs(t.type);return i?[i]:[]});return[...e.warningMessages??[],...t]}function vl(e){return"number"==typeof e&&Number.isFinite(e)?e:null}function vu(e){let t=e.trim().toUpperCase();if(!/^[A-Z][A-Z0-9_]*-\d+$/.test(t))throw Error("Invalid Jira issue key");return t}function vc(e){if(null===e)return null;try{return JSON.parse(e)}catch{return null}}function vd(e){return vn(vc(e)).flatMap(e=>"string"==typeof e&&e.length>0?[e]:[])}function vh(e){return JSON.stringify(function e(t){return Array.isArray(t)?t.map(e):vi(t)?Object.fromEntries(Object.keys(t).sort().map(r=>[r,e(t[r])])):t}(e))}function vp(e){if(!vi(e))return null;let t=e.status??va(e.response).status;return"number"==typeof t?t:null}function vm(e,t){let r=e instanceof Error?e.message:String(e);return(t?r.replaceAll(t,"[REDACTED]"):r).slice(0,1e3)}function vf(e){return vs(va(va(e.fields).project).key)??(e.key?.split("-")[0]||"UNKNOWN")}function vg(e){let t=va(e),r=vs(t.displayName);if(!r)return null;let i=va(t.avatarUrls);return{accountId:vs(t.accountId),displayName:r,avatarUrl:vs(i["48x48"])??vs(i["32x32"])??vs(i["24x24"])}}function vy(e){return vn(e).map(va).map(e=>({id:vs(e.id),name:vs(e.name)??"Unknown"}))}function vw(e,t){let r=va(e),i=vs(r.key);if(!i)return null;let a=va(r.fields);return{relationship:t,key:i,summary:vs(a.summary)??i,status:vs(va(a.status).name)}}function vb(e){return{...e,kind:"BOARD"===e.kind?"BOARD":"JQL"}}function vE(e){return{source:e.source,stale:e.stale,fetchedAt:e.fetchedAt.toISOString()}}function vS(e){return 0===e.length?{source:"CACHE",stale:!1,fetchedAt:new Date(0).toISOString()}:{source:e.some(e=>"ERROR"===e.source)?"ERROR":e.some(e=>"LIVE"===e.source)?"LIVE":"CACHE",stale:e.some(e=>e.stale),fetchedAt:new Date(Math.max(...e.map(e=>e.fetchedAt.getTime()))).toISOString()}}function vv(e){let t=va(e.fields),r=va(t.status),i=va(r.statusCategory),a=va(t.assignee),n=va(a.avatarUrls),s=va(t.project),o=e.key??"UNKNOWN";return{id:e.id??o,key:o,summary:vs(t.summary)??o,statusId:vs(r.id)??vs(r.name)??"unknown",status:vs(r.name)??"Unknown",statusCategory:vs(i.key)??vs(i.name)??"unknown",issueType:vs(va(t.issuetype).name),priority:vs(va(t.priority).name),assignee:vs(a.displayName),assigneeAccountId:vs(a.accountId),assigneeAvatarUrl:vs(n["48x48"])??vs(n["32x32"]),projectKey:vs(s.key)??vf(e),updatedAt:vs(t.updated)}}function vI(e){let t=e.toLowerCase();return"new"===t||t.includes("to do")?0:"indeterminate"===t||t.includes("progress")?1:"done"===t?2:3}let vA=new Set(["ALL","UNASSIGNED_OR_SELF","SELF_IN_PROGRESS"]);function vk(e){return vA.has(e)?e:"ALL"}e.s(["JiraService",0,class{credentials;workflowEvents;recordCallLogs;inFlight;clients;lastPrunedAt;constructor(e=new gZ.CredentialService,t,r="true"!==process.env.JIRA_CACHE_LOGGING_DISABLED){this.credentials=e,this.workflowEvents=t,this.recordCallLogs=r,this.inFlight=new Map,this.lastPrunedAt=0}async storedConnection(){return(0,gX.readConnectionSettings)(this.credentials,gQ.CREDENTIALS.jiraConnectionSettings,gX.jiraConnectionSettings)}async recordTicketWorkflowEvents(e,t){if(!this.workflowEvents)return;let r=e.comments.at(-1)??null,i={ticket:{key:e.key,title:e.summary,type:e.issueType,status:e.status,statusId:e.statusId,statusCategory:e.statusCategory,assignee:e.assignee,assigneeAccountId:e.assigneeAccountId,labels:e.labels,sprintNames:e.sprintNames,activeSprintNames:e.activeSprintNames,closedSprintNames:e.closedSprintNames,url:e.jiraUrl},comment:r?{id:r.id,body:r.content?.rawText??"",author:r.author}:null,...void 0!==t?{changelog:t}:{}},a=e.cache.fetchedAt,n=e.assigneeAccountId?await this.currentAccountId().catch(()=>null):null,s=[["JIRA_STATUS",e.statusId],["JIRA_LABEL",JSON.stringify([...e.labels].sort())],["JIRA_MENTION",r?.id??"none"],["JIRA_SPRINT_STARTED",[...e.activeSprintNames].sort()],["JIRA_TICKET_UPDATED",e.updatedAt??"unknown"],["JIRA_COMMENT_ADDED",r?.id??"none"],["JIRA_SPRINT_ENDED",[...e.closedSprintNames].sort()]];if(n&&n===e.assigneeAccountId&&s.push(["JIRA_ASSIGNED_SELF",n]),t?.items.length){let e=new Set(t.items.flatMap(e=>[e.fieldId,e.field].filter(e=>!!e).map(e=>e.trim().toLowerCase()))),r=new Set(["JIRA_TICKET_UPDATED"]);e.has("status")&&r.add("JIRA_STATUS"),(e.has("label")||e.has("labels"))&&r.add("JIRA_LABEL"),e.has("assignee")&&r.add("JIRA_ASSIGNED_SELF"),e.has("sprint")&&(r.add("JIRA_SPRINT_STARTED"),r.add("JIRA_SPRINT_ENDED")),s=s.filter(([e])=>r.has(e))}await Promise.allSettled(s.map(([t,r])=>this.workflowEvents.record({kind:t,subjectKey:e.key,dedupeKey:`jira-trigger:${t}:${e.key}:${a}`,payload:{...i,sessionData:i,cursorValue:r}})))}async getSettings(){let e=await (0,gJ.getPrismaClient)(),[t,r,i]=await Promise.all([e.jiraSettings.upsert({where:{id:ve},create:{id:ve,cacheTtlSeconds:300},update:{}}),this.storedConnection(),this.credentials.isConfigured(gQ.CREDENTIALS.jiraApiToken)]);return{siteUrl:r?.value.siteUrl??null,email:r?.value.email??null,tokenConfigured:!!(r&&i),cacheTtlSeconds:t.cacheTtlSeconds,updatedAt:new Date(Math.max(t.updatedAt.getTime(),r?.updatedAt.getTime()??0)).toISOString()}}async saveSettings(e){let t=await (0,gJ.getPrismaClient)(),r=function(e){let t=new URL(e.trim());if("https:"!==t.protocol)throw Error("Jira Cloud site URL must use HTTPS");if(!t.hostname.toLowerCase().endsWith(".atlassian.net"))throw Error("Only Jira Cloud *.atlassian.net sites are supported");if(t.username||t.password||t.search||t.hash)throw Error("Jira site URL must not include credentials, query, or fragment");return t.origin}(e.siteUrl),i=e.email.trim();if(!/^\S+@\S+\.\S+$/.test(i))throw Error("A valid Jira email is required");let a=await this.storedConnection(),n=e.apiToken?.trim()||null,s=!!(a?.value.siteUrl&&a.value.siteUrl!==r);if(s&&!e.resetSite)throw Error("Changing the Jira site requires resetSite=true");let o=a?.value.siteUrl!==r||a?.value.email!==i||!!n,l={siteUrl:r,email:i},u=async e=>{s&&(await e.jiraProject.deleteMany(),await e.jiraWebhookDelivery.deleteMany()),o&&(await e.jiraCacheEntry.deleteMany(),await e.jiraCachedTicket.deleteMany()),await e.jiraSettings.upsert({where:{id:ve},create:{id:ve,cacheTtlSeconds:300},update:s?{webhookEnabled:!1,webhookConfiguredAt:null,webhookId:null}:{}})},c=[...a&&JSON.stringify(a.value)===JSON.stringify(l)?[]:[{descriptor:gQ.CREDENTIALS.jiraConnectionSettings,value:(0,gQ.encodeJsonCredential)(l)}],...n?[{descriptor:gQ.CREDENTIALS.jiraApiToken,value:Buffer.from(n,"utf8")}]:[]];return c.length?s?await this.credentials.setAndDeleteMany(c,[gQ.CREDENTIALS.jiraWebhookSecret,gQ.CREDENTIALS.jiraWebhookSettings],u):await this.credentials.setMany(c,u):await t.$transaction(u),this.clients=void 0,this.getSettings()}async clearCredentials(){let e=await (0,gJ.getPrismaClient)(),[t,r]=await Promise.all([e.jiraSettings.findUnique({where:{id:ve},select:{webhookId:!0}}),this.storedConnection()]),i=await this.credentials.isConfigured(gQ.CREDENTIALS.jiraApiToken);if(r?.value.siteUrl&&r.value.email&&t?.webhookId&&i)try{await this.webhookApiRequest("DELETE",`/rest/webhooks/1.0/webhook/${encodeURIComponent(t.webhookId)}`)}catch(e){if(404!==vp(e))throw e}return await this.credentials.deleteMany([gQ.CREDENTIALS.jiraConnectionSettings,gQ.CREDENTIALS.jiraApiToken,gQ.CREDENTIALS.jiraWebhookSettings,gQ.CREDENTIALS.jiraWebhookSecret],async e=>{await e.jiraCacheEntry.deleteMany(),await e.jiraCachedTicket.deleteMany(),await e.jiraWebhookDelivery.deleteMany(),await e.jiraSettings.upsert({where:{id:ve},create:{id:ve,cacheTtlSeconds:300},update:{webhookEnabled:!1,webhookConfiguredAt:null,webhookId:null}})}),this.clients=void 0,this.getSettings()}async updateCacheTtl(e){if(!Number.isInteger(e)||e<1||e>1440)throw Error("Cache TTL must be an integer from 1 to 1440 minutes");let t=await (0,gJ.getPrismaClient)();return await t.jiraSettings.upsert({where:{id:ve},create:{id:ve,cacheTtlSeconds:60*e},update:{cacheTtlSeconds:60*e}}),this.getSettings()}async testConnection(){let e=await this.cachedCall({operation:"MYSELF",params:{},requestSummary:"Current Jira user",force:!0,allowStaleOnError:!1,fetcher:async()=>{let{cloud:e}=await this.getClients();return e.myself.getCurrentUser()}});if(e.stale)throw Error("Jira connection test failed because the live request failed");let t=va(e.value);return{accountId:vs(t.accountId),displayName:vs(t.displayName)??"Jira user",emailAddress:vs(t.emailAddress),cache:vE(e)}}async listProjects(){let e=await (0,gJ.getPrismaClient)();return(await e.jiraProject.findMany({include:{sources:{orderBy:[{position:"asc"},{createdAt:"asc"}]}},orderBy:[{position:"asc"},{createdAt:"asc"}]})).map(e=>({id:e.id,jiraId:e.jiraId,key:e.key,name:e.name,avatarUrl:e.avatarUrl,position:e.position,ticketAssignmentFilter:vk(e.ticketAssignmentFilter),hideCompletedTickets:e.hideCompletedTickets,completedStatusIds:vd(e.completedStatusIdsJson),doneStatusId:e.doneStatusId,branchNamingScript:e.branchNamingScript??g3,sources:e.sources.map(vb)}))}async projectStatuses(e){let t=await (0,gJ.getPrismaClient)(),r=await t.jiraProject.findUnique({where:{id:e},select:{jiraId:!0,key:!0}});if(!r)throw Error("Jira project not found");let i=await this.cachedCall({operation:"PROJECT_STATUSES",params:{jiraId:r.jiraId},requestSummary:`Statuses for project ${r.key}`,fetcher:async()=>{let{cloud:e}=await this.getClients();return e.projects.getAllStatuses({projectIdOrKey:r.jiraId})}}),a=new Map;for(let e of vn(i.value).map(va))for(let t of vn(e.statuses).map(va)){let e=vs(t.id),r=vs(t.name);if(!e||!r||a.has(e))continue;let i=va(t.statusCategory);a.set(e,{id:e,name:r,category:vs(i.key)??vs(i.name)??"unknown"})}return[...a.values()].sort((e,t)=>vI(e.category)-vI(t.category)||e.name.localeCompare(t.name))}async updateProjectDisplaySettings(e){if(!vA.has(e.ticketAssignmentFilter))throw Error("Invalid Jira ticket assignment filter");let t=[...new Set(e.completedStatusIds.map(e=>e.trim()).filter(Boolean))].slice(0,200),r=await (0,gJ.getPrismaClient)(),i=void 0===e.doneStatusId?void 0:e.doneStatusId?.trim()||null;if(i&&!(await this.projectStatuses(e.projectId)).some(e=>e.id===i))throw Error("The selected Jira done status is not available");return await r.jiraProject.update({where:{id:e.projectId},data:{ticketAssignmentFilter:e.ticketAssignmentFilter,hideCompletedTickets:e.hideCompletedTickets,completedStatusIdsJson:JSON.stringify(t),...void 0===i?{}:{doneStatusId:i}}}),this.listProjects()}async updateProjectBranchNaming(e,t){let r=await (0,gJ.getPrismaClient)(),i=await r.jiraProject.findUnique({where:{id:e},select:{key:!0}});if(!i)throw Error("Jira project not found");let a=await g5(t,i.key);return await r.jiraProject.update({where:{id:e},data:{branchNamingScript:a}}),this.listProjects()}async availableProjects(){let e=[],t=0;for(;;){let r=await this.cachedCall({operation:"PROJECTS",params:{startAt:t,maxResults:100},requestSummary:`Visible projects from ${t}`,fetcher:async()=>{let{cloud:e}=await this.getClients();return e.projects.searchProjects({startAt:t,maxResults:100,orderBy:"name"})},itemCount:e=>vn(va(e).values).length}),i=va(r.value),a=vn(i.values).map(va);e.push(...a.flatMap(e=>{let t=vs(e.id),r=vs(e.key),i=vs(e.name);if(!t||!r||!i)return[];let a=va(e.avatarUrls);return[{jiraId:t,key:r,name:i,avatarUrl:vs(a["48x48"])??vs(a["32x32"])}]}));let n=vl(i.total)??e.length;if(0===a.length||e.length>=n)break;t+=a.length}return e}async addProject(e){let r=e.trim();if(!r)throw Error("Jira project ID is required");let i=va((await this.cachedCall({operation:"PROJECT",params:{jiraId:r},requestSummary:`Project ${r}`,fetcher:async()=>{let{cloud:e}=await this.getClients();return e.projects.getProject({projectIdOrKey:r})}})).value),a=vs(i.key),n=vs(i.name),s=vs(i.id);if(!a||!n||!s)throw Error("Jira returned an incomplete project");let o=va(i.avatarUrls),l=await (0,gJ.getPrismaClient)(),u=await l.jiraProject.aggregate({_max:{position:!0}});return await l.jiraProject.create({data:{id:(0,t.randomUUID)(),jiraId:s,key:a,name:n,avatarUrl:vs(o["48x48"])??vs(o["32x32"]),position:(u._max.position??-1)+1,branchNamingScript:g3}}),this.listProjects()}async removeProject(e){let t=await (0,gJ.getPrismaClient)(),r=(await t.jiraSource.findMany({where:{projectId:e},select:{id:!0}})).map(e=>e.id);return await t.$transaction(async t=>{r.length>0&&await t.jiraCacheEntry.deleteMany({where:{sourceId:{in:r}}}),await t.jiraProject.delete({where:{id:e}}),await t.jiraCachedTicket.deleteMany({where:{cacheEntries:{none:{}}}})}),this.listProjects()}async createSource(e){let r=await this.validateSource(e.kind,e.value),i=this.validateSourceName(e.name),a=await (0,gJ.getPrismaClient)();if(!await a.jiraProject.findUnique({where:{id:e.projectId}}))throw Error("Jira project not found");let n=await a.jiraSource.aggregate({where:{projectId:e.projectId},_max:{position:!0}});return await a.jiraSource.create({data:{id:(0,t.randomUUID)(),projectId:e.projectId,name:i,kind:e.kind,value:r.value,boardId:r.boardId,position:(n._max.position??-1)+1}}),this.listProjects()}async updateSource(e){let t=await this.validateSource(e.kind,e.value),r=this.validateSourceName(e.name),i=await (0,gJ.getPrismaClient)();return await i.$transaction([i.jiraCacheEntry.deleteMany({where:{sourceId:e.id}}),i.jiraSource.update({where:{id:e.id},data:{name:r,kind:e.kind,value:t.value,boardId:t.boardId}})]),this.listProjects()}async deleteSource(e){let t=await (0,gJ.getPrismaClient)();return await t.$transaction(async t=>{await t.jiraCacheEntry.deleteMany({where:{sourceId:e}}),await t.jiraSource.delete({where:{id:e}}),await t.jiraCachedTicket.deleteMany({where:{cacheEntries:{none:{}}}})}),this.listProjects()}async ticketBoard(e,t=!1){var r;let i,a,n,s=await (0,gJ.getPrismaClient)(),o=await s.jiraSource.findUnique({where:{id:e},include:{project:!0}});if(!o)throw Error("Jira source not found");let l=await s.jiraCacheEntry.findFirst({where:{sourceId:e,issues:{some:{}}},orderBy:{fetchedAt:"desc"},include:{issues:{select:{issueKey:!0}}}}),u=new Set(l?.issues.map(({issueKey:e})=>e)??[]),c="BOARD"===o.kind?await this.loadBoardSource(vb(o),t):await this.loadJqlSource(vb(o),t),d={ticketAssignmentFilter:vk(o.project.ticketAssignmentFilter),hideCompletedTickets:o.project.hideCompletedTickets,completedStatusIds:vd(o.project.completedStatusIdsJson)},h="ALL"===d.ticketAssignmentFilter?null:await this.currentAccountId(),p=(r={source:vb(o),...c},i=d.hideCompletedTickets?new Set(d.completedStatusIds):new Set,a=new Set(r.tickets.filter(e=>i.has(e.statusId)).map(e=>e.status)),n=r.tickets.filter(e=>{let t;return!i.has(e.statusId)&&("ALL"===d.ticketAssignmentFilter||("UNASSIGNED_OR_SELF"===d.ticketAssignmentFilter?null===e.assigneeAccountId||e.assigneeAccountId===h:null!==h&&e.assigneeAccountId===h&&("indeterminate"===(t=e.statusCategory.toLowerCase())||t.includes("progress"))))}),{...r,tickets:n,statusOrder:r.statusOrder.filter(e=>!a.has(e))});return this.workflowEvents&&l&&await Promise.allSettled(p.tickets.filter(({key:e})=>!u.has(e)).map(t=>{let r={ticket:{key:t.key,title:t.summary,type:t.issueType,status:t.status,statusId:t.statusId,statusCategory:t.statusCategory,assignee:t.assignee}};return this.workflowEvents.record({kind:"JIRA_SOURCE_NEW_TICKET",subjectKey:`${e}:${t.key}`,dedupeKey:`jira-source-new:${e}:${t.key}:${p.cache.fetchedAt}`,payload:{...r,sessionData:r,source:{id:e,name:o.name,kind:o.kind},cursorValue:t.key}})})),p}async ticket(e,t=!1,r){let i=vu(e),a=await this.cachedCall({operation:"ISSUE",params:{issueKey:i,fields:"*all",expand:"names,schema"},requestSummary:`Issue ${i} with all fields`,force:t,fetcher:async()=>{let{cloud:e}=await this.getClients();return e.issues.getIssue({issueIdOrKey:i,fields:["*all"],expand:["names","schema"],updateHistory:!1})}});"LIVE"===a.source&&await this.storeDetail(a.entryId,a.value,a.fetchedAt);let n=[],s=[],o=0;for(;;){let e=await this.cachedCall({operation:"COMMENTS",params:{issueKey:i,startAt:o,maxResults:100},requestSummary:`Comments for ${i} from ${o}`,force:t,fetcher:async()=>{let{cloud:e}=await this.getClients();return e.issueComments.getComments({issueIdOrKey:i,startAt:o,maxResults:100,orderBy:"created"})},itemCount:e=>vn(va(e).comments).length});n.push(e);let r=va(e.value),a=vn(r.comments);s.push(...a);let l=vl(r.total)??s.length;if(0===a.length||s.length>=l)break;o+=a.length}let l=new Date(Math.min(...n.map(e=>e.fetchedAt.getTime())));await this.storeComments(i,s,l,n.map(e=>e.entryId));let u=await this.requireCredentials(),c=this.normalizeTicketDetail(a.value,s,u.siteUrl,vE(a),vS(n));return await this.recordTicketWorkflowEvents(c,r),c}async assignableUsers(e,t=""){let r=vu(e),i=t.trim().slice(0,100),a=await this.cachedCall({operation:"ASSIGNABLE_USERS",params:{issueKey:r,query:i,maxResults:50},requestSummary:`Assignable users for ${r}`,fetcher:async()=>{let{cloud:e}=await this.getClients();return e.userSearch.findAssignableUsers({issueKey:r,query:i,maxResults:50,recommend:!0})},itemCount:e=>vn(e).length});return await this.linkCacheEntryToIssue(r,a.entryId),vn(a.value).map(vg).filter(e=>null!==e)}async ticketTransitions(e){let t=vu(e),r=await this.cachedCall({operation:"ISSUE_TRANSITIONS",params:{issueKey:t,expand:"transitions.fields"},requestSummary:`Available transitions for ${t}`,fetcher:async()=>{let{cloud:e}=await this.getClients();return e.issues.getTransitions({issueIdOrKey:t,expand:"transitions.fields"})},itemCount:e=>vn(va(e).transitions).length});return await this.linkCacheEntryToIssue(t,r.entryId),vn(va(r.value).transitions).map(va).filter(e=>!1!==e.isAvailable).flatMap(e=>{let t=vs(e.id),r=vs(e.name);if(!t||!r)return[];let i=va(e.to),a=va(i.statusCategory),n=Object.entries(va(e.fields)).filter(([,e])=>!0===va(e).required).map(([e,t])=>vs(va(t).name)??e);return[{id:t,name:r,toStatusId:vs(i.id),toStatus:vs(i.name)??r,toStatusCategory:vs(a.key)??vs(a.name),hasScreen:!0===e.hasScreen,requiredFields:n}]})}async ticketEditFields(e){let t=vu(e),r=await this.cachedCall({operation:"ISSUE_EDIT_META",params:{issueKey:t},requestSummary:`Editable fields for ${t}`,fetcher:async()=>{let{cloud:e}=await this.getClients();return e.issues.getEditIssueMeta({issueIdOrKey:t})},itemCount:e=>Object.keys(va(va(e).fields)).length});return await this.linkCacheEntryToIssue(t,r.entryId),Object.entries(va(va(r.value).fields)).map(([e,t])=>{let r=va(t);return{id:e,name:vs(r.name)??e,required:!0===r.required,schemaType:vs(va(r.schema).type),allowedValues:vn(r.allowedValues).flatMap(e=>{if("string"==typeof e)return[{id:e,name:e}];let t=va(e),r=vs(t.name)??vs(t.value)??vs(t.displayName)??vs(t.key);return r?[{id:vs(t.id)??vs(t.accountId)??vs(t.value)??r,name:r}]:[]})}}).sort((e,t)=>e.name.localeCompare(t.name))}async ticketChanges(e,r=50,i=0){let a=vu(e),n=this.validatePagination(r,i),s=await this.cachedCall({operation:"ISSUE_CHANGELOG",params:{issueKey:a,startAt:0,maxResults:1},requestSummary:`Changelog count for ${a}`,fetcher:async()=>{let{cloud:e}=await this.getClients();return e.issues.getChangeLogs({issueIdOrKey:a,startAt:0,maxResults:1})},itemCount:e=>vn(va(e).values).length});await this.linkCacheEntryToIssue(a,s.entryId);let o=vl(va(s.value).total)??0,l=Math.min(n.limit,Math.max(0,o-n.offset)),u=Math.max(0,o-n.offset-l);if(0===l)return{...n,total:o,items:[],cache:vE(s)};let c=await this.cachedCall({operation:"ISSUE_CHANGELOG",params:{issueKey:a,startAt:u,maxResults:l},requestSummary:`Changelog for ${a} from ${u}`,fetcher:async()=>{let{cloud:e}=await this.getClients();return e.issues.getChangeLogs({issueIdOrKey:a,startAt:u,maxResults:l})},itemCount:e=>vn(va(e).values).length});await this.linkCacheEntryToIssue(a,c.entryId);let d=vn(va(c.value).values).map(va).reverse().map(e=>({id:vs(e.id)??(0,t.randomUUID)(),author:vg(e.author),createdAt:vs(e.created),items:vn(e.items).map(va).map(e=>({field:vs(e.field)??"Field",fieldId:vs(e.fieldId),from:vs(e.fromString)??vs(e.from),to:vs(e.toString)??vs(e.to)}))}));return{...n,total:o,items:d,cache:vS([s,c])}}async ticketWorklogs(e,r=50,i=0){let a=vu(e),n=this.validatePagination(r,i),s=await this.cachedCall({operation:"ISSUE_WORKLOGS",params:{issueKey:a,startAt:0,maxResults:1},requestSummary:`Worklog count for ${a}`,fetcher:async()=>{let{cloud:e}=await this.getClients();return e.issueWorklogs.getIssueWorklog({issueIdOrKey:a,startAt:0,maxResults:1})},itemCount:e=>vn(va(e).worklogs).length});await this.linkCacheEntryToIssue(a,s.entryId);let o=vl(va(s.value).total)??0,l=Math.min(n.limit,Math.max(0,o-n.offset)),u=Math.max(0,o-n.offset-l);if(0===l)return{...n,total:o,items:[],cache:vE(s)};let c=await this.cachedCall({operation:"ISSUE_WORKLOGS",params:{issueKey:a,startAt:u,maxResults:l},requestSummary:`Worklogs for ${a} from ${u}`,fetcher:async()=>{let{cloud:e}=await this.getClients();return e.issueWorklogs.getIssueWorklog({issueIdOrKey:a,startAt:u,maxResults:l})},itemCount:e=>vn(va(e).worklogs).length});await this.linkCacheEntryToIssue(a,c.entryId);let d=await this.requireCredentials(),h=vn(va(c.value).worklogs).map(va).reverse().map(e=>({id:vs(e.id)??(0,t.randomUUID)(),author:vg(e.author),comment:S9(e.comment??null,d.siteUrl),timeSpent:vs(e.timeSpent),timeSpentSeconds:vl(e.timeSpentSeconds),startedAt:vs(e.started),createdAt:vs(e.created),updatedAt:vs(e.updated)})),p=h[0];if(this.workflowEvents&&p){let e={ticket:{key:a},worklog:{id:p.id,author:p.author,timeSpent:p.timeSpent,timeSpentSeconds:p.timeSpentSeconds,startedAt:p.startedAt,updatedAt:p.updatedAt}};await this.workflowEvents.record({kind:"JIRA_WORKLOG_ADDED",subjectKey:a,dedupeKey:`jira-worklog:${a}:${p.id}:${c.fetchedAt}`,payload:{...e,sessionData:e,cursorValue:p.id}})}return{...n,total:o,items:h,cache:vS([s,c])}}async addComment(e,t){let r=vu(e);if(!t.value.trim())throw Error("Comment text is required");let i=S7(t);return this.mutateTicket(r,"ADD_COMMENT",async()=>{let{cloud:e}=await this.getClients();await e.issueComments.addComment({issueIdOrKey:r,body:i})})}async assignTicket(e,t){let r=vu(e),i=t?.trim()||null;return this.mutateTicket(r,"ASSIGN_ISSUE",async()=>{let{cloud:e}=await this.getClients();await e.issues.assignIssue({issueIdOrKey:r,accountId:i})})}async transitionTicket(e,t){let r=vu(e),i=(await this.ticketTransitions(r)).find(e=>e.id===t);if(!i)throw Error("The Jira transition is not available");if(i.requiredFields.length>0)throw Error(`This transition requires fields that must be completed in Jira: ${i.requiredFields.join(", ")}`);return this.mutateTicket(r,"TRANSITION_ISSUE",async()=>{let{cloud:e}=await this.getClients();await e.issues.doTransition({issueIdOrKey:r,transition:{id:i.id}})})}async transitionTicketToConfiguredDone(e){let t=vu(e),r=t.split("-")[0]??"",i=await (0,gJ.getPrismaClient)(),a=await i.jiraProject.findUnique({where:{key:r},select:{doneStatusId:!0}});if(!a?.doneStatusId)throw Error(`Configure a done status for Jira project ${r} before using this option`);let n=await this.ticket(t);if(n.statusId===a.doneStatusId)return n;let s=(await this.ticketTransitions(t)).filter(e=>e.toStatusId===a.doneStatusId).sort((e,t)=>e.requiredFields.length-t.requiredFields.length)[0];if(!s)throw Error("Jira does not currently offer a transition to the configured done status");return this.transitionTicket(t,s.id)}async updateTicket(e){let t=vu(e.issueKey),r=new Map((await this.ticketEditFields(t)).map(e=>[e.id,e])),i={},a=e=>{let t=r.get(e);if(!t)throw Error(`${e} is not editable on this ticket`);return t},n=t=>Object.prototype.hasOwnProperty.call(e,t);if(n("summary")){a("summary");let t=e.summary?.trim();if(!t)throw Error("Ticket summary is required");i.summary=t}if(n("description")){let t=a("description");if(null===e.description){if(t.required)throw Error("Description is required");i.description=null}else e.description&&(i.description=S7(e.description))}if(n("priorityId")){let t=a("priority"),r=e.priorityId?.trim()||null;if(!r&&t.required)throw Error("Priority is required");if(r&&t.allowedValues.length>0&&!t.allowedValues.some(e=>e.id===r))throw Error("The selected priority is not available");i.priority=r?{id:r}:null}n("labels")&&(a("labels"),i.labels=[...new Set((e.labels??[]).map(e=>e.trim()).filter(Boolean))]);let s=(t,r)=>{if(!n(t))return;let s=a(r),o=[...new Set(e[t]??[])];if(s.allowedValues.length>0&&o.some(e=>!s.allowedValues.some(t=>t.id===e)))throw Error(`A selected ${s.name} value is not available`);i[r]=o.map(e=>({id:e}))};if(s("componentIds","components"),s("fixVersionIds","fixVersions"),s("affectedVersionIds","versions"),n("dueDate")){let t=a("duedate"),r=e.dueDate?.trim()||null;if(r&&!/^\d{4}-\d{2}-\d{2}$/.test(r))throw Error("Due date must use YYYY-MM-DD");if(!r&&t.required)throw Error("Due date is required");i.duedate=r}if(0===Object.keys(i).length)throw Error("At least one editable Jira field is required");return this.mutateTicket(t,"EDIT_ISSUE",async()=>{let{cloud:e}=await this.getClients();await e.issues.editIssue({issueIdOrKey:t,fields:i})})}async createTicket(e){let t=e.projectKey.trim().toUpperCase(),r=e.issueTypeId.trim(),i=e.summary.trim();if(!t||!r||!i)throw Error("Project, issue type, and summary are required");let{cloud:a}=await this.getClients(),n=await a.issues.createIssue({fields:{...e.fields??{},project:{key:t},issuetype:{id:r},summary:i,...e.description?{description:S7(e.description)}:{}}});if(!n.key)throw Error("Jira did not return the created issue key");return this.ticket(n.key,!0)}async addWorklog(e){let t=vu(e.issueKey);if(!Number.isInteger(e.timeSpentSeconds)||e.timeSpentSeconds<1)throw Error("Time spent must be a positive number of seconds");let{cloud:r}=await this.getClients();return await r.issueWorklogs.addWorklog({issueIdOrKey:t,timeSpentSeconds:e.timeSpentSeconds,started:e.startedAt??new Date().toISOString(),...e.comment?{comment:S7(e.comment)}:{}}),this.ticket(t,!0)}async linkTickets(e){let t=vu(e.inwardIssueKey),r=vu(e.outwardIssueKey),i=e.linkType.trim();if(!i)throw Error("Jira issue link type is required");let{cloud:a}=await this.getClients();return await a.issueLinks.linkIssues({type:{name:i},inwardIssue:{key:t},outwardIssue:{key:r}}),this.ticket(t,!0)}async branchTicket(e){let t=vu(e),r=t.replace(/-\d+$/,""),i=await (0,gJ.getPrismaClient)(),a=await i.jiraProject.findUnique({where:{key:r},select:{key:!0,branchNamingScript:!0}});if(!a)throw Error(`Jira project ${r} is not managed; add it in Manage Jira projects and sources`);let n=await this.cachedCall({operation:"ISSUE_BRANCH",params:{issueKey:t,fields:["summary","issuetype","project"]},requestSummary:`Branch details for ${t}`,fetcher:async()=>{let{cloud:e}=await this.getClients();return e.issues.getIssue({issueIdOrKey:t,fields:["summary","issuetype","project"],updateHistory:!1})}});await this.linkCacheEntryToIssue(t,n.entryId);let s=va(n.value.fields);if((vs(va(s.project).key)??vf(n.value))!==a.key)throw Error(`Jira ticket ${t} does not belong to project ${a.key}`);return{ticketKey:n.value.key??t,ticketTitle:vs(s.summary)??t,ticketType:vs(va(s.issuetype).name),projectKey:a.key,branchNamingScript:a.branchNamingScript??g3}}async clearCache(){let e=await (0,gJ.getPrismaClient)();return await e.$transaction([e.jiraCacheEntry.deleteMany(),e.jiraCachedTicket.deleteMany()]),!0}async clearApiCalls(){let e=await (0,gJ.getPrismaClient)();return await e.jiraApiCallLog.deleteMany(),!0}async deleteCachedTicket(e){return await this.invalidateIssueCaches(vu(e)),!0}async invalidateIssueCaches(e){let t=await (0,gJ.getPrismaClient)(),r=await t.jiraCacheEntryIssue.findMany({where:{issueKey:e},select:{cacheEntryId:!0}});await t.$transaction(async t=>{r.length>0&&await t.jiraCacheEntry.deleteMany({where:{id:{in:r.map(e=>e.cacheEntryId)}}}),await t.jiraCachedTicket.deleteMany({where:{issueKey:e}})})}async refreshCachedTicket(e,t){let r=await (0,gJ.getPrismaClient)(),i=await r.jiraCacheEntryIssue.findMany({where:{issueKey:e},select:{cacheEntryId:!0}});return i.length>0&&await r.jiraCacheEntry.deleteMany({where:{id:{in:i.map(e=>e.cacheEntryId)}}}),this.ticket(e,!0,t)}async resolveIssueKeys(e){let t=[...new Set(e.map(e=>e.trim()).filter(Boolean))];if(0===t.length)return[];let{cloud:r}=await this.getClients();return[...new Set((await Promise.all(t.map(e=>r.issues.getIssue({issueIdOrKey:e,fields:["key"]})))).map(e=>{let t=vs(e.key);if(!t)throw Error(`Jira issue ${e.id??""} has no key`);return vu(t)}))]}async refreshSprintTickets(e){let t;if(!Number.isSafeInteger(e)||e<=0)throw Error("Invalid Jira sprint ID");let{agile:r}=await this.getClients(),i=[];for(;i.length<1e3;){let a=Math.min(100,1e3-i.length),n=await r.sprint.getIssuesForSprint({sprintId:e,nextPageToken:t,maxResults:a,fields:["key"]}),s=n.issues??[];i.push(...s.flatMap(e=>{let t=vs(e.key);return t?[vu(t)]:[]}));let o=vs(n.nextPageToken)??void 0;if(0===s.length||n.isLast||!o)break;if(o===t)throw Error("Jira returned a repeated sprint pagination token");t=o}let a=[],n=[...new Set(i)];for(let e=0;e<n.length;e+=5)a.push(...await Promise.all(n.slice(e,e+5).map(e=>this.refreshCachedTicket(e))));return a}async listCachedTickets(e=50,t=0){let r=this.validatePagination(e,t),i=await (0,gJ.getPrismaClient)(),[a,n,s]=await Promise.all([i.jiraCachedTicket.findMany({take:r.limit,skip:r.offset,orderBy:{updatedAt:"desc"}}),i.jiraCachedTicket.count(),this.getSettings()]);return{...r,total:n,items:a.map(e=>this.cachedTicketView(e,s.cacheTtlSeconds))}}async cachedTicket(e){let t=await (0,gJ.getPrismaClient)(),[r,i]=await Promise.all([t.jiraCachedTicket.findUnique({where:{issueKey:e},include:{cacheEntries:{include:{cacheEntry:!0}}}}),this.getSettings()]);return r?{...this.cachedTicketView(r,i.cacheTtlSeconds),summaryData:vc(r.summaryJson),detailData:vc(r.detailJson),commentsData:vc(r.commentsJson),cacheEntries:r.cacheEntries.map(e=>({id:e.cacheEntry.id,operation:e.cacheEntry.operation,fetchedAt:e.cacheEntry.fetchedAt.toISOString()})).sort((e,t)=>t.fetchedAt.localeCompare(e.fetchedAt))}:null}async listApiCalls(e=50,t=0){let r=this.validatePagination(e,t);await this.pruneLogs();let i=await (0,gJ.getPrismaClient)(),[a,n]=await Promise.all([i.jiraApiCallLog.findMany({take:r.limit,skip:r.offset,orderBy:{createdAt:"desc"}}),i.jiraApiCallLog.count()]);return{...r,total:n,items:a.map(e=>({id:e.id,operation:e.operation,requestSummary:e.requestSummary,source:e.source,durationMs:e.durationMs,statusCode:e.statusCode,error:e.error,itemCount:e.itemCount,servedStale:e.servedStale,createdAt:e.createdAt.toISOString()}))}}async cacheMetrics(){await this.pruneLogs();let e=await (0,gJ.getPrismaClient)(),t=Date.now(),r=await e.jiraApiCallLog.findMany({where:{createdAt:{gte:new Date(t-vr.at(-1).milliseconds)}},orderBy:{createdAt:"asc"}});return{windows:vr.map(e=>this.metricWindow(e.window,r.filter(r=>r.createdAt.getTime()>=t-e.milliseconds))),operations:[...new Set(r.map(e=>e.operation))].sort().map(e=>({operation:e,windows:vr.map(i=>this.metricWindow(i.window,r.filter(r=>r.operation===e&&r.createdAt.getTime()>=t-i.milliseconds)))}))}}async requireCredentials(){let e=await (0,gJ.getPrismaClient)(),[t,r]=await Promise.all([e.jiraSettings.findUnique({where:{id:ve}}),this.storedConnection()]);if(!r)throw Error("Configure the Jira site, email, and API token in Settings first");let i=await this.credentials.getText(gQ.CREDENTIALS.jiraApiToken);if(!i)throw Error("Configure the Jira site, email, and API token in Settings first");return{siteUrl:r.value.siteUrl,email:r.value.email,apiToken:i,cacheTtlSeconds:t?.cacheTtlSeconds??300}}async getClients(){let e,r,i=await this.requireCredentials(),a=(0,t.createHash)("sha256").update(`${i.siteUrl}\0${i.email}\0${i.apiToken}`).digest("hex");if(this.clients?.key===a)return this.clients;let n=K({host:i.siteUrl,auth:{type:"basic",email:i.email,apiToken:i.apiToken}});return this.clients={key:a,cloud:(e=K(n),{announcementBanner:{getBanner:()=>rL(e),setBanner:t=>rU(e,t)},issueCustomFieldValuesApps:{updateMultipleCustomFieldValues:t=>rB(e,t),updateCustomFieldValue:t=>rM(e,t)},issueCustomFieldConfigurationApps:{getCustomFieldConfiguration:t=>r$(e,t),updateCustomFieldConfiguration:t=>rG(e,t)},jiraSettings:{getApplicationProperty:t=>rV(e,t),getAdvancedSettings:()=>rK(e),setApplicationProperty:t=>rW(e,t),getConfiguration:()=>rJ(e)},applicationRoles:{getAllApplicationRoles:()=>rZ(e),getApplicationRole:t=>rX(e,t)},issueAttachments:{getAttachmentContent:t=>il(e,t),getAttachmentMeta:()=>iu(e),getAttachmentThumbnail:t=>ic(e,t),getAttachment:t=>id(e,t),removeAttachment:t=>ih(e,t),addAttachment:t=>ip(e,t)},auditRecords:{getAuditRecords:t=>ib(e,t)},avatars:{getAllSystemAvatars:t=>iI(e,t),getAvatars:t=>iA(e,t),storeAvatar:t=>ik(e,t),deleteAvatar:t=>i_(e,t),getAvatarImageByType:t=>iT(e,t),getAvatarImageByID:t=>iC(e,t),getAvatarImageByOwner:t=>iR(e,t)},issueBulkOperations:{submitBulkDelete:t=>iq(e,t),getBulkEditableFields:t=>ij(e,t),submitBulkEdit:t=>i$(e,t),submitBulkMove:t=>iG(e,t),getAvailableTransitions:t=>iF(e,t),submitBulkTransition:t=>iz(e,t),submitBulkUnwatch:t=>iH(e,t),submitBulkWatch:t=>iV(e,t),getBulkOperationProgress:t=>iK(e,t)},issues:{getBulkChangelogs:t=>aw(e,t),createIssue:t=>ab(e,t),createIssues:t=>aE(e,t),bulkFetchIssues:t=>aS(e,t),getCreateIssueMetaIssueTypes:t=>av(e,t),getCreateIssueMetaIssueTypeId:t=>aI(e,t),getIssue:t=>aA(e,t),editIssue:t=>ak(e,t),deleteIssue:t=>a_(e,t),assignIssue:t=>aT(e,t),getChangeLogs:t=>aC(e,t),getChangeLogsByIds:t=>aR(e,t),getEditIssueMeta:t=>aN(e,t),notify:t=>aO(e,t),getTransitions:t=>aD(e,t),doTransition:t=>aP(e,t)},issueComments:{getCommentsByIds:t=>aj(e,t),getComments:t=>a$(e,t),addComment:t=>aG(e,t),getComment:t=>aF(e,t),updateComment:t=>az(e,t),deleteComment:t=>aH(e,t)},issueCommentProperties:{getCommentPropertyKeys:t=>aW(e,t),getCommentProperty:t=>aJ(e,t),setCommentProperty:t=>aY(e,t),deleteCommentProperty:t=>aQ(e,t)},projectComponents:{findComponentsForProjects:t=>a2(e,t),createComponent:t=>a3(e,t),getComponent:t=>a4(e,t),updateComponent:t=>a5(e,t),deleteComponent:t=>a6(e,t),getComponentRelatedIssues:t=>a8(e,t),getProjectComponentsPaginated:t=>a9(e,t),getProjectComponents:t=>a7(e,t)},timeTracking:{getSelectedTimeTrackingImplementation:()=>nt(e),selectTimeTrackingImplementation:t=>nr(e,t),getAvailableTimeTrackingImplementations:()=>ni(e),getSharedTimeTrackingConfiguration:()=>na(e),setSharedTimeTrackingConfiguration:t=>nn(e,t)},issueCustomFieldOptions:{getCustomFieldOption:t=>nf(e,t),getOptionsForContext:t=>ng(e,t),createCustomFieldOption:t=>ny(e,t),updateCustomFieldOption:t=>nw(e,t),reorderCustomFieldOptions:t=>nb(e,t),deleteCustomFieldOption:t=>nE(e,t),replaceCustomFieldOption:t=>nS(e,t)},dashboards:{getAllDashboards:t=>nF(e,t),getDashboardsPaginated:t=>nz(e,t),getDashboardItemPropertyKeys:t=>nH(e,t),getDashboardItemProperty:t=>nV(e,t),setDashboardItemProperty:t=>nK(e,t),deleteDashboardItemProperty:t=>nW(e,t),getDashboard:t=>nJ(e,t)},appDataPolicies:{getPolicy:()=>n0(e),getPolicies:t=>n1(e,t)},jiraExpressions:{analyseExpression:t=>sr(e,t),evaluateJSISJiraExpression:t=>si(e,t)},issueFields:{getFields:()=>sl(e),createCustomField:t=>su(e,t),getFieldsPaginated:t=>sc(e,t),getTrashedFieldsPaginated:t=>sd(e,t),updateCustomField:t=>sh(e,t),deleteCustomField:t=>sp(e,t),restoreCustomField:t=>sm(e,t),trashCustomField:t=>sf(e,t)},issueCustomFieldAssociations:{createAssociations:t=>sg(e,t),removeAssociations:t=>sy(e,t)},issueCustomFieldContexts:{getContextsForField:t=>s0(e,t),createCustomFieldContext:t=>s1(e,t),getContextDefaultValues:t=>s2(e,t),getIssueTypeMappingsForContexts:t=>s3(e,t),getCustomFieldContextsForProjectsAndIssueTypes:t=>s4(e,t),getProjectContextMapping:t=>s5(e,t),updateCustomFieldContext:t=>s6(e,t),deleteCustomFieldContext:t=>s8(e,t),addIssueTypesToContext:t=>s9(e,t),removeIssueTypesFromContext:t=>s7(e,t),assignProjectsToCustomFieldContext:t=>oe(e,t),removeCustomFieldContextFromProjects:t=>ot(e,t)},screens:{getScreensForField:t=>os(e,t),getScreens:t=>oo(e,t),addFieldToDefaultScreen:t=>ol(e,t),getAvailableScreenFields:t=>ou(e,t)},issueCustomFieldOptionsApps:{getAllIssueFieldOptions:t=>og(e,t),createIssueFieldOption:t=>oy(e,t),getSelectableIssueFieldOptions:t=>ow(e,t),getVisibleIssueFieldOptions:t=>ob(e,t),getIssueFieldOption:t=>oE(e,t),updateIssueFieldOption:t=>oS(e,t),deleteIssueFieldOption:t=>ov(e,t),replaceIssueFieldOption:t=>oI(e,t)},filters:{createFilter:t=>oN(e,t),getFavouriteFilters:t=>oO(e,t),getMyFilters:t=>oD(e,t),getFiltersPaginated:t=>oP(e,t),getFilter:t=>ox(e,t),updateFilter:t=>oL(e,t),deleteFilter:t=>oU(e,t),getColumns:t=>oB(e,t),setColumns:t=>oM(e,t),resetColumns:t=>oq(e,t),setFavouriteForFilter:t=>oj(e,t),deleteFavouriteForFilter:t=>o$(e,t)},filterSharing:{getDefaultShareScope:()=>oF(e),setDefaultShareScope:t=>oz(e,t),getSharePermissions:t=>oH(e,t),addSharePermission:t=>oV(e,t),getSharePermission:t=>oK(e,t),deleteSharePermission:t=>oW(e,t)},issuePanels:{bulkPinUnpinProjectsAsync:t=>oY(e,t)},groups:{createGroup:t=>o3(e,t),removeGroup:t=>o4(e,t),getUsersFromGroup:t=>o5(e,t),addUserToGroup:t=>o6(e,t),removeUserFromGroup:t=>o8(e,t),findGroups:t=>o9(e,t)},groupAndUserPicker:{findUsersAndGroups:t=>lr(e,t)},issueSearch:{getIssuePickerResource:t=>lh(e,t),matchIssues:t=>lp(e,t),countIssues:t=>lm(e,t),searchAndReconsileIssuesUsingJql:t=>lf(e,t),searchAndReconsileIssuesUsingJqlPost:t=>lg(e,t)},issueProperties:{bulkSetIssuesPropertiesList:t=>ly(e,t),bulkSetIssuePropertiesByIssue:t=>lw(e,t),bulkSetIssueProperty:t=>lb(e,t),bulkDeleteIssueProperty:t=>lE(e,t),getIssuePropertyKeys:t=>lS(e,t),getIssueProperty:t=>lv(e,t),setIssueProperty:t=>lI(e,t),deleteIssueProperty:t=>lA(e,t)},issueWatchers:{getIsWatchingIssueBulk:t=>lT(e,t),getIssueWatchers:t=>lC(e,t),addWatcher:t=>lR(e,t),removeWatcher:t=>lN(e,t)},issueRemoteLinks:{getRemoteIssueLinks:t=>lM(e,t),createOrUpdateRemoteIssueLink:t=>lq(e,t),deleteRemoteIssueLinkByGlobalId:t=>lj(e,t),getRemoteIssueLinkById:t=>l$(e,t),updateRemoteIssueLink:t=>lG(e,t),deleteRemoteIssueLinkById:t=>lF(e,t)},issueVotes:{getVotes:t=>lH(e,t),addVote:t=>lV(e,t),removeVote:t=>lK(e,t)},issueWorklogs:{getIssueWorklog:t=>lZ(e,t),addWorklog:t=>lX(e,t),getWorklog:t=>l0(e,t),updateWorklog:t=>l1(e,t),deleteWorklog:t=>l2(e,t),getIdsOfWorklogsDeletedSince:t=>l3(e,t),getWorklogsForIds:t=>l4(e,t),getIdsOfWorklogsModifiedSince:t=>l5(e,t)},issueWorklogProperties:{getWorklogPropertyKeys:t=>l6(e,t),getWorklogProperty:t=>l8(e,t),setWorklogProperty:t=>l9(e,t),deleteWorklogProperty:t=>l7(e,t)},issueLinks:{linkIssues:t=>uo(e,t),getIssueLink:t=>ul(e,t),deleteIssueLink:t=>uu(e,t)},issueLinkTypes:{getIssueLinkTypes:()=>ud(e),createIssueLinkType:t=>uh(e,t),getIssueLinkType:t=>up(e,t),updateIssueLinkType:t=>um(e,t),deleteIssueLinkType:t=>uf(e,t)},issueSecuritySchemes:{getIssueSecuritySchemes:()=>ub(e),getIssueSecurityScheme:t=>uE(e,t)},issueSecurityLevel:{getIssueSecurityLevelMembers:t=>uI(e,t),getIssueSecurityLevel:t=>uA(e,t)},issueTypes:{getIssueAllTypes:()=>uk(e),createIssueType:t=>u_(e,t),getIssueType:t=>uT(e,t),updateIssueType:t=>uC(e,t),deleteIssueType:t=>uR(e,t),getAlternativeIssueTypes:t=>uN(e,t),createIssueTypeAvatar:t=>uO(e,t)},issueTypeProperties:{getIssueTypePropertyKeys:t=>uD(e,t),getIssueTypeProperty:t=>uP(e,t),setIssueTypeProperty:t=>ux(e,t),deleteIssueTypeProperty:t=>uL(e,t)},issueTypeSchemes:{getAllIssueTypeSchemes:t=>u$(e,t),createIssueTypeScheme:t=>uG(e,t),getIssueTypeSchemesMapping:t=>uF(e,t),getIssueTypeSchemeForProjects:t=>uz(e,t),assignIssueTypeSchemeToProject:t=>uH(e,t),updateIssueTypeScheme:t=>uV(e,t),deleteIssueTypeScheme:t=>uK(e,t),addIssueTypesToIssueTypeScheme:t=>uW(e,t),reorderIssueTypesInIssueTypeScheme:t=>uJ(e,t),removeIssueTypeFromIssueTypeScheme:t=>uY(e,t)},issueTypeScreenSchemes:{getIssueTypeScreenSchemes:t=>u3(e,t),createIssueTypeScreenScheme:t=>u4(e,t),getIssueTypeScreenSchemeMappings:t=>u5(e,t),getIssueTypeScreenSchemeProjectAssociations:t=>u6(e,t),assignIssueTypeScreenSchemeToProject:t=>u8(e,t),updateIssueTypeScreenScheme:t=>u9(e,t),deleteIssueTypeScreenScheme:t=>u7(e,t),appendMappingsForIssueTypeScreenScheme:t=>ce(e,t),updateDefaultScreenScheme:t=>ct(e,t),removeMappingsFromIssueTypeScreenScheme:t=>cr(e,t),getProjectsForIssueTypeScreenScheme:t=>ci(e,t)},jql:{getAutoComplete:()=>cN(e),getAutoCompletePost:t=>cO(e,t),getFieldAutoCompleteForQueryString:t=>cD(e,t),parseJqlQueries:t=>cP(e,t),migrateQueries:t=>cx(e,t)},jqlFunctionsApps:{getPrecomputations:t=>cM(e,t),updatePrecomputations:t=>cq(e,t),getPrecomputationsByID:t=>cj(e,t)},labels:{getAllLabels:t=>cG(e,t)},permissions:{getMyPermissions:t=>cW(e,t),getAllPermissions:()=>cJ(e),getBulkPermissions:t=>cY(e,t),getPermittedProjects:t=>cQ(e,t)},myself:{getPreference:t=>cX(e,t),setPreference:t=>c0(e,t),removePreference:t=>c1(e,t),getLocale:()=>c2(e),getCurrentUser:t=>c3(e,t)},issueNotificationSchemes:{getNotificationSchemes:t=>de(e,t),getNotificationSchemeToProjectMappings:t=>dt(e,t),getNotificationScheme:t=>dr(e,t),addNotifications:t=>di(e,t),removeNotificationFromNotificationScheme:t=>da(e,t)},permissionSchemes:{getAllPermissionSchemes:t=>dc(e,t),createPermissionScheme:t=>dd(e,t),getPermissionScheme:t=>dh(e,t),updatePermissionScheme:t=>dp(e,t),deletePermissionScheme:t=>dm(e,t),getPermissionSchemeGrants:t=>df(e,t),createPermissionGrant:t=>dg(e,t),getPermissionSchemeGrant:t=>dy(e,t),deletePermissionSchemeEntity:t=>dw(e,t)},issuePriorities:{createPriority:t=>dS(e,t),setDefaultPriority:t=>dv(e,t),movePriorities:t=>dI(e,t),searchPriorities:t=>dA(e,t),getPriority:t=>dk(e,t),updatePriority:t=>d_(e,t),deletePriority:t=>dT(e,t)},projects:{createProject:t=>dx(e,t),searchProjects:t=>dL(e,t),getProject:t=>dU(e,t),updateProject:t=>dB(e,t),deleteProject:t=>dM(e,t),archiveProject:t=>dq(e,t),getAllStatuses:t=>dj(e,t),getHierarchy:t=>d$(e,t),getNotificationSchemeForProject:t=>dG(e,t)},projectTemplates:{createProjectWithCustomTemplate:t=>dF(e,t)},projectTypes:{getAllProjectTypes:()=>dH(e),getAllAccessibleProjectTypes:()=>dV(e),getProjectTypeByKey:t=>dK(e,t),getAccessibleProjectTypeByKey:t=>dW(e,t)},projectAvatars:{updateProjectAvatar:t=>dY(e,t),deleteProjectAvatar:t=>dQ(e,t),createProjectAvatar:t=>dZ(e,t),getAllProjectAvatars:t=>dX(e,t)},projectFeatures:{getFeaturesForProject:t=>d2(e,t),toggleFeatureForProject:t=>d3(e,t)},projectProperties:{getProjectPropertyKeys:t=>d4(e,t),getProjectProperty:t=>d5(e,t),setProjectProperty:t=>d6(e,t),deleteProjectProperty:t=>d8(e,t)},projectRoles:{getProjectRoles:t=>he(e,t),getProjectRole:t=>ht(e,t),getProjectRoleDetails:t=>hr(e,t),getAllProjectRoles:()=>hi(e),createProjectRole:t=>ha(e,t),getProjectRoleById:t=>hn(e,t),partialUpdateProjectRole:t=>hs(e,t),fullyUpdateProjectRole:t=>ho(e,t),deleteProjectRole:t=>hl(e,t)},projectRoleActors:{addActorUsers:t=>hu(e,t),setActors:t=>hc(e,t),deleteActor:t=>hd(e,t),getProjectRoleActorsForRole:t=>hh(e,t),addProjectRoleActorsToRole:t=>hp(e,t),deleteProjectRoleActorsFromRole:t=>hm(e,t)},projectVersions:{getProjectVersionsPaginated:t=>hE(e,t),getProjectVersions:t=>hS(e,t),createVersion:t=>hv(e,t),getVersion:t=>hI(e,t),updateVersion:t=>hA(e,t),mergeVersions:t=>hk(e,t),moveVersion:t=>h_(e,t),getVersionRelatedIssues:t=>hT(e,t),getRelatedWork:t=>hC(e,t),createRelatedWork:t=>hR(e,t),updateRelatedWork:t=>hN(e,t),deleteAndReplaceVersion:t=>hO(e,t),getVersionUnresolvedIssues:t=>hD(e,t),deleteRelatedWork:t=>hP(e,t)},projectEmail:{getProjectEmail:t=>hL(e,t),updateProjectEmail:t=>hU(e,t)},projectPermissionSchemes:{getProjectIssueSecurityScheme:t=>hM(e,t),getAssignedPermissionScheme:t=>hq(e,t),assignPermissionScheme:t=>hj(e,t),getSecurityLevelsForProject:t=>h$(e,t)},projectCategories:{getAllProjectCategories:()=>hG(e),createProjectCategory:t=>hF(e,t),getProjectCategoryById:t=>hz(e,t),updateProjectCategory:t=>hH(e,t),removeProjectCategory:t=>hV(e,t)},projectKeyAndNameValidation:{validateProjectKey:t=>hK(e,t),getValidProjectKey:t=>hW(e,t),getValidProjectName:t=>hJ(e,t)},issueRedaction:{redact:t=>hX(e,t),getRedactionStatus:t=>h0(e,t)},issueResolutions:{getResolution:t=>h2(e,t)},screenTabs:{getAllScreenTabs:t=>h3(e,t),addScreenTab:t=>h4(e,t),renameScreenTab:t=>h5(e,t),deleteScreenTab:t=>h6(e,t),moveScreenTab:t=>h8(e,t)},screenTabFields:{getAllScreenTabFields:t=>h9(e,t),addScreenTabField:t=>h7(e,t),removeScreenTabField:t=>pe(e,t),moveScreenTabField:t=>pt(e,t)},screenSchemes:{getScreenSchemes:t=>pn(e,t),createScreenScheme:t=>ps(e,t),updateScreenScheme:t=>po(e,t),deleteScreenScheme:t=>pl(e,t)},serverInfo:{getServerInfo:()=>pd(e)},issueNavigatorSettings:{getIssueNavigatorDefaultColumns:()=>ph(e),setIssueNavigatorDefaultColumns:t=>pp(e,t)},workflowStatuses:{getStatuses:()=>pm(e),getStatus:t=>pf(e,t)},workflowStatusCategories:{getStatusCategories:()=>pg(e),getStatusCategory:t=>py(e,t)},status:{getStatusesById:t=>pO(e,t),createStatuses:t=>pD(e,t),updateStatuses:t=>pP(e,t),deleteStatusesById:t=>px(e,t),getStatusesByName:t=>pL(e,t),search:t=>pU(e,t),getProjectIssueTypeUsagesForStatus:t=>pB(e,t),getProjectUsagesForStatus:t=>pM(e,t),getWorkflowUsagesForStatus:t=>pq(e,t)},tasks:{getTask:t=>pj(e,t)},uiModificationsApps:{getUiModifications:t=>pz(e,t),createUiModification:t=>pH(e,t),updateUiModification:t=>pV(e,t),deleteUiModification:t=>pK(e,t)},users:{getUser:t=>pJ(e,t),createUser:t=>pY(e,t),removeUser:t=>pQ(e,t),getUserDefaultColumns:t=>pZ(e,t),setUserColumns:t=>pX(e,t),resetUserColumns:t=>p0(e,t),getUserEmail:t=>p1(e,t),getUserEmailBulk:t=>p2(e,t),getUserGroups:t=>p3(e,t),getAllUsersDefault:t=>p4(e,t),getAllUsers:t=>p5(e,t)},userSearch:{findBulkAssignableUsers:t=>p9(e,t),findAssignableUsers:t=>p7(e,t),findUsersWithAllPermissions:t=>me(e,t),findUsersForPicker:t=>mt(e,t),findUsers:t=>mr(e,t),findUsersByQuery:t=>mi(e,t),findUserKeysByQuery:t=>ma(e,t),findUsersWithBrowsePermission:t=>mn(e,t)},userProperties:{getUserPropertyKeys:t=>ms(e,t),getUserProperty:t=>mo(e,t),setUserProperty:t=>ml(e,t),deleteUserProperty:t=>mu(e,t)},webhooks:{getDynamicWebhooksForApp:t=>mm(e,t),registerDynamicWebhooks:t=>mf(e,t),deleteWebhookById:t=>mg(e,t),refreshWebhooks:t=>my(e,t)},workflows:{readWorkflowFromHistory:t=>fd(e,t),listWorkflowHistory:t=>fh(e,t),deleteInactiveWorkflow:t=>fp(e,t),getWorkflowProjectIssueTypeUsages:t=>fm(e,t),getProjectUsagesForWorkflow:t=>ff(e,t),getWorkflowSchemeUsagesForWorkflow:t=>fg(e,t),readWorkflows:t=>fy(e,t),workflowCapabilities:t=>fw(e,t),createWorkflows:t=>fb(e,t),validateCreateWorkflows:t=>fE(e,t),getDefaultEditor:()=>fS(e),readWorkflowPreviews:t=>fv(e,t),searchWorkflows:t=>fI(e,t),updateWorkflows:t=>fA(e,t),validateUpdateWorkflows:t=>fk(e,t)},workflowTransitionRules:{getWorkflowTransitionRuleConfigurations:t=>fx(e,t),updateWorkflowTransitionRuleConfigurations:t=>fL(e,t),deleteWorkflowTransitionRuleConfigurations:t=>fU(e,t)},workflowSchemes:{getAllWorkflowSchemes:t=>fQ(e,t),createWorkflowScheme:t=>fZ(e,t),readWorkflowSchemes:t=>fX(e,t),updateSchemes:t=>f0(e,t),getRequiredWorkflowSchemeMappings:t=>f1(e,t),getWorkflowScheme:t=>f2(e,t),updateWorkflowScheme:t=>f3(e,t),deleteWorkflowScheme:t=>f4(e,t),getDefaultWorkflow:t=>f5(e,t),updateDefaultWorkflow:t=>f6(e,t),deleteDefaultWorkflow:t=>f8(e,t),getWorkflowSchemeIssueType:t=>f9(e,t),setWorkflowSchemeIssueType:t=>f7(e,t),deleteWorkflowSchemeIssueType:t=>ge(e,t),getWorkflow:t=>gt(e,t),updateWorkflowMapping:t=>gr(e,t),deleteWorkflowMapping:t=>gi(e,t),getProjectUsagesForWorkflowScheme:t=>ga(e,t)},workflowSchemeProjectAssociations:{getWorkflowSchemeProjectAssociations:t=>go(e,t),assignSchemeToProject:t=>gl(e,t)},workflowSchemeDrafts:{createWorkflowSchemeDraftFromParent:t=>gu(e,t),getWorkflowSchemeDraft:t=>gc(e,t),updateWorkflowSchemeDraft:t=>gd(e,t),deleteWorkflowSchemeDraft:t=>gh(e,t),getDraftDefaultWorkflow:t=>gp(e,t),updateDraftDefaultWorkflow:t=>gm(e,t),deleteDraftDefaultWorkflow:t=>gf(e,t),getWorkflowSchemeDraftIssueType:t=>gg(e,t),setWorkflowSchemeDraftIssueType:t=>gy(e,t),deleteWorkflowSchemeDraftIssueType:t=>gw(e,t),publishDraftWorkflowScheme:t=>gb(e,t),getDraftWorkflow:t=>gE(e,t),updateDraftWorkflowMapping:t=>gS(e,t),deleteDraftWorkflowMapping:t=>gv(e,t)},appProperties:{getAddonProperties:t=>g_(e,t),getAddonProperty:t=>gT(e,t),putAddonProperty:t=>gC(e,t),deleteAddonProperty:t=>gR(e,t),getForgeAppPropertyKeys:()=>gN(e),getForgeAppProperty:t=>gO(e,t),putForgeAppProperty:t=>gD(e,t),deleteForgeAppProperty:t=>gP(e,t)},dynamicModules:{getModules:()=>gU(e),registerModules:t=>gB(e,t),removeModules:t=>gM(e,t)},appMigration:{updateIssueFields:t=>gj(e,t),updateEntityPropertiesValue:t=>g$(e,t),workflowRuleSearch:t=>gG(e,t)},migrationOfConnectModulesToForge:{fetchMigrationTask:t=>gz(e,t),submitTask:t=>gH(e,t)},api:{getWorklogsByIssueIdAndWorklogId:t=>gW(e,t)}}),agile:(r=K(n),{backlog:{moveIssuesToBacklog:e=>W(r,e),moveIssuesToBacklogForBoard:e=>J(r,e)},board:{getAllBoards:e=>eq(r,e),createBoard:e=>ej(r,e),getBoardByFilterId:e=>e$(r,e),getBoard:e=>eG(r,e),deleteBoard:e=>eF(r,e),getIssuesForBacklog:e=>ez(r,e),getApproximateIssueCountForBacklog:e=>eH(r,e),getConfiguration:e=>eV(r,e),getEpics:e=>eK(r,e),getIssuesWithoutEpicForBoard:e=>eW(r,e),getBoardIssuesForEpic:e=>eJ(r,e),getFeaturesForBoard:e=>eY(r,e),toggleFeatures:e=>eQ(r,e),moveIssuesToBoard:e=>eZ(r,e),getIssuesForBoard:e=>eX(r,e),getApproximateIssueCountForBoard:e=>e0(r,e),getProjects:e=>e1(r,e),getProjectsFull:e=>e2(r,e),getBoardPropertyKeys:e=>e3(r,e),getBoardProperty:e=>e4(r,e),setBoardProperty:e=>e5(r,e),deleteBoardProperty:e=>e6(r,e),getAllQuickFilters:e=>e8(r,e),getQuickFilter:e=>e9(r,e),getReportsForBoard:e=>e7(r,e),getAllSprints:e=>te(r,e),getBoardIssuesForSprint:e=>tt(r,e),getAllVersions:e=>tr(r,e)},epic:{removeIssuesFromEpic:e=>ti(r,e),getIssuesWithoutEpic:e=>ta(r,e),getEpic:e=>tn(r,e),partiallyUpdateEpic:e=>ts(r,e),moveIssuesToEpic:e=>to(r,e),getIssuesForEpic:e=>tl(r,e),rankEpics:e=>tu(r,e)},issue:{rankIssues:e=>th(r,e),getIssue:e=>tp(r,e),getIssueEstimationForBoard:e=>tm(r,e),estimateIssueForBoard:e=>tf(r,e)},sprint:{createSprint:e=>tg(r,e),getSprint:e=>ty(r,e),partiallyUpdateSprint:e=>tw(r,e),updateSprint:e=>tb(r,e),deleteSprint:e=>tE(r,e),moveIssuesToSprintAndRank:e=>tS(r,e),getIssuesForSprint:e=>tv(r,e),getPropertiesKeys:e=>tI(r,e),getProperty:e=>tA(r,e),setProperty:e=>tk(r,e),deleteProperty:e=>t_(r,e),swapSprint:e=>tT(r,e)},developmentInformation:{storeDevelopmentInformation:e=>tD(r,e),getRepository:e=>tP(r,e),deleteRepository:e=>tx(r,e),deleteByProperties:e=>tL(r,e),existsByProperties:e=>tU(r,e),deleteEntity:e=>tB(r,e)},featureFlags:{submitFeatureFlags:e=>tj(r,e),deleteFeatureFlagsByProperty:e=>t$(r,e),getFeatureFlagById:e=>tG(r,e),deleteFeatureFlagById:e=>tF(r,e)},deployments:{submitDeployments:e=>tJ(r,e),deleteDeploymentsByProperty:e=>tY(r,e),getDeploymentByKey:e=>tQ(r,e),deleteDeploymentByKey:e=>tZ(r,e),getDeploymentGatingStatusByKey:e=>tX(r,e)},builds:{submitBuilds:e=>t2(r,e),deleteBuildsByProperty:e=>t3(r,e),getBuildByKey:e=>t4(r,e),deleteBuildByKey:e=>t5(r,e)},remoteLinks:{submitRemoteLinks:e=>t9(r,e),deleteRemoteLinksByProperty:e=>t7(r,e),getRemoteLinkById:e=>re(r,e),deleteRemoteLinkById:e=>rt(r,e)},securityInformation:{submitWorkspaces:e=>rs(r,e),deleteLinkedWorkspaces:e=>ro(r,e),getLinkedWorkspaces:()=>rl(r),getLinkedWorkspaceById:e=>ru(r,e),submitVulnerabilities:e=>rc(r,e),deleteVulnerabilitiesByProperty:e=>rd(r,e),getVulnerabilityById:e=>rh(r,e),deleteVulnerabilityById:e=>rp(r,e)},operations:{submitOperationsWorkspaces:e=>rb(r,e),deleteWorkspaces:e=>rE(r,e),getWorkspaces:e=>rS(r,e),submitEntity:e=>rv(r,e),deleteEntityByProperty:e=>rI(r,e),getIncidentById:e=>rA(r,e),deleteIncidentById:e=>rk(r,e),getReviewById:e=>r_(r,e),deleteReviewById:e=>rT(r,e)},devopsComponents:{submitComponents:e=>rN(r,e),deleteComponentsByProperty:e=>rO(r,e),getComponentById:e=>rD(r,e),deleteComponentById:e=>rP(r,e)}})},this.clients}async webhookApiRequest(e,t,r){let i,a=await this.requireCredentials(),n=Buffer.from(`${a.email}:${a.apiToken}`).toString("base64");try{i=await fetch(`${a.siteUrl}${t}`,{method:e,headers:{Accept:"application/json",Authorization:`Basic ${n}`,"Content-Type":"application/json"},body:void 0===r?void 0:JSON.stringify(r),signal:AbortSignal.timeout(15e3)})}catch(e){throw Error(vm(e,a.apiToken))}let s=await i.text();if(!i.ok){let e=s.trim().slice(0,300)||i.statusText;throw Object.assign(Error(vm(`Jira rejected the webhook request with ${i.status}: ${e}`,a.apiToken)),{status:i.status})}if(!s.trim())return null;try{return JSON.parse(s)}catch{return null}}async currentAccountId(){let e=vs(va((await this.cachedCall({operation:"MYSELF",params:{},requestSummary:"Current Jira user",fetcher:async()=>{let{cloud:e}=await this.getClients();return e.myself.getCurrentUser()}})).value).accountId);if(!e)throw Error("Jira did not return the current user ID");return e}async linkCacheEntryToIssue(e,t){let r=await (0,gJ.getPrismaClient)();await r.$transaction(async r=>{await r.jiraCachedTicket.upsert({where:{issueKey:e},create:{issueKey:e,projectKey:e.replace(/-\d+$/,"")},update:{}}),await r.jiraCacheEntryIssue.upsert({where:{cacheEntryId_issueKey:{cacheEntryId:t,issueKey:e}},create:{cacheEntryId:t,issueKey:e},update:{}})})}async mutateTicket(e,t,r){let i,a=await this.requireCredentials(),n=Date.now();try{await r(),await this.logCall({operation:t,requestSummary:`${t.replaceAll("_"," ")} for ${e}`,source:"LIVE",durationMs:Date.now()-n})}catch(i){let r=vm(i,a.apiToken);throw await this.logCall({operation:t,requestSummary:`${t.replaceAll("_"," ")} for ${e}`,source:"ERROR",durationMs:Date.now()-n,statusCode:vp(i),error:r}),Error(r)}await this.invalidateIssueCaches(e);try{i=await this.ticket(e,!0)}catch(e){throw Error(`Jira accepted the update, but refreshed ticket details could not be loaded: ${vm(e,a.apiToken)}`)}return gY.agentEventBus.publish(gY.JIRA_TICKET_CHANGED_TOPIC,{jiraTicketChanged:{issueKey:i.key,projectKey:i.projectKey,event:`aide:${t.toLowerCase()}`}}),i}cacheKey(e,r,i){return(0,t.createHash)("sha256").update(vh({siteUrl:e,operation:r,params:i})).digest("hex")}async cachedCall(e){let r=await this.requireCredentials(),i=await (0,gJ.getPrismaClient)(),a=this.cacheKey(r.siteUrl,e.operation,e.params),n=Date.now(),s=await i.jiraCacheEntry.findUnique({where:{cacheKey:a}}),o=null!==s&&Date.now()-s.fetchedAt.getTime()<1e3*r.cacheTtlSeconds;if(!e.force&&o)return await this.logCall({operation:e.operation,requestSummary:e.requestSummary,source:"CACHE",durationMs:Date.now()-n,itemCount:e.itemCount?.(vc(s.responseJson))??null,sourceId:e.sourceId}),{value:vc(s.responseJson),source:"CACHE",stale:!1,fetchedAt:s.fetchedAt,entryId:s.id};let l=this.inFlight.get(a);if(l){let t=await l;return await this.logCall({operation:e.operation,requestSummary:`${e.requestSummary} (coalesced)`,source:"CACHE",durationMs:Date.now()-n,itemCount:e.itemCount?.(t.value)??null,sourceId:e.sourceId}),{...t,source:"CACHE"}}let u=(async()=>{try{let r=await e.fetcher(),s=new Date,o=await i.jiraCacheEntry.upsert({where:{cacheKey:a},create:{id:(0,t.randomUUID)(),cacheKey:a,operation:e.operation,paramsJson:vh(e.params),responseJson:JSON.stringify(r),fetchedAt:s,sourceId:e.sourceId??null},update:{operation:e.operation,paramsJson:vh(e.params),responseJson:JSON.stringify(r),fetchedAt:s,sourceId:e.sourceId??null}});return await this.logCall({operation:e.operation,requestSummary:e.requestSummary,source:"LIVE",durationMs:Date.now()-n,itemCount:e.itemCount?.(r)??null,sourceId:e.sourceId}),{value:r,source:"LIVE",stale:!1,fetchedAt:s,entryId:o.id}}catch(i){let t=null!==s&&!1!==e.allowStaleOnError;if(await this.logCall({operation:e.operation,requestSummary:e.requestSummary,source:"ERROR",durationMs:Date.now()-n,statusCode:vp(i),error:vm(i,r.apiToken),servedStale:t,sourceId:e.sourceId}),t)return{value:vc(s.responseJson),source:"ERROR",stale:!0,fetchedAt:s.fetchedAt,entryId:s.id};throw Error(vm(i,r.apiToken))}})();this.inFlight.set(a,u);try{return await u}finally{this.inFlight.delete(a)}}async logCall(e){if(!this.recordCallLogs)return;let r=await (0,gJ.getPrismaClient)();await r.jiraApiCallLog.create({data:{id:(0,t.randomUUID)(),operation:e.operation,requestSummary:e.requestSummary.slice(0,1e3),source:e.source,durationMs:Math.max(0,Math.round(e.durationMs)),statusCode:e.statusCode??null,error:e.error??null,itemCount:e.itemCount??null,servedStale:e.servedStale??!1,sourceId:e.sourceId??null}})}validateSourceName(e){let t=e.trim();if(!t||t.length>100)throw Error("Source name must be 1 to 100 characters");return t}async validateSource(e,t){let r=t.trim();if(!r)throw Error("BOARD"===e?"Board URL is required":"JQL is required");if("JQL"===e)return await this.cachedCall({operation:"JQL_VALIDATE",params:{jql:r},requestSummary:`Validate JQL: ${r}`,fetcher:async()=>{let{cloud:e}=await this.getClients();return e.issueSearch.searchAndReconsileIssuesUsingJql({jql:r,maxResults:1,fields:["key"],failFast:!0})}}),{value:r,boardId:null};let i=function(e,t){let r=new URL(e.trim());if(r.origin!==new URL(t).origin)throw Error("Board URL must belong to the configured Jira site");let i=r.pathname.match(/\/boards\/(\d+)(?:\/|$)/i),a=r.searchParams.get("rapidView"),n=Number(i?.[1]??a);if(!Number.isSafeInteger(n)||n<=0)throw Error("Board URL must contain a Jira board ID");return{boardId:n,normalizedUrl:r.toString()}}(r,(await this.requireCredentials()).siteUrl);return await this.cachedCall({operation:"BOARD",params:{boardId:i.boardId},requestSummary:`Board ${i.boardId}`,fetcher:async()=>{let{agile:e}=await this.getClients();return e.board.getBoard({boardId:i.boardId})}}),{value:i.normalizedUrl,boardId:i.boardId}}async loadJqlSource(e,t){let r,i=[],a=[],n=[],s=!1;do{let o=Math.min(100,1e3-i.length),l=await this.cachedCall({operation:"JQL_SEARCH",params:{jql:e.value,nextPageToken:r??null,maxResults:o,fields:vt},requestSummary:`JQL ${e.name}${r?" next page":""}`,sourceId:e.id,force:t,fetcher:async()=>{let{cloud:t}=await this.getClients();return t.issueSearch.searchAndReconsileIssuesUsingJql({jql:e.value,nextPageToken:r,maxResults:o,fields:vt})},itemCount:e=>e.issues?.length??0});a.push(l);let u=l.value.issues??[];i.push(...u),n.push(...vo(l.value)),"LIVE"===l.source&&await this.storeSummaries(l.entryId,u,l.fetchedAt);let c=vs(l.value.nextPageToken)??void 0,d=!0!==l.value.isLast&&!!c;d&&c===r?(n.push("Jira returned a repeated JQL pagination token."),r=void 0):r=d?c:void 0,i.length>=1e3&&r&&(s=!0)}while(r&&i.length<1e3)return this.buildBoardResult(i,a,n,s)}async loadBoardSource(e,t){if(!e.boardId)throw Error("Saved board source has no board ID");let r=await this.cachedCall({operation:"BOARD",params:{boardId:e.boardId},requestSummary:`Board ${e.boardId}`,sourceId:e.id,force:t,fetcher:async()=>{let{agile:t}=await this.getClients();return t.board.getBoard({boardId:e.boardId})}}),i=await this.cachedCall({operation:"BOARD_CONFIGURATION",params:{boardId:e.boardId},requestSummary:`Board ${e.boardId} configuration`,sourceId:e.id,force:t,fetcher:async()=>{let{agile:t}=await this.getClients();return t.board.getConfiguration({boardId:e.boardId})}}),a=[r,i],n=[],s=[],o=!1;if("scrum"===(vs(r.value.type)??"").toLowerCase()){let r=await this.cachedCall({operation:"SPRINTS",params:{boardId:e.boardId,state:"active"},requestSummary:`Active sprints for board ${e.boardId}`,sourceId:e.id,force:t,fetcher:async()=>{let{agile:t}=await this.getClients();return t.board.getAllSprints({boardId:e.boardId,state:"active",startAt:0,maxResults:100})},itemCount:e=>vn(e.values).length});a.push(r);let i=vn(r.value.values).map(va);for(let r of(0===i.length&&s.push("This Scrum board has no active sprint."),i)){let i=vl(r.id);if(!i||n.length>=1e3)continue;let l=await this.loadAgileIssues("SPRINT_ISSUES",e,t,(e,t)=>({sprintId:i,nextPageToken:e,maxResults:t,fields:vt}),async e=>{let{agile:t}=await this.getClients();return t.sprint.getIssuesForSprint(e)},n.length);n.push(...l.issues),a.push(...l.results),s.push(...l.warnings),o||=l.truncated}}else{let r=await this.loadAgileIssues("BOARD_ISSUES",e,t,(t,r)=>({boardId:e.boardId,nextPageToken:t,maxResults:r,fields:vt}),async e=>{let{agile:t}=await this.getClients();return t.board.getIssuesForBoard(e)},0);n.push(...r.issues),a.push(...r.results),s.push(...r.warnings),o=r.truncated}let l=[...new Map(n.map(e=>[e.key??e.id,e])).values()],u=new Map;return vn(va(i.value.columnConfig).columns).map(va).forEach((e,t)=>{vn(e.statuses).map(va).forEach(e=>{let r=vs(e.id);r&&u.set(r,t)})}),this.buildBoardResult(l,a,s,o,u)}async loadAgileIssues(e,t,r,i,a,n){let s,o=[],l=[],u=[],c=!1;for(;o.length+n<1e3;){let c=i(s,Math.min(100,1e3-n-o.length)),d=await this.cachedCall({operation:e,params:c,requestSummary:`${e.replaceAll("_"," ")}${s?" next page":""}`,sourceId:t.id,force:r,fetcher:()=>a(c),itemCount:e=>e.issues?.length??0});l.push(d);let h=d.value.issues??[];o.push(...h),u.push(...vo(d.value)),"LIVE"===d.source&&await this.storeSummaries(d.entryId,h,d.fetchedAt);let p=vs(d.value.nextPageToken)??void 0,m=!0!==d.value.isLast&&!!p;if(0===h.length||!m){s=void 0;break}if(p===s){u.push("Jira returned a repeated Agile pagination token."),s=void 0;break}s=p}return o.length+n>=1e3&&s&&(c=!0),{issues:o,results:l,warnings:u,truncated:c}}buildBoardResult(e,t,r,i,a){let n=e.slice(0,1e3).map(vv),s=[...new Map(n.map(e=>[e.status,e])).values()];return s.sort((e,t)=>{let r=a?.get(e.statusId),i=a?.get(t.statusId);return void 0!==r||void 0!==i?(r??Number.MAX_SAFE_INTEGER)-(i??Number.MAX_SAFE_INTEGER):vI(e.statusCategory)-vI(t.statusCategory)||e.status.localeCompare(t.status)}),{tickets:n,statusOrder:s.map(e=>e.status),cache:vS(t),truncated:i,warnings:[...new Set(r)]}}async storeSummaries(e,t,r){let i=await (0,gJ.getPrismaClient)();await i.$transaction(async i=>{for(let e of t)e.key&&await i.jiraCachedTicket.upsert({where:{issueKey:e.key},create:{issueKey:e.key,projectKey:vf(e),summaryJson:JSON.stringify(e),summaryFetchedAt:r},update:{projectKey:vf(e),summaryJson:JSON.stringify(e),summaryFetchedAt:r}});await i.jiraCacheEntryIssue.deleteMany({where:{cacheEntryId:e}});let a=[...new Set(t.map(e=>e.key).filter(Boolean))];a.length>0&&await i.jiraCacheEntryIssue.createMany({data:a.map(t=>({cacheEntryId:e,issueKey:t}))})})}async storeDetail(e,t,r){if(!t.key)throw Error("Jira detail response did not include an issue key");let i=await (0,gJ.getPrismaClient)();await i.$transaction(async i=>{await i.jiraCachedTicket.upsert({where:{issueKey:t.key},create:{issueKey:t.key,projectKey:vf(t),detailJson:JSON.stringify(t),detailFetchedAt:r},update:{projectKey:vf(t),detailJson:JSON.stringify(t),detailFetchedAt:r}}),await i.jiraCacheEntryIssue.upsert({where:{cacheEntryId_issueKey:{cacheEntryId:e,issueKey:t.key}},create:{cacheEntryId:e,issueKey:t.key},update:{}})})}async storeComments(e,t,r,i){let a=await (0,gJ.getPrismaClient)();await a.$transaction(async a=>{for(let n of(await a.jiraCachedTicket.upsert({where:{issueKey:e},create:{issueKey:e,projectKey:e.split("-")[0]??"UNKNOWN",commentsJson:JSON.stringify(t),commentsFetchedAt:r},update:{commentsJson:JSON.stringify(t),commentsFetchedAt:r}}),i))await a.jiraCacheEntryIssue.upsert({where:{cacheEntryId_issueKey:{cacheEntryId:n,issueKey:e}},create:{cacheEntryId:n,issueKey:e},update:{}})})}normalizeTicketDetail(e,r,i,a,n){let s=vv(e),o=va(e.fields),l=va(e.names),u=va(e.schema),c=[];for(let e of vn(o.issuelinks).map(va)){let t=va(e.type),r=vw(e.outwardIssue,vs(t.outward)??"relates to"),i=vw(e.inwardIssue,vs(t.inward)??"relates to");r&&c.push(r),i&&c.push(i)}let d=vw(o.parent,"parent"),h=vn(o.subtasks).map(e=>vw(e,"subtask")).filter(e=>null!==e),p=vn(o.sprint).map(va),m=vn(o.closedSprints).map(va),f=p.filter(e=>{let t=vs(e.state)?.toLowerCase();return!t||"active"===t}).map(e=>vs(e.name)).filter(e=>!!e),g=m.concat(p.filter(e=>vs(e.state)?.toLowerCase()==="closed")).map(e=>vs(e.name)).filter(e=>!!e),y=f.concat(g),w=r.map(va).map(e=>({id:vs(e.id)??(0,t.randomUUID)(),author:vg(e.author),body:e.body??null,content:S9(e.body??null,i),createdAt:vs(e.created),updatedAt:vs(e.updated)}));return{...s,jiraUrl:`${i}/browse/${s.key}`,description:o.description??null,descriptionContent:S9(o.description??null,i),reporter:vg(o.reporter),creator:vg(o.creator),labels:vn(o.labels).filter(e=>"string"==typeof e),components:vy(o.components),fixVersions:vy(o.fixVersions),affectedVersions:vy(o.versions),sprintNames:[...new Set(y)],activeSprintNames:[...new Set(f)],closedSprintNames:[...new Set(g)],parent:d,subtasks:h,issueLinks:c,attachments:vn(o.attachment).map(va).map(e=>({id:vs(e.id)??(0,t.randomUUID)(),filename:vs(e.filename)??"Attachment",contentUrl:vs(e.content),mimeType:vs(e.mimeType),size:vl(e.size),author:vg(e.author),createdAt:vs(e.created)})),comments:w,createdAt:vs(o.created),dueAt:vs(o.duedate),resolvedAt:vs(o.resolutiondate),timeTracking:o.timetracking??null,allFields:Object.entries(o).map(([e,t])=>{let r=va(u[e]),a="string"==typeof t||vi(t)&&"doc"===t.type?S9(t,i):null;return{id:e,name:vs(l[e])??e,schemaType:vs(r.type),custom:!0===r.custom||e.startsWith("customfield_"),value:t??null,content:a}}).sort((e,t)=>e.name.localeCompare(t.name)),cache:a,commentsCache:n}}cachedTicketView(e,t){let r=vv(va(vc(e.detailJson)??vc(e.summaryJson))),i=e.detailJson&&e.commentsJson?"FULL":e.detailJson?"DETAIL":"SUMMARY",a=[e.summaryFetchedAt,e.detailFetchedAt,e.commentsFetchedAt].filter(e=>null!==e).some(e=>Date.now()-e.getTime()>=1e3*t);return{issueKey:e.issueKey,projectKey:e.projectKey,summary:r.summary,status:"Unknown"===r.status?null:r.status,coverage:i,stale:a,summaryFetchedAt:e.summaryFetchedAt?.toISOString()??null,detailFetchedAt:e.detailFetchedAt?.toISOString()??null,commentsFetchedAt:e.commentsFetchedAt?.toISOString()??null,updatedAt:e.updatedAt.toISOString()}}validatePagination(e,t){if(!Number.isInteger(e)||e<1||e>100)throw Error("Pagination limit must be from 1 to 100");if(!Number.isInteger(t)||t<0)throw Error("Pagination offset must be non-negative");return{limit:e,offset:t}}metricWindow(e,t){return{window:e,total:t.length,live:t.filter(e=>"LIVE"===e.source).length,cache:t.filter(e=>"CACHE"===e.source).length,errors:t.filter(e=>"ERROR"===e.source).length,averageMs:0===t.length?0:Math.round(t.reduce((e,t)=>e+t.durationMs,0)/t.length)}}async pruneLogs(){let e=Date.now();if(e-this.lastPrunedAt<36e5)return;this.lastPrunedAt=e;let t=await (0,gJ.getPrismaClient)();await t.jiraApiCallLog.deleteMany({where:{createdAt:{lt:new Date(e-2592e6)}}})}}],126223)},141528,(e,t,r)=>{function i(e,t,r,i){return Math.round(e/r)+" "+i+(t>=1.5*r?"s":"")}t.exports=function(e,t){t=t||{};var r,a,n,s,o=typeof e;if("string"===o&&e.length>0){var l=e;if(!((l=String(l)).length>100)){var u=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(l);if(u){var c=parseFloat(u[1]);switch((u[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*c;case"weeks":case"week":case"w":return 6048e5*c;case"days":case"day":case"d":return 864e5*c;case"hours":case"hour":case"hrs":case"hr":case"h":return 36e5*c;case"minutes":case"minute":case"mins":case"min":case"m":return 6e4*c;case"seconds":case"second":case"secs":case"sec":case"s":return 1e3*c;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return c;default:break}}}return}if("number"===o&&isFinite(e)){return t.long?(a=Math.abs(r=e))>=864e5?i(r,a,864e5,"day"):a>=36e5?i(r,a,36e5,"hour"):a>=6e4?i(r,a,6e4,"minute"):a>=1e3?i(r,a,1e3,"second"):r+" ms":(s=Math.abs(n=e))>=864e5?Math.round(n/864e5)+"d":s>=36e5?Math.round(n/36e5)+"h":s>=6e4?Math.round(n/6e4)+"m":s>=1e3?Math.round(n/1e3)+"s":n+"ms"}throw Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},916525,(e,t,r)=>{t.exports=function(t){function r(e){let t,a,n,s=null;function o(...e){if(!o.enabled)return;let i=Number(new Date);o.diff=i-(t||i),o.prev=t,o.curr=i,t=i,e[0]=r.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(t,i)=>{if("%%"===t)return"%";a++;let n=r.formatters[i];if("function"==typeof n){let r=e[a];t=n.call(o,r),e.splice(a,1),a--}return t}),r.formatArgs.call(o,e),(o.log||r.log).apply(o,e)}return o.namespace=e,o.useColors=r.useColors(),o.color=r.selectColor(e),o.extend=i,o.destroy=r.destroy,Object.defineProperty(o,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==s?s:(a!==r.namespaces&&(a=r.namespaces,n=r.enabled(e)),n),set:e=>{s=e}}),"function"==typeof r.init&&r.init(o),o}function i(e,t){let i=r(this.namespace+(void 0===t?":":t)+e);return i.log=this.log,i}function a(e,t){let r=0,i=0,a=-1,n=0;for(;r<e.length;)if(i<t.length&&(t[i]===e[r]||"*"===t[i]))"*"===t[i]?(a=i,n=r):r++,i++;else{if(-1===a)return!1;i=a+1,r=++n}for(;i<t.length&&"*"===t[i];)i++;return i===t.length}return r.debug=r,r.default=r,r.coerce=function(e){return e instanceof Error?e.stack||e.message:e},r.disable=function(){let e=[...r.names,...r.skips.map(e=>"-"+e)].join(",");return r.enable(""),e},r.enable=function(e){for(let t of(r.save(e),r.namespaces=e,r.names=[],r.skips=[],("string"==typeof e?e:"").trim().replace(/\s+/g,",").split(",").filter(Boolean)))"-"===t[0]?r.skips.push(t.slice(1)):r.names.push(t)},r.enabled=function(e){for(let t of r.skips)if(a(e,t))return!1;for(let t of r.names)if(a(e,t))return!0;return!1},r.humanize=e.r(141528),r.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(t).forEach(e=>{r[e]=t[e]}),r.names=[],r.skips=[],r.formatters={},r.selectColor=function(e){let t=0;for(let r=0;r<e.length;r++)t=(t<<5)-t+e.charCodeAt(r)|0;return r.colors[Math.abs(t)%r.colors.length]},r.enable(r.load()),r}},53803,264977,e=>{"use strict";var t,r={type:"sync",importFFI:()=>e.A(175367).then(e=>e.QuickJSFFI),importModuleLoader:()=>e.A(674591).then(e=>e.default)};async function i(t){let r=n(await t),[i,a,{QuickJSWASMModule:s}]=await Promise.all([r.importModuleLoader().then(n),r.importFFI(),e.A(969484).then(n)]),o=await i();o.type="sync";let l=new a(o);return new s(o,l)}async function a(t){let r=n(await t),[i,a,{QuickJSAsyncWASMModule:s}]=await Promise.all([r.importModuleLoader().then(n),r.importFFI(),e.A(706986).then(n)]),o=await i();o.type="async";let l=new a(o);return new s(o,l)}function n(e){return e&&"default"in e&&e.default?e.default&&"default"in e.default&&e.default.default?e.default.default:e.default:e}async function s(e=r){return i(e)}async function o(){return t??(t=s().then(e=>e)),await t}e.i(215402),e.i(469064),e.s(["newQuickJSAsyncWASMModuleFromVariant",0,a,"newQuickJSWASMModuleFromVariant",0,i,"shouldInterruptAfterDeadline",0,function(e){let t="number"==typeof e?e:e.getTime();return function(){return Date.now()>t}}],264977),e.s(["getQuickJS",0,o],53803)},289064,(e,t,r)=>{var i,a;a=i||(i={}),function(t){var r="object"==typeof globalThis?globalThis:e.g,i=n(a);function n(e,t){return function(r,i){Object.defineProperty(e,r,{configurable:!0,writable:!0,value:i}),t&&t(r,i)}}void 0!==r.Reflect&&(i=n(r.Reflect,i)),t(i,r),void 0===r.Reflect&&(r.Reflect=a)}(function(e,t){var r,i=Object.prototype.hasOwnProperty,a="function"==typeof Symbol,n=a&&void 0!==Symbol.toPrimitive?Symbol.toPrimitive:"@@toPrimitive",s=a&&void 0!==Symbol.iterator?Symbol.iterator:"@@iterator",o="function"==typeof Object.create,l=({__proto__:[]})instanceof Array,u=!o&&!l,c={create:o?function(){return B(Object.create(null))}:l?function(){return B({__proto__:null})}:function(){return B({})},has:u?function(e,t){return i.call(e,t)}:function(e,t){return t in e},get:u?function(e,t){return i.call(e,t)?e[t]:void 0}:function(e,t){return e[t]}},d=Object.getPrototypeOf(Function),h="function"==typeof Map&&"function"==typeof Map.prototype.entries?Map:function(){var e={},t=[],r=function(){function e(e,t,r){this._index=0,this._keys=e,this._values=t,this._selector=r}return e.prototype["@@iterator"]=function(){return this},e.prototype[s]=function(){return this},e.prototype.next=function(){var e=this._index;if(e>=0&&e<this._keys.length){var r=this._selector(this._keys[e],this._values[e]);return e+1>=this._keys.length?(this._index=-1,this._keys=t,this._values=t):this._index++,{value:r,done:!1}}return{value:void 0,done:!0}},e.prototype.throw=function(e){throw this._index>=0&&(this._index=-1,this._keys=t,this._values=t),e},e.prototype.return=function(e){return this._index>=0&&(this._index=-1,this._keys=t,this._values=t),{value:e,done:!0}},e}();function i(){this._keys=[],this._values=[],this._cacheKey=e,this._cacheIndex=-2}return Object.defineProperty(i.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),i.prototype.has=function(e){return this._find(e,!1)>=0},i.prototype.get=function(e){var t=this._find(e,!1);return t>=0?this._values[t]:void 0},i.prototype.set=function(e,t){var r=this._find(e,!0);return this._values[r]=t,this},i.prototype.delete=function(t){var r=this._find(t,!1);if(r>=0){for(var i=this._keys.length,a=r+1;a<i;a++)this._keys[a-1]=this._keys[a],this._values[a-1]=this._values[a];return this._keys.length--,this._values.length--,N(t,this._cacheKey)&&(this._cacheKey=e,this._cacheIndex=-2),!0}return!1},i.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=e,this._cacheIndex=-2},i.prototype.keys=function(){return new r(this._keys,this._values,a)},i.prototype.values=function(){return new r(this._keys,this._values,n)},i.prototype.entries=function(){return new r(this._keys,this._values,o)},i.prototype["@@iterator"]=function(){return this.entries()},i.prototype[s]=function(){return this.entries()},i.prototype._find=function(e,t){if(!N(this._cacheKey,e)){this._cacheIndex=-1;for(var r=0;r<this._keys.length;r++)if(N(this._keys[r],e)){this._cacheIndex=r;break}}return this._cacheIndex<0&&t&&(this._cacheIndex=this._keys.length,this._keys.push(e),this._values.push(void 0)),this._cacheIndex},i;function a(e,t){return e}function n(e,t){return t}function o(e,t){return[e,t]}}(),p="function"==typeof Set&&"function"==typeof Set.prototype.entries?Set:function(){function e(){this._map=new h}return Object.defineProperty(e.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),e.prototype.has=function(e){return this._map.has(e)},e.prototype.add=function(e){return this._map.set(e,e),this},e.prototype.delete=function(e){return this._map.delete(e)},e.prototype.clear=function(){this._map.clear()},e.prototype.keys=function(){return this._map.keys()},e.prototype.values=function(){return this._map.keys()},e.prototype.entries=function(){return this._map.entries()},e.prototype["@@iterator"]=function(){return this.keys()},e.prototype[s]=function(){return this.keys()},e}(),m="function"==typeof WeakMap?WeakMap:function(){var e=c.create(),t=a();function r(){this._key=a()}return r.prototype.has=function(e){var t=n(e,!1);return void 0!==t&&c.has(t,this._key)},r.prototype.get=function(e){var t=n(e,!1);return void 0!==t?c.get(t,this._key):void 0},r.prototype.set=function(e,t){return n(e,!0)[this._key]=t,this},r.prototype.delete=function(e){var t=n(e,!1);return void 0!==t&&delete t[this._key]},r.prototype.clear=function(){this._key=a()},r;function a(){var t;do t="@@WeakMap@@"+function(){var e=function(){if("function"==typeof Uint8Array){var e=new Uint8Array(16);return"u">typeof crypto?crypto.getRandomValues(e):"u">typeof msCrypto?msCrypto.getRandomValues(e):s(e,16),e}return s(Array(16),16)}();e[6]=79&e[6]|64,e[8]=191&e[8]|128;for(var t="",r=0;r<16;++r){var i=e[r];(4===r||6===r||8===r)&&(t+="-"),i<16&&(t+="0"),t+=i.toString(16).toLowerCase()}return t}();while(c.has(e,t))return e[t]=!0,t}function n(e,r){if(!i.call(e,t)){if(!r)return;Object.defineProperty(e,t,{value:c.create()})}return e[t]}function s(e,t){for(var r=0;r<t;++r)e[r]=255*Math.random()|0;return e}}(),f=a?Symbol.for("@reflect-metadata:registry"):void 0,g=(!I(f)&&k(t.Reflect)&&Object.isExtensible(t.Reflect)&&(r=t.Reflect[f]),I(r)&&(r=function(){I(f)||void 0===t.Reflect||f in t.Reflect||"function"!=typeof t.Reflect.defineMetadata||(r=(e=t.Reflect).defineMetadata,i=e.hasOwnMetadata,a=e.getOwnMetadata,n=e.getOwnMetadataKeys,s=e.deleteMetadata,o=new m,l={isProviderFor:function(e,t){var r=o.get(e);return!!(!I(r)&&r.has(t))||!!n(e,t).length&&(I(r)&&(r=new p,o.set(e,r)),r.add(t),!0)},OrdinaryDefineOwnMetadata:r,OrdinaryHasOwnMetadata:i,OrdinaryGetOwnMetadata:a,OrdinaryOwnMetadataKeys:n,OrdinaryDeleteMetadata:s});var e,r,i,a,n,s,o,l,u,c,d,g=new m,y={registerProvider:function(e){if(!Object.isExtensible(y))throw Error("Cannot add provider to a frozen registry.");switch(!0){case l===e:break;case I(u):u=e;break;case u===e:break;case I(c):c=e;break;case c===e:break;default:void 0===d&&(d=new p),d.add(e)}},getProvider:w,setProvider:function(e,t,r){if(!function(e){if(I(e))throw TypeError();return u===e||c===e||!I(d)&&d.has(e)}(r))throw Error("Metadata provider not registered.");var i=w(e,t);if(i!==r){if(!I(i))return!1;var a=g.get(e);I(a)&&(a=new h,g.set(e,a)),a.set(t,r)}return!0}};return y;function w(e,t){var r,i=g.get(e);return I(i)||(r=i.get(t)),I(r)&&(r=function(e,t){if(!I(u)){if(u.isProviderFor(e,t))return u;if(!I(c)){if(c.isProviderFor(e,t))return u;if(!I(d))for(var r=D(d);;){var i=P(r);if(!i)return;var a=i.value;if(a.isProviderFor(e,t))return x(r),a}}}if(!I(l)&&l.isProviderFor(e,t))return l}(e,t),I(r)||(I(i)&&(i=new h,g.set(e,i)),i.set(t,r))),r}}()),!I(f)&&k(t.Reflect)&&Object.isExtensible(t.Reflect)&&Object.defineProperty(t.Reflect,f,{enumerable:!1,configurable:!1,writable:!1,value:r}),r),y=function(e){var t=new m,r={isProviderFor:function(e,r){var i=t.get(e);return!I(i)&&i.has(r)},OrdinaryDefineOwnMetadata:function(e,t,r,a){i(r,a,!0).set(e,t)},OrdinaryHasOwnMetadata:function(e,t,r){var a=i(t,r,!1);return!I(a)&&!!a.has(e)},OrdinaryGetOwnMetadata:function(e,t,r){var a=i(t,r,!1);if(!I(a))return a.get(e)},OrdinaryOwnMetadataKeys:function(e,t){var r=[],a=i(e,t,!1);if(I(a))return r;for(var n=D(a.keys()),s=0;;){var o=P(n);if(!o)return r.length=s,r;var l=o.value;try{r[s]=l}catch(e){try{x(n)}finally{throw e}}s++}},OrdinaryDeleteMetadata:function(e,r,a){var n=i(r,a,!1);if(I(n)||!n.delete(e))return!1;if(0===n.size){var s=t.get(r);I(s)||(s.delete(a),0===s.size&&t.delete(s))}return!0}};return g.registerProvider(r),r;function i(i,a,n){var s=t.get(i),o=!1;if(I(s)){if(!n)return;s=new h,t.set(i,s),o=!0}var l=s.get(a);if(I(l)){if(!n)return;if(l=new h,s.set(a,l),!e.setProvider(i,a,r))throw s.delete(a),o&&t.delete(i),Error("Wrong provider for target.")}return l}}(g);function w(e,t,r){var i=U(t,r,!1);return!I(i)&&!!i.OrdinaryHasOwnMetadata(e,t,r)}function b(e,t,r){var i=U(t,r,!1);if(!I(i))return i.OrdinaryGetOwnMetadata(e,t,r)}function E(e,t,r,i){U(r,i,!0).OrdinaryDefineOwnMetadata(e,t,r,i)}function S(e,t){var r=U(e,t,!1);return r?r.OrdinaryOwnMetadataKeys(e,t):[]}function v(e){if(null===e)return 1;switch(typeof e){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return null===e?1:6;default:return 6}}function I(e){return void 0===e}function A(e){return null===e}function k(e){return"object"==typeof e?null!==e:"function"==typeof e}e("decorate",function(e,t,r,i){if(I(r)){if(!T(e)||!R(t))throw TypeError();for(var a=e,n=t,s=a.length-1;s>=0;--s){var o=(0,a[s])(n);if(!I(o)&&!A(o)){if(!R(o))throw TypeError();n=o}}return n}if(!T(e)||!k(t)||!k(i)&&!I(i)&&!A(i))throw TypeError();return A(i)&&(i=void 0),function(e,t,r,i){for(var a=e.length-1;a>=0;--a){var n=(0,e[a])(t,r,i);if(!I(n)&&!A(n)){if(!k(n))throw TypeError();i=n}}return i}(e,t,r=_(r),i)}),e("metadata",function(e,t){return function(r,i){if(!k(r)||!I(i)&&!function(e){switch(v(e)){case 3:case 4:return!0;default:return!1}}(i))throw TypeError();E(e,t,r,i)}}),e("defineMetadata",function(e,t,r,i){if(!k(r))throw TypeError();return I(i)||(i=_(i)),E(e,t,r,i)}),e("hasMetadata",function(e,t,r){if(!k(t))throw TypeError();return I(r)||(r=_(r)),function e(t,r,i){if(w(t,r,i))return!0;var a=L(r);return!A(a)&&e(t,a,i)}(e,t,r)}),e("hasOwnMetadata",function(e,t,r){if(!k(t))throw TypeError();return I(r)||(r=_(r)),w(e,t,r)}),e("getMetadata",function(e,t,r){if(!k(t))throw TypeError();return I(r)||(r=_(r)),function e(t,r,i){if(w(t,r,i))return b(t,r,i);var a=L(r);if(!A(a))return e(t,a,i)}(e,t,r)}),e("getOwnMetadata",function(e,t,r){if(!k(t))throw TypeError();return I(r)||(r=_(r)),b(e,t,r)}),e("getMetadataKeys",function(e,t){if(!k(e))throw TypeError();return I(t)||(t=_(t)),function e(t,r){var i=S(t,r),a=L(t);if(null===a)return i;var n=e(a,r);if(n.length<=0)return i;if(i.length<=0)return n;for(var s=new p,o=[],l=0;l<i.length;l++){var u=i[l],c=s.has(u);c||(s.add(u),o.push(u))}for(var d=0;d<n.length;d++){var u=n[d],c=s.has(u);c||(s.add(u),o.push(u))}return o}(e,t)}),e("getOwnMetadataKeys",function(e,t){if(!k(e))throw TypeError();return I(t)||(t=_(t)),S(e,t)}),e("deleteMetadata",function(e,t,r){if(!k(t)||(I(r)||(r=_(r)),!k(t)))throw TypeError();I(r)||(r=_(r));var i=U(t,r,!1);return!I(i)&&i.OrdinaryDeleteMetadata(e,t,r)});function _(e){var t=function(e){switch(v(e)){case 0:case 1:case 2:case 3:case 4:case 5:return e}var t="string",r=O(e,n);if(void 0!==r){var i=r.call(e,t);if(k(i))throw TypeError();return i}return function(e,t){if("string"===t){var r=e.toString;if(C(r)){var i=r.call(e);if(!k(i))return i}var a=e.valueOf;if(C(a)){var i=a.call(e);if(!k(i))return i}}else{var a=e.valueOf;if(C(a)){var i=a.call(e);if(!k(i))return i}var n=e.toString;if(C(n)){var i=n.call(e);if(!k(i))return i}}throw TypeError()}(e,t)}(e);return"symbol"==typeof t?t:""+t}function T(e){return Array.isArray?Array.isArray(e):e instanceof Object?e instanceof Array:"[object Array]"===Object.prototype.toString.call(e)}function C(e){return"function"==typeof e}function R(e){return"function"==typeof e}function N(e,t){return e===t||e!=e&&t!=t}function O(e,t){var r=e[t];if(null!=r){if(!C(r))throw TypeError();return r}}function D(e){var t=O(e,s);if(!C(t))throw TypeError();var r=t.call(e);if(!k(r))throw TypeError();return r}function P(e){var t=e.next();return!t.done&&t}function x(e){var t=e.return;t&&t.call(e)}function L(e){var t=Object.getPrototypeOf(e);if("function"!=typeof e||e===d||t!==d)return t;var r=e.prototype,i=r&&Object.getPrototypeOf(r);if(null==i||i===Object.prototype)return t;var a=i.constructor;return"function"!=typeof a||a===e?t:a}function U(e,t,r){var i=g.getProvider(e,t);if(!I(i))return i;if(r){if(g.setProvider(e,t,y))return y;throw Error("Illegal state.")}}function B(e){return e.__=void 0,delete e.__,e}})},832623,(e,t,r)=>{"use strict";var i,a=e.r(500874),n=a.Buffer,s={};for(i in a)a.hasOwnProperty(i)&&"SlowBuffer"!==i&&"Buffer"!==i&&(s[i]=a[i]);var o=s.Buffer={};for(i in n)n.hasOwnProperty(i)&&"allocUnsafe"!==i&&"allocUnsafeSlow"!==i&&(o[i]=n[i]);if(s.Buffer.prototype=n.prototype,o.from&&o.from!==Uint8Array.from||(o.from=function(e,t,r){if("number"==typeof e)throw TypeError('The "value" argument must not be of type number. Received type '+typeof e);if(e&&void 0===e.length)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);return n(e,t,r)}),o.alloc||(o.alloc=function(e,t,r){if("number"!=typeof e)throw TypeError('The "size" argument must be of type number. Received type '+typeof e);if(e<0||e>=2*0x40000000)throw RangeError('The value "'+e+'" is invalid for option "size"');var i=n(e);return t&&0!==t.length?"string"==typeof r?i.fill(t,r):i.fill(t):i.fill(0),i}),!s.kStringMaxLength)try{s.kStringMaxLength=process.binding("buffer").kStringMaxLength}catch(e){}!s.constants&&(s.constants={MAX_LENGTH:s.kMaxLength},s.kStringMaxLength&&(s.constants.MAX_STRING_LENGTH=s.kStringMaxLength)),t.exports=s},857406,(e,t,r)=>{"use strict";let i=e.r(966397);function a(e){this._reporterState={obj:null,path:[],options:e||{},errors:[]}}function n(e,t){this.path=e,this.rethrow(t)}r.Reporter=a,a.prototype.isError=function(e){return e instanceof n},a.prototype.save=function(){let e=this._reporterState;return{obj:e.obj,pathLen:e.path.length}},a.prototype.restore=function(e){let t=this._reporterState;t.obj=e.obj,t.path=t.path.slice(0,e.pathLen)},a.prototype.enterKey=function(e){return this._reporterState.path.push(e)},a.prototype.exitKey=function(e){let t=this._reporterState;t.path=t.path.slice(0,e-1)},a.prototype.leaveKey=function(e,t,r){let i=this._reporterState;this.exitKey(e),null!==i.obj&&(i.obj[t]=r)},a.prototype.path=function(){return this._reporterState.path.join("/")},a.prototype.enterObject=function(){let e=this._reporterState,t=e.obj;return e.obj={},t},a.prototype.leaveObject=function(e){let t=this._reporterState,r=t.obj;return t.obj=e,r},a.prototype.error=function(e){let t,r=this._reporterState,i=e instanceof n;if(t=i?e:new n(r.path.map(function(e){return"["+JSON.stringify(e)+"]"}).join(""),e.message||e,e.stack),!r.options.partial)throw t;return i||r.errors.push(t),t},a.prototype.wrapResult=function(e){let t=this._reporterState;return t.options.partial?{result:this.isError(e)?null:e,errors:t.errors}:e},i(n,Error),n.prototype.rethrow=function(e){if(this.message=e+" at: "+(this.path||"(shallow)"),Error.captureStackTrace&&Error.captureStackTrace(this,n),!this.stack)try{throw Error(this.message)}catch(e){this.stack=e.stack}return this}},644833,(e,t,r)=>{"use strict";let i=e.r(966397),a=e.r(857406).Reporter,n=e.r(832623).Buffer;function s(e,t){(a.call(this,t),n.isBuffer(e))?(this.base=e,this.offset=0,this.length=e.length):this.error("Input not Buffer")}function o(e,t){if(Array.isArray(e))this.length=0,this.value=e.map(function(e){return o.isEncoderBuffer(e)||(e=new o(e,t)),this.length+=e.length,e},this);else if("number"==typeof e){if(!(0<=e&&e<=255))return t.error("non-byte EncoderBuffer value");this.value=e,this.length=1}else if("string"==typeof e)this.value=e,this.length=n.byteLength(e);else{if(!n.isBuffer(e))return t.error("Unsupported type: "+typeof e);this.value=e,this.length=e.length}}i(s,a),r.DecoderBuffer=s,s.isDecoderBuffer=function(e){return e instanceof s||"object"==typeof e&&n.isBuffer(e.base)&&"DecoderBuffer"===e.constructor.name&&"number"==typeof e.offset&&"number"==typeof e.length&&"function"==typeof e.save&&"function"==typeof e.restore&&"function"==typeof e.isEmpty&&"function"==typeof e.readUInt8&&"function"==typeof e.skip&&"function"==typeof e.raw},s.prototype.save=function(){return{offset:this.offset,reporter:a.prototype.save.call(this)}},s.prototype.restore=function(e){let t=new s(this.base);return t.offset=e.offset,t.length=this.offset,this.offset=e.offset,a.prototype.restore.call(this,e.reporter),t},s.prototype.isEmpty=function(){return this.offset===this.length},s.prototype.readUInt8=function(e){return this.offset+1<=this.length?this.base.readUInt8(this.offset++,!0):this.error(e||"DecoderBuffer overrun")},s.prototype.skip=function(e,t){if(!(this.offset+e<=this.length))return this.error(t||"DecoderBuffer overrun");let r=new s(this.base);return r._reporterState=this._reporterState,r.offset=this.offset,r.length=this.offset+e,this.offset+=e,r},s.prototype.raw=function(e){return this.base.slice(e?e.offset:this.offset,this.length)},r.EncoderBuffer=o,o.isEncoderBuffer=function(e){return e instanceof o||"object"==typeof e&&"EncoderBuffer"===e.constructor.name&&"number"==typeof e.length&&"function"==typeof e.join},o.prototype.join=function(e,t){return e||(e=n.alloc(this.length)),t||(t=0),0===this.length||(Array.isArray(this.value)?this.value.forEach(function(r){r.join(e,t),t+=r.length}):("number"==typeof this.value?e[t]=this.value:"string"==typeof this.value?e.write(this.value,t):n.isBuffer(this.value)&&this.value.copy(e,t),t+=this.length)),e}},81221,(e,t,r)=>{function i(e,t){if(!e)throw Error(t||"Assertion failed")}t.exports=i,i.equal=function(e,t,r){if(e!=t)throw Error(r||"Assertion failed: "+e+" != "+t)}},524283,(e,t,r)=>{"use strict";let i=e.r(857406).Reporter,a=e.r(644833).EncoderBuffer,n=e.r(644833).DecoderBuffer,s=e.r(81221),o=["seq","seqof","set","setof","objid","bool","gentime","utctime","null_","enum","int","objDesc","bitstr","bmpstr","charstr","genstr","graphstr","ia5str","iso646str","numstr","octstr","printstr","t61str","unistr","utf8str","videostr"],l=["key","obj","use","optional","explicit","implicit","def","choice","any","contains"].concat(o);function u(e,t,r){let i={};this._baseState=i,i.name=r,i.enc=e,i.parent=t||null,i.children=null,i.tag=null,i.args=null,i.reverseArgs=null,i.choice=null,i.optional=!1,i.any=!1,i.obj=!1,i.use=null,i.useDecoder=null,i.key=null,i.default=null,i.explicit=null,i.implicit=null,i.contains=null,i.parent||(i.children=[],this._wrap())}t.exports=u;let c=["enc","parent","children","tag","args","reverseArgs","choice","optional","any","obj","use","alteredUse","key","default","explicit","implicit","contains"];u.prototype.clone=function(){let e=this._baseState,t={};c.forEach(function(r){t[r]=e[r]});let r=new this.constructor(t.parent);return r._baseState=t,r},u.prototype._wrap=function(){let e=this._baseState;l.forEach(function(t){this[t]=function(){let r=new this.constructor(this);return e.children.push(r),r[t].apply(r,arguments)}},this)},u.prototype._init=function(e){let t=this._baseState;s(null===t.parent),e.call(this),t.children=t.children.filter(function(e){return e._baseState.parent===this},this),s.equal(t.children.length,1,"Root node can have only one child")},u.prototype._useArgs=function(e){let t=this._baseState,r=e.filter(function(e){return e instanceof this.constructor},this);e=e.filter(function(e){return!(e instanceof this.constructor)},this),0!==r.length&&(s(null===t.children),t.children=r,r.forEach(function(e){e._baseState.parent=this},this)),0!==e.length&&(s(null===t.args),t.args=e,t.reverseArgs=e.map(function(e){if("object"!=typeof e||e.constructor!==Object)return e;let t={};return Object.keys(e).forEach(function(r){r==(0|r)&&(r|=0),t[e[r]]=r}),t}))},["_peekTag","_decodeTag","_use","_decodeStr","_decodeObjid","_decodeTime","_decodeNull","_decodeInt","_decodeBool","_decodeList","_encodeComposite","_encodeStr","_encodeObjid","_encodeTime","_encodeNull","_encodeInt","_encodeBool"].forEach(function(e){u.prototype[e]=function(){throw Error(e+" not implemented for encoding: "+this._baseState.enc)}}),o.forEach(function(e){u.prototype[e]=function(){let t=this._baseState,r=Array.prototype.slice.call(arguments);return s(null===t.tag),t.tag=e,this._useArgs(r),this}}),u.prototype.use=function(e){s(e);let t=this._baseState;return s(null===t.use),t.use=e,this},u.prototype.optional=function(){return this._baseState.optional=!0,this},u.prototype.def=function(e){let t=this._baseState;return s(null===t.default),t.default=e,t.optional=!0,this},u.prototype.explicit=function(e){let t=this._baseState;return s(null===t.explicit&&null===t.implicit),t.explicit=e,this},u.prototype.implicit=function(e){let t=this._baseState;return s(null===t.explicit&&null===t.implicit),t.implicit=e,this},u.prototype.obj=function(){let e=this._baseState,t=Array.prototype.slice.call(arguments);return e.obj=!0,0!==t.length&&this._useArgs(t),this},u.prototype.key=function(e){let t=this._baseState;return s(null===t.key),t.key=e,this},u.prototype.any=function(){return this._baseState.any=!0,this},u.prototype.choice=function(e){let t=this._baseState;return s(null===t.choice),t.choice=e,this._useArgs(Object.keys(e).map(function(t){return e[t]})),this},u.prototype.contains=function(e){let t=this._baseState;return s(null===t.use),t.contains=e,this},u.prototype._decode=function(e,t){let r,i=this._baseState;if(null===i.parent)return e.wrapResult(i.children[0]._decode(e,t));let a=i.default,s=!0,o=null;if(null!==i.key&&(o=e.enterKey(i.key)),i.optional){let r=null;if(null!==i.explicit?r=i.explicit:null!==i.implicit?r=i.implicit:null!==i.tag&&(r=i.tag),null!==r||i.any){if(s=this._peekTag(e,r,i.any),e.isError(s))return s}else{let r=e.save();try{null===i.choice?this._decodeGeneric(i.tag,e,t):this._decodeChoice(e,t),s=!0}catch(e){s=!1}e.restore(r)}}if(i.obj&&s&&(r=e.enterObject()),s){if(null!==i.explicit){let t=this._decodeTag(e,i.explicit);if(e.isError(t))return t;e=t}let r=e.offset;if(null===i.use&&null===i.choice){let t;i.any&&(t=e.save());let r=this._decodeTag(e,null!==i.implicit?i.implicit:i.tag,i.any);if(e.isError(r))return r;i.any?a=e.raw(t):e=r}if(t&&t.track&&null!==i.tag&&t.track(e.path(),r,e.length,"tagged"),t&&t.track&&null!==i.tag&&t.track(e.path(),e.offset,e.length,"content"),i.any||(a=null===i.choice?this._decodeGeneric(i.tag,e,t):this._decodeChoice(e,t)),e.isError(a))return a;if(i.any||null!==i.choice||null===i.children||i.children.forEach(function(r){r._decode(e,t)}),i.contains&&("octstr"===i.tag||"bitstr"===i.tag)){let r=new n(a);a=this._getUse(i.contains,e._reporterState.obj)._decode(r,t)}}return i.obj&&s&&(a=e.leaveObject(r)),null!==i.key&&(null!==a||!0===s)?e.leaveKey(o,i.key,a):null!==o&&e.exitKey(o),a},u.prototype._decodeGeneric=function(e,t,r){let i=this._baseState;if("seq"===e||"set"===e)return null;if("seqof"===e||"setof"===e)return this._decodeList(t,e,i.args[0],r);if(/str$/.test(e))return this._decodeStr(t,e,r);if("objid"===e&&i.args)return this._decodeObjid(t,i.args[0],i.args[1],r);if("objid"===e)return this._decodeObjid(t,null,null,r);if("gentime"===e||"utctime"===e)return this._decodeTime(t,e,r);else if("null_"===e)return this._decodeNull(t,r);else if("bool"===e)return this._decodeBool(t,r);else if("objDesc"===e)return this._decodeStr(t,e,r);else if("int"===e||"enum"===e)return this._decodeInt(t,i.args&&i.args[0],r);return null!==i.use?this._getUse(i.use,t._reporterState.obj)._decode(t,r):t.error("unknown tag: "+e)},u.prototype._getUse=function(e,t){let r=this._baseState;return r.useDecoder=this._use(e,t),s(null===r.useDecoder._baseState.parent),r.useDecoder=r.useDecoder._baseState.children[0],r.implicit!==r.useDecoder._baseState.implicit&&(r.useDecoder=r.useDecoder.clone(),r.useDecoder._baseState.implicit=r.implicit),r.useDecoder},u.prototype._decodeChoice=function(e,t){let r=this._baseState,i=null,a=!1;return(Object.keys(r.choice).some(function(n){let s=e.save(),o=r.choice[n];try{let r=o._decode(e,t);if(e.isError(r))return!1;i={type:n,value:r},a=!0}catch(t){return e.restore(s),!1}return!0},this),a)?i:e.error("Choice not matched")},u.prototype._createEncoderBuffer=function(e){return new a(e,this.reporter)},u.prototype._encode=function(e,t,r){let i=this._baseState;if(null!==i.default&&i.default===e)return;let a=this._encodeValue(e,t,r);if(void 0!==a&&!this._skipDefault(a,t,r))return a},u.prototype._encodeValue=function(e,t,r){let a=this._baseState;if(null===a.parent)return a.children[0]._encode(e,t||new i);let n=null;if(this.reporter=t,a.optional&&void 0===e)if(null===a.default)return;else e=a.default;let s=null,o=!1;if(a.any)n=this._createEncoderBuffer(e);else if(a.choice)n=this._encodeChoice(e,t);else if(a.contains)s=this._getUse(a.contains,r)._encode(e,t),o=!0;else if(a.children)s=a.children.map(function(r){if("null_"===r._baseState.tag)return r._encode(null,t,e);if(null===r._baseState.key)return t.error("Child should have a key");let i=t.enterKey(r._baseState.key);if("object"!=typeof e)return t.error("Child expected, but input is not object");let a=r._encode(e[r._baseState.key],t,e);return t.leaveKey(i),a},this).filter(function(e){return e}),s=this._createEncoderBuffer(s);else if("seqof"===a.tag||"setof"===a.tag){if(!(a.args&&1===a.args.length))return t.error("Too many args for : "+a.tag);if(!Array.isArray(e))return t.error("seqof/setof, but data is not Array");let r=this.clone();r._baseState.implicit=null,s=this._createEncoderBuffer(e.map(function(r){let i=this._baseState;return this._getUse(i.args[0],e)._encode(r,t)},r))}else null!==a.use?n=this._getUse(a.use,r)._encode(e,t):(s=this._encodePrimitive(a.tag,e),o=!0);if(!a.any&&null===a.choice){let e=null!==a.implicit?a.implicit:a.tag,r=null===a.implicit?"universal":"context";null===e?null===a.use&&t.error("Tag could be omitted only for .use()"):null===a.use&&(n=this._encodeComposite(e,o,r,s))}return null!==a.explicit&&(n=this._encodeComposite(a.explicit,!1,"context",n)),n},u.prototype._encodeChoice=function(e,t){let r=this._baseState,i=r.choice[e.type];return i||s(!1,e.type+" not found in "+JSON.stringify(Object.keys(r.choice))),i._encode(e.value,t)},u.prototype._encodePrimitive=function(e,t){let r=this._baseState;if(/str$/.test(e))return this._encodeStr(t,e);if("objid"===e&&r.args)return this._encodeObjid(t,r.reverseArgs[0],r.args[1]);if("objid"===e)return this._encodeObjid(t,null,null);if("gentime"===e||"utctime"===e)return this._encodeTime(t,e);if("null_"===e)return this._encodeNull();else if("int"===e||"enum"===e)return this._encodeInt(t,r.args&&r.reverseArgs[0]);else if("bool"===e)return this._encodeBool(t);else if("objDesc"===e)return this._encodeStr(t,e);else throw Error("Unsupported tag: "+e)},u.prototype._isNumstr=function(e){return/^[0-9 ]*$/.test(e)},u.prototype._isPrintstr=function(e){return/^[A-Za-z0-9 '()+,-./:=?]*$/.test(e)}},433689,(e,t,r)=>{"use strict";function i(e){let t={};return Object.keys(e).forEach(function(r){(0|r)==r&&(r|=0),t[e[r]]=r}),t}r.tagClass={0:"universal",1:"application",2:"context",3:"private"},r.tagClassByName=i(r.tagClass),r.tag={0:"end",1:"bool",2:"int",3:"bitstr",4:"octstr",5:"null_",6:"objid",7:"objDesc",8:"external",9:"real",10:"enum",11:"embed",12:"utf8str",13:"relativeOid",16:"seq",17:"set",18:"numstr",19:"printstr",20:"t61str",21:"videostr",22:"ia5str",23:"utctime",24:"gentime",25:"graphstr",26:"iso646str",27:"genstr",28:"unistr",29:"charstr",30:"bmpstr"},r.tagByName=i(r.tag)},970738,(e,t,r)=>{"use strict";let i=e.r(966397),a=e.r(832623).Buffer,n=e.r(524283),s=e.r(433689);function o(e){this.enc="der",this.name=e.name,this.entity=e,this.tree=new l,this.tree._init(e.body)}function l(e){n.call(this,"der",e)}function u(e){return e<10?"0"+e:e}t.exports=o,o.prototype.encode=function(e,t){return this.tree._encode(e,t).join()},i(l,n),l.prototype._encodeComposite=function(e,t,r,i){let n=function(e,t,r,i){let a;if("seqof"===e?e="seq":"setof"===e&&(e="set"),s.tagByName.hasOwnProperty(e))a=s.tagByName[e];else{if("number"!=typeof e||(0|e)!==e)return i.error("Unknown tag: "+e);a=e}return a>=31?i.error("Multi-octet tag encoding unsupported"):(t||(a|=32),a|=s.tagClassByName[r||"universal"]<<6)}(e,t,r,this.reporter);if(i.length<128){let e=a.alloc(2);return e[0]=n,e[1]=i.length,this._createEncoderBuffer([e,i])}let o=1;for(let e=i.length;e>=256;e>>=8)o++;let l=a.alloc(2+o);l[0]=n,l[1]=128|o;for(let e=1+o,t=i.length;t>0;e--,t>>=8)l[e]=255&t;return this._createEncoderBuffer([l,i])},l.prototype._encodeStr=function(e,t){if("bitstr"===t)return this._createEncoderBuffer([0|e.unused,e.data]);if("bmpstr"===t){let t=a.alloc(2*e.length);for(let r=0;r<e.length;r++)t.writeUInt16BE(e.charCodeAt(r),2*r);return this._createEncoderBuffer(t)}if("numstr"===t)return this._isNumstr(e)?this._createEncoderBuffer(e):this.reporter.error("Encoding of string type: numstr supports only digits and space");if("printstr"===t)return this._isPrintstr(e)?this._createEncoderBuffer(e):this.reporter.error("Encoding of string type: printstr supports only latin upper and lower case letters, digits, space, apostrophe, left and rigth parenthesis, plus sign, comma, hyphen, dot, slash, colon, equal sign, question mark");if(/str$/.test(t))return this._createEncoderBuffer(e);else if("objDesc"===t)return this._createEncoderBuffer(e);else return this.reporter.error("Encoding of string type: "+t+" unsupported")},l.prototype._encodeObjid=function(e,t,r){if("string"==typeof e){if(!t)return this.reporter.error("string objid given, but no values map found");if(!t.hasOwnProperty(e))return this.reporter.error("objid not found in values map");e=t[e].split(/[\s.]+/g);for(let t=0;t<e.length;t++)e[t]|=0}else if(Array.isArray(e)){e=e.slice();for(let t=0;t<e.length;t++)e[t]|=0}if(!Array.isArray(e))return this.reporter.error("objid() should be either array or string, got: "+JSON.stringify(e));if(!r){if(e[1]>=40)return this.reporter.error("Second objid identifier OOB");e.splice(0,2,40*e[0]+e[1])}let i=0;for(let t=0;t<e.length;t++){let r=e[t];for(i++;r>=128;r>>=7)i++}let n=a.alloc(i),s=n.length-1;for(let t=e.length-1;t>=0;t--){let r=e[t];for(n[s--]=127&r;(r>>=7)>0;)n[s--]=128|127&r}return this._createEncoderBuffer(n)},l.prototype._encodeTime=function(e,t){let r,i=new Date(e);return"gentime"===t?r=[u(i.getUTCFullYear()),u(i.getUTCMonth()+1),u(i.getUTCDate()),u(i.getUTCHours()),u(i.getUTCMinutes()),u(i.getUTCSeconds()),"Z"].join(""):"utctime"===t?r=[u(i.getUTCFullYear()%100),u(i.getUTCMonth()+1),u(i.getUTCDate()),u(i.getUTCHours()),u(i.getUTCMinutes()),u(i.getUTCSeconds()),"Z"].join(""):this.reporter.error("Encoding "+t+" time is not supported yet"),this._encodeStr(r,"octstr")},l.prototype._encodeNull=function(){return this._createEncoderBuffer("")},l.prototype._encodeInt=function(e,t){if("string"==typeof e){if(!t)return this.reporter.error("String int or enum given, but no values map");if(!t.hasOwnProperty(e))return this.reporter.error("Values map doesn't contain: "+JSON.stringify(e));e=t[e]}if("number"!=typeof e&&!a.isBuffer(e)){let t=e.toArray();!e.sign&&128&t[0]&&t.unshift(0),e=a.from(t)}if(a.isBuffer(e)){let t=e.length;0===e.length&&t++;let r=a.alloc(t);return e.copy(r),0===e.length&&(r[0]=0),this._createEncoderBuffer(r)}if(e<128)return this._createEncoderBuffer(e);if(e<256)return this._createEncoderBuffer([0,e]);let r=1;for(let t=e;t>=256;t>>=8)r++;let i=Array(r);for(let t=i.length-1;t>=0;t--)i[t]=255&e,e>>=8;return 128&i[0]&&i.unshift(0),this._createEncoderBuffer(a.from(i))},l.prototype._encodeBool=function(e){return this._createEncoderBuffer(255*!!e)},l.prototype._use=function(e,t){return"function"==typeof e&&(e=e(t)),e._getEncoder("der").tree},l.prototype._skipDefault=function(e,t,r){let i,a=this._baseState;if(null===a.default)return!1;let n=e.join();if(void 0===a.defaultBuffer&&(a.defaultBuffer=this._encodeValue(a.default,t,r).join()),n.length!==a.defaultBuffer.length)return!1;for(i=0;i<n.length;i++)if(n[i]!==a.defaultBuffer[i])return!1;return!0}},671153,(e,t,r)=>{"use strict";let i=e.r(966397),a=e.r(970738);function n(e){a.call(this,e),this.enc="pem"}i(n,a),t.exports=n,n.prototype.encode=function(e,t){let r=a.prototype.encode.call(this,e).toString("base64"),i=["-----BEGIN "+t.label+"-----"];for(let e=0;e<r.length;e+=64)i.push(r.slice(e,e+64));return i.push("-----END "+t.label+"-----"),i.join("\n")}},642134,(e,t,r)=>{"use strict";r.der=e.r(970738),r.pem=e.r(671153)},229677,(e,t,r)=>{"use strict";let i=e.r(966397),a=e.r(917397),n=e.r(644833).DecoderBuffer,s=e.r(524283),o=e.r(433689);function l(e){this.enc="der",this.name=e.name,this.entity=e,this.tree=new u,this.tree._init(e.body)}function u(e){s.call(this,"der",e)}function c(e,t){let r=e.readUInt8(t);if(e.isError(r))return r;let i=o.tagClass[r>>6],a=(32&r)==0;if((31&r)==31){let i=r;for(r=0;(128&i)==128;){if(i=e.readUInt8(t),e.isError(i))return i;r<<=7,r|=127&i}}else r&=31;let n=o.tag[r];return{cls:i,primitive:a,tag:r,tagStr:n}}function d(e,t,r){let i=e.readUInt8(r);if(e.isError(i))return i;if(!t&&128===i)return null;if((128&i)==0)return i;let a=127&i;if(a>4)return e.error("length octect is too long");i=0;for(let t=0;t<a;t++){i<<=8;let t=e.readUInt8(r);if(e.isError(t))return t;i|=t}return i}t.exports=l,l.prototype.decode=function(e,t){return n.isDecoderBuffer(e)||(e=new n(e,t)),this.tree._decode(e,t)},i(u,s),u.prototype._peekTag=function(e,t,r){if(e.isEmpty())return!1;let i=e.save(),a=c(e,'Failed to peek tag: "'+t+'"');return e.isError(a)?a:(e.restore(i),a.tag===t||a.tagStr===t||a.tagStr+"of"===t||r)},u.prototype._decodeTag=function(e,t,r){let i=c(e,'Failed to decode tag of "'+t+'"');if(e.isError(i))return i;let a=d(e,i.primitive,'Failed to get length of "'+t+'"');if(e.isError(a))return a;if(!r&&i.tag!==t&&i.tagStr!==t&&i.tagStr+"of"!==t)return e.error('Failed to match tag: "'+t+'"');if(i.primitive||null!==a)return e.skip(a,'Failed to match body of: "'+t+'"');let n=e.save(),s=this._skipUntilEnd(e,'Failed to skip indefinite length body: "'+this.tag+'"');return e.isError(s)?s:(a=e.offset-n.offset,e.restore(n),e.skip(a,'Failed to match body of: "'+t+'"'))},u.prototype._skipUntilEnd=function(e,t){for(;;){let r,i=c(e,t);if(e.isError(i))return i;let a=d(e,i.primitive,t);if(e.isError(a))return a;if(r=i.primitive||null!==a?e.skip(a):this._skipUntilEnd(e,t),e.isError(r))return r;if("end"===i.tagStr)break}},u.prototype._decodeList=function(e,t,r,i){let a=[];for(;!e.isEmpty();){let t=this._peekTag(e,"end");if(e.isError(t))return t;let n=r.decode(e,"der",i);if(e.isError(n)&&t)break;a.push(n)}return a},u.prototype._decodeStr=function(e,t){if("bitstr"===t){let t=e.readUInt8();return e.isError(t)?t:{unused:t,data:e.raw()}}if("bmpstr"===t){let t=e.raw();if(t.length%2==1)return e.error("Decoding of string type: bmpstr length mismatch");let r="";for(let e=0;e<t.length/2;e++)r+=String.fromCharCode(t.readUInt16BE(2*e));return r}if("numstr"===t){let t=e.raw().toString("ascii");return this._isNumstr(t)?t:e.error("Decoding of string type: numstr unsupported characters")}if("octstr"===t)return e.raw();if("objDesc"===t)return e.raw();else if("printstr"===t){let t=e.raw().toString("ascii");return this._isPrintstr(t)?t:e.error("Decoding of string type: printstr unsupported characters")}else if(/str$/.test(t))return e.raw().toString();else return e.error("Decoding of string type: "+t+" unsupported")},u.prototype._decodeObjid=function(e,t,r){let i,a=[],n=0,s=0;for(;!e.isEmpty();)s=e.readUInt8(),n<<=7,n|=127&s,(128&s)==0&&(a.push(n),n=0);128&s&&a.push(n);let o=a[0]/40|0,l=a[0]%40;if(i=r?a:[o,l].concat(a.slice(1)),t){let e=t[i.join(" ")];void 0===e&&(e=t[i.join(".")]),void 0!==e&&(i=e)}return i},u.prototype._decodeTime=function(e,t){let r,i,a,n,s,o,l=e.raw().toString();if("gentime"===t)r=0|l.slice(0,4),i=0|l.slice(4,6),a=0|l.slice(6,8),n=0|l.slice(8,10),s=0|l.slice(10,12),o=0|l.slice(12,14);else{if("utctime"!==t)return e.error("Decoding "+t+" time is not supported yet");r=0|l.slice(0,2),i=0|l.slice(2,4),a=0|l.slice(4,6),n=0|l.slice(6,8),s=0|l.slice(8,10),o=0|l.slice(10,12),r=r<70?2e3+r:1900+r}return Date.UTC(r,i-1,a,n,s,o,0)},u.prototype._decodeNull=function(){return null},u.prototype._decodeBool=function(e){let t=e.readUInt8();return e.isError(t)?t:0!==t},u.prototype._decodeInt=function(e,t){let r=new a(e.raw());return t&&(r=t[r.toString(10)]||r),r},u.prototype._use=function(e,t){return"function"==typeof e&&(e=e(t)),e._getDecoder("der").tree}},594334,(e,t,r)=>{"use strict";let i=e.r(966397),a=e.r(832623).Buffer,n=e.r(229677);function s(e){n.call(this,e),this.enc="pem"}i(s,n),t.exports=s,s.prototype.decode=function(e,t){let r=e.toString().split(/[\r\n]+/g),i=t.label.toUpperCase(),s=/^-----(BEGIN|END) ([^-]+)-----$/,o=-1,l=-1;for(let e=0;e<r.length;e++){let t=r[e].match(s);if(null!==t&&t[2]===i)if(-1===o){if("BEGIN"!==t[1])break;o=e}else{if("END"!==t[1])break;l=e;break}}if(-1===o||-1===l)throw Error("PEM section not found for: "+i);let u=r.slice(o+1,l).join("");u.replace(/[^a-z0-9+/=]+/gi,"");let c=a.from(u,"base64");return n.prototype.decode.call(this,c,t)}},88855,(e,t,r)=>{"use strict";r.der=e.r(229677),r.pem=e.r(594334)},181713,(e,t,r)=>{"use strict";let i=e.r(642134),a=e.r(88855),n=e.r(966397);function s(e,t){this.name=e,this.body=t,this.decoders={},this.encoders={}}r.define=function(e,t){return new s(e,t)},s.prototype._createNamed=function(e){let t=this.name;function r(e){this._initNamed(e,t)}return n(r,e),r.prototype._initNamed=function(t,r){e.call(this,t,r)},new r(this)},s.prototype._getDecoder=function(e){return e=e||"der",this.decoders.hasOwnProperty(e)||(this.decoders[e]=this._createNamed(a[e])),this.decoders[e]},s.prototype.decode=function(e,t,r){return this._getDecoder(t).decode(e,r)},s.prototype._getEncoder=function(e){return e=e||"der",this.encoders.hasOwnProperty(e)||(this.encoders[e]=this._createNamed(i[e])),this.encoders[e]},s.prototype.encode=function(e,t,r){return this._getEncoder(t).encode(e,r)}},356767,(e,t,r)=>{"use strict";r.Reporter=e.r(857406).Reporter,r.DecoderBuffer=e.r(644833).DecoderBuffer,r.EncoderBuffer=e.r(644833).EncoderBuffer,r.Node=e.r(524283)},434299,(e,t,r)=>{"use strict";r._reverse=function(e){let t={};return Object.keys(e).forEach(function(r){(0|r)==r&&(r|=0),t[e[r]]=r}),t},r.der=e.r(433689)},572257,(e,t,r)=>{"use strict";r.bignum=e.r(917397),r.define=e.r(181713).define,r.base=e.r(356767),r.constants=e.r(434299),r.decoders=e.r(88855),r.encoders=e.r(642134)},779430,e=>{"use strict";var t=function(e,r){return(t=Object.setPrototypeOf||({__proto__:[]})instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])})(e,r)};function r(e,r){if("function"!=typeof r&&null!==r)throw TypeError("Class extends value "+String(r)+" is not a constructor or null");function i(){this.constructor=e}t(e,r),e.prototype=null===r?Object.create(r):(i.prototype=r.prototype,new i)}var i=function(){return(i=Object.assign||function(e){for(var t,r=1,i=arguments.length;r<i;r++)for(var a in t=arguments[r])Object.prototype.hasOwnProperty.call(t,a)&&(e[a]=t[a]);return e}).apply(this,arguments)};function a(e,t){var r={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&0>t.indexOf(i)&&(r[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var a=0,i=Object.getOwnPropertySymbols(e);a<i.length;a++)0>t.indexOf(i[a])&&Object.prototype.propertyIsEnumerable.call(e,i[a])&&(r[i[a]]=e[i[a]]);return r}function n(e,t,r,i){var a,n=arguments.length,s=n<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,r,i);else for(var o=e.length-1;o>=0;o--)(a=e[o])&&(s=(n<3?a(s):n>3?a(t,r,s):a(t,r))||s);return n>3&&s&&Object.defineProperty(t,r,s),s}function s(e,t){return function(r,i){t(r,i,e)}}function o(e,t,r,i,a,n){function s(e){if(void 0!==e&&"function"!=typeof e)throw TypeError("Function expected");return e}for(var o,l=i.kind,u="getter"===l?"get":"setter"===l?"set":"value",c=!t&&e?i.static?e:e.prototype:null,d=t||(c?Object.getOwnPropertyDescriptor(c,i.name):{}),h=!1,p=r.length-1;p>=0;p--){var m={};for(var f in i)m[f]="access"===f?{}:i[f];for(var f in i.access)m.access[f]=i.access[f];m.addInitializer=function(e){if(h)throw TypeError("Cannot add initializers after decoration has completed");n.push(s(e||null))};var g=(0,r[p])("accessor"===l?{get:d.get,set:d.set}:d[u],m);if("accessor"===l){if(void 0===g)continue;if(null===g||"object"!=typeof g)throw TypeError("Object expected");(o=s(g.get))&&(d.get=o),(o=s(g.set))&&(d.set=o),(o=s(g.init))&&a.unshift(o)}else(o=s(g))&&("field"===l?a.unshift(o):d[u]=o)}c&&Object.defineProperty(c,i.name,d),h=!0}function l(e,t,r){for(var i=arguments.length>2,a=0;a<t.length;a++)r=i?t[a].call(e,r):t[a].call(e);return i?r:void 0}function u(e){return"symbol"==typeof e?e:"".concat(e)}function c(e,t,r){return"symbol"==typeof t&&(t=t.description?"[".concat(t.description,"]"):""),Object.defineProperty(e,"name",{configurable:!0,value:r?"".concat(r," ",t):t})}function d(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function h(e,t,r,i){return new(r||(r=Promise))(function(a,n){function s(e){try{l(i.next(e))}catch(e){n(e)}}function o(e){try{l(i.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?a(e.value):((t=e.value)instanceof r?t:new r(function(e){e(t)})).then(s,o)}l((i=i.apply(e,t||[])).next())})}function p(e,t){var r,i,a,n={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},s=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return s.next=o(0),s.throw=o(1),s.return=o(2),"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function o(o){return function(l){var u=[o,l];if(r)throw TypeError("Generator is already executing.");for(;s&&(s=0,u[0]&&(n=0)),n;)try{if(r=1,i&&(a=2&u[0]?i.return:u[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,u[1])).done)return a;switch(i=0,a&&(u=[2&u[0],a.value]),u[0]){case 0:case 1:a=u;break;case 4:return n.label++,{value:u[1],done:!1};case 5:n.label++,i=u[1],u=[0];continue;case 7:u=n.ops.pop(),n.trys.pop();continue;default:if(!(a=(a=n.trys).length>0&&a[a.length-1])&&(6===u[0]||2===u[0])){n=0;continue}if(3===u[0]&&(!a||u[1]>a[0]&&u[1]<a[3])){n.label=u[1];break}if(6===u[0]&&n.label<a[1]){n.label=a[1],a=u;break}if(a&&n.label<a[2]){n.label=a[2],n.ops.push(u);break}a[2]&&n.ops.pop(),n.trys.pop();continue}u=t.call(e,n)}catch(e){u=[6,e],i=0}finally{r=a=0}if(5&u[0])throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}}var m=Object.create?function(e,t,r,i){void 0===i&&(i=r);var a=Object.getOwnPropertyDescriptor(t,r);(!a||("get"in a?!t.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,a)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]};function f(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||m(t,e,r)}function g(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],i=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&i>=e.length&&(e=void 0),{value:e&&e[i++],done:!e}}};throw TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function y(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var i,a,n=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(i=n.next()).done;)s.push(i.value)}catch(e){a={error:e}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return s}function w(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(y(arguments[t]));return e}function b(){for(var e=0,t=0,r=arguments.length;t<r;t++)e+=arguments[t].length;for(var i=Array(e),a=0,t=0;t<r;t++)for(var n=arguments[t],s=0,o=n.length;s<o;s++,a++)i[a]=n[s];return i}function E(e,t,r){if(r||2==arguments.length)for(var i,a=0,n=t.length;a<n;a++)!i&&a in t||(i||(i=Array.prototype.slice.call(t,0,a)),i[a]=t[a]);return e.concat(i||Array.prototype.slice.call(t))}function S(e){return this instanceof S?(this.v=e,this):new S(e)}function v(e,t,r){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var i,a=r.apply(e,t||[]),n=[];return i=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),s("next"),s("throw"),s("return",function(e){return function(t){return Promise.resolve(t).then(e,u)}}),i[Symbol.asyncIterator]=function(){return this},i;function s(e,t){a[e]&&(i[e]=function(t){return new Promise(function(r,i){n.push([e,t,r,i])>1||o(e,t)})},t&&(i[e]=t(i[e])))}function o(e,t){try{var r;(r=a[e](t)).value instanceof S?Promise.resolve(r.value.v).then(l,u):c(n[0][2],r)}catch(e){c(n[0][3],e)}}function l(e){o("next",e)}function u(e){o("throw",e)}function c(e,t){e(t),n.shift(),n.length&&o(n[0][0],n[0][1])}}function I(e){var t,r;return t={},i("next"),i("throw",function(e){throw e}),i("return"),t[Symbol.iterator]=function(){return this},t;function i(i,a){t[i]=e[i]?function(t){return(r=!r)?{value:S(e[i](t)),done:!1}:a?a(t):t}:a}}function A(e){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e=g(e),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(r){t[r]=e[r]&&function(t){return new Promise(function(i,a){var n,s,o;n=i,s=a,o=(t=e[r](t)).done,Promise.resolve(t.value).then(function(e){n({value:e,done:o})},s)})}}}function k(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e}var _=Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t},T=function(e){return(T=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t})(e)};function C(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=T(e),i=0;i<r.length;i++)"default"!==r[i]&&m(t,e,r[i]);return _(t,e),t}function R(e){return e&&e.__esModule?e:{default:e}}function N(e,t,r,i){if("a"===r&&!i)throw TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)}function O(e,t,r,i,a){if("m"===i)throw TypeError("Private method is not writable");if("a"===i&&!a)throw TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!a:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?a.call(e,r):a?a.value=r:t.set(e,r),r}function D(e,t){if(null===t||"object"!=typeof t&&"function"!=typeof t)throw TypeError("Cannot use 'in' operator on non-object");return"function"==typeof e?t===e:e.has(t)}function P(e,t,r){if(null!=t){var i,a;if("object"!=typeof t&&"function"!=typeof t)throw TypeError("Object expected.");if(r){if(!Symbol.asyncDispose)throw TypeError("Symbol.asyncDispose is not defined.");i=t[Symbol.asyncDispose]}if(void 0===i){if(!Symbol.dispose)throw TypeError("Symbol.dispose is not defined.");i=t[Symbol.dispose],r&&(a=i)}if("function"!=typeof i)throw TypeError("Object not disposable.");a&&(i=function(){try{a.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:i,async:r})}else r&&e.stack.push({async:!0});return t}var x="function"==typeof SuppressedError?SuppressedError:function(e,t,r){var i=Error(r);return i.name="SuppressedError",i.error=e,i.suppressed=t,i};function L(e){function t(t){e.error=e.hasError?new x(t,e.error,"An error was suppressed during disposal."):t,e.hasError=!0}var r,i=0;return function a(){for(;r=e.stack.pop();)try{if(!r.async&&1===i)return i=0,e.stack.push(r),Promise.resolve().then(a);if(r.dispose){var n=r.dispose.call(r.value);if(r.async)return i|=2,Promise.resolve(n).then(a,function(e){return t(e),a()})}else i|=1}catch(e){t(e)}if(1===i)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}()}function U(e,t){return"string"==typeof e&&/^\.\.?\//.test(e)?e.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(e,r,i,a,n){return r?t?".jsx":".js":!i||a&&n?i+a+"."+n.toLowerCase()+"js":e}):e}let B={__extends:r,__assign:i,__rest:a,__decorate:n,__param:s,__esDecorate:o,__runInitializers:l,__propKey:u,__setFunctionName:c,__metadata:d,__awaiter:h,__generator:p,__createBinding:m,__exportStar:f,__values:g,__read:y,__spread:w,__spreadArrays:b,__spreadArray:E,__await:S,__asyncGenerator:v,__asyncDelegator:I,__asyncValues:A,__makeTemplateObject:k,__importStar:C,__importDefault:R,__classPrivateFieldGet:N,__classPrivateFieldSet:O,__classPrivateFieldIn:D,__addDisposableResource:P,__disposeResources:L,__rewriteRelativeImportExtension:U};e.s(["__addDisposableResource",0,P,"__assign",()=>i,"__asyncDelegator",0,I,"__asyncGenerator",0,v,"__asyncValues",0,A,"__await",0,S,"__awaiter",0,h,"__classPrivateFieldGet",0,N,"__classPrivateFieldIn",0,D,"__classPrivateFieldSet",0,O,"__createBinding",0,m,"__decorate",0,n,"__disposeResources",0,L,"__esDecorate",0,o,"__exportStar",0,f,"__extends",0,r,"__generator",0,p,"__importDefault",0,R,"__importStar",0,C,"__makeTemplateObject",0,k,"__metadata",0,d,"__param",0,s,"__propKey",0,u,"__read",0,y,"__rest",0,a,"__rewriteRelativeImportExtension",0,U,"__runInitializers",0,l,"__setFunctionName",0,c,"__spread",0,w,"__spreadArray",0,E,"__spreadArrays",0,b,"__values",0,g,"default",0,B])},162232,(e,t,r)=>{"use strict";let i={};i.supportedContentEncodings={AES_GCM:"aesgcm",AES_128_GCM:"aes128gcm"},i.supportedUrgency={VERY_LOW:"very-low",LOW:"low",NORMAL:"normal",HIGH:"high"},t.exports=i},341220,(e,t,r)=>{"use strict";t.exports={validate:function(e){return/^[A-Za-z0-9\-_]+$/.test(e)}}},114916,(e,t,r)=>{"use strict";let i=e.r(254799),a=e.r(572257),n=e.r(258184),{URL:s}=e.r(792509),o=e.r(162232),l=e.r(341220),u=a.define("ECPrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("privateKey").octstr(),this.key("parameters").explicit(0).objid().optional(),this.key("publicKey").explicit(1).bitstr().optional())});function c(e){if(!e)throw Error("No subject set in vapidDetails.subject.");if("string"!=typeof e||0===e.length)throw Error("The subject value must be a string containing an https: URL or mailto: address. "+e);let t=null;try{t=new s(e)}catch(t){throw Error("Vapid subject is not a valid URL. "+e)}if(!["https:","mailto:"].includes(t.protocol))throw Error("Vapid subject is not an https: or mailto: URL. "+e);"localhost"===t.hostname&&console.warn("Vapid subject points to a localhost web URI, which is unsupported by Apple's push notification server and will result in a BadJwtToken error when sending notifications.")}function d(e){if(!e)throw Error("No key set vapidDetails.publicKey");if("string"!=typeof e)throw Error("Vapid public key is must be a URL safe Base 64 encoded string.");if(!l.validate(e))throw Error('Vapid public key must be a URL safe Base 64 (without "=")');if(65!==(e=Buffer.from(e,"base64url")).length)throw Error("Vapid public key should be 65 bytes long when decoded.")}function h(e){if(!e)throw Error("No key set in vapidDetails.privateKey");if("string"!=typeof e)throw Error("Vapid private key must be a URL safe Base 64 encoded string.");if(!l.validate(e))throw Error('Vapid private key must be a URL safe Base 64 (without "=")');if(32!==(e=Buffer.from(e,"base64url")).length)throw Error("Vapid private key should be 32 bytes long when decoded.")}function p(e){let t=new Date;return t.setSeconds(t.getSeconds()+e),Math.floor(t.getTime()/1e3)}function m(e){if(!Number.isInteger(e))throw Error("`expiration` value must be a number");if(e<0)throw Error("`expiration` must be a positive integer");if(e>=p(86400))throw Error("`expiration` value is greater than maximum of 24 hours")}t.exports={generateVAPIDKeys:function(){let e=i.createECDH("prime256v1");e.generateKeys();let t=e.getPublicKey(),r=e.getPrivateKey();if(r.length<32){let e=Buffer.alloc(32-r.length);e.fill(0),r=Buffer.concat([e,r])}if(t.length<65){let e=Buffer.alloc(65-t.length);e.fill(0),t=Buffer.concat([e,t])}return{publicKey:t.toString("base64url"),privateKey:r.toString("base64url")}},getFutureExpirationTimestamp:p,getVapidHeaders:function(e,t,r,i,a,l){var f;if(!e)throw Error("No audience could be generated for VAPID.");if("string"!=typeof e||0===e.length)throw Error("The audience value must be a string containing the origin of a push service. "+e);try{new s(e)}catch(t){throw Error("VAPID audience is not a url. "+e)}c(t),d(r),h(i),i=Buffer.from(i,"base64url"),l?m(l):l=p(43200);let g={aud:e,exp:l,sub:t},y=n.sign({header:{typ:"JWT",alg:"ES256"},payload:g,privateKey:(f=i,u.encode({version:1,privateKey:f,parameters:[1,2,840,10045,3,1,7]},"pem",{label:"EC PRIVATE KEY"}))});if(a===o.supportedContentEncodings.AES_128_GCM)return{Authorization:"vapid t="+y+", k="+r};if(a===o.supportedContentEncodings.AES_GCM)return{Authorization:"WebPush "+y,"Crypto-Key":"p256ecdsa="+r};throw Error("Unsupported encoding type specified.")},validateSubject:c,validatePublicKey:d,validatePrivateKey:h,validateExpiration:m}},792320,(e,t,r)=>{"use strict";var i,a=e.r(254799),n="aes-128-gcm",s={aes128gcm:1,aesgcm:2},o="encrypt",l="decrypt";function u(e){return"string"==typeof e?Buffer.from(e,"base64url"):e}function c(e,t){var r=a.createHmac("sha256",e);return r.update(t),r.digest()}function d(e,t){return i("salt",e),i("ikm",t),i("extract",c(e,t))}function h(e,t,r){i("prk",e),i("info",t);var a=Buffer.alloc(0),n=Buffer.alloc(0);t=Buffer.from(t,"ascii");for(var s=0,o=Buffer.alloc(1);a.length<r;)o.writeUIntBE(++s,0,1),n=c(e,Buffer.concat([n,t,o])),a=Buffer.concat([a,n]);return i("expand",a.slice(0,r))}function p(e,t){var r=Buffer.concat([Buffer.from("Content-Encoding: "+e+"\0","ascii"),t]);return i("info "+e,r),r}function m(e){var t=Buffer.concat([Buffer.alloc(2),e]);return t.writeUIntBE(e.length,0,2),t}function f(e,t,r){if(!e.salt)throw Error("must include a salt parameter for "+e.version);if("aesgcm"===e.version){var a,n,s,u=function(e,t){var r,a,n,s={secret:null,context:Buffer.alloc(0)};if(e.key){if(s.secret=e.key,16!==s.secret.length)throw Error("An explicit key must be 16 bytes")}else e.dh?s=function(e,t){var r,i,a=e.privateKey;if(t===o)r=a.getPublicKey(),i=e.dh;else if(t===l)r=e.dh,i=a.getPublicKey();else throw Error("Unknown mode only "+o+" and "+l+" supported");return{secret:a.computeSecret(e.dh),context:Buffer.concat([Buffer.from(e.keylabel,"ascii"),Buffer.from([0]),m(i),m(r)])}}(e,t):(e.keyid,s.secret=e.keymap[e.keyid]);if(!s.secret)throw Error("Unable to determine key");return i("secret",s.secret),i("context",s.context),e.authSecret&&(s.secret=(r=e.authSecret,a=s.secret,n=p("auth",Buffer.alloc(0)),h(d(r,a),n,32)),i("authsecret",s.secret)),s}(e,t);a=p("aesgcm",u.context),n=p("nonce",u.context),s=u.secret}else if("aes128gcm"===e.version)a=Buffer.from("Content-Encoding: aes128gcm\0"),n=Buffer.from("Content-Encoding: nonce\0"),s=function(e,t,r){if(r&&"function"!=typeof r)throw Error("Callback is not a function");if(e.key){if(16!==e.key.length)throw Error("An explicit key must be 16 bytes");return i("secret key",e.key)}if(!e.privateKey){if(r)var a=r(e.keyid);else var a=e.keymap&&e.keymap[e.keyid];if(!a)throw Error('No saved key (keyid: "'+e.keyid+'")');return a}return function(e,t){var r,a,n,s,u,c;if(!e.authSecret)throw Error("No authentication secret for webpush");if(i("authsecret",e.authSecret),t===o)a=e.privateKey.getPublicKey(),r=n=e.dh;else if(t===l)r=a=e.keyid,n=e.privateKey.getPublicKey();else throw Error("Unknown mode only "+o+" and "+l+" supported");return i("remote pubkey",r),i("sender pubkey",a),i("receiver pubkey",n),i("secret dh",(s=e.authSecret,u=e.privateKey.computeSecret(r),c=Buffer.concat([Buffer.from("WebPush: info\0"),n,a]),h(d(s,u),c,32)))}(e,t)}(e,t,r);else throw Error("Unable to set context for mode "+e.version);var c=d(e.salt,s),f={key:h(c,a,16),nonce:h(c,n,12)};return i("key",f.key),i("nonce base",f.nonce),f}function g(e){var t={};t.version=e.version||"aes128gcm",t.rs=parseInt(e.rs,10),isNaN(t.rs)&&(t.rs=4096);var r=s[t.version];if("aes128gcm"===t.version&&(r+=16),t.rs<=r)throw Error("The rs parameter has to be greater than "+r);if(e.salt&&(t.salt=u(e.salt),16!==t.salt.length))throw Error("The salt parameter must be 16 bytes");return t.keyid=e.keyid,e.key?t.key=u(e.key):(t.privateKey=e.privateKey,t.privateKey||(t.keymap=e.keymap),"aes128gcm"!==t.version&&(t.keylabel=e.keylabel||"P-256"),e.dh&&(t.dh=u(e.dh))),e.authSecret&&(t.authSecret=u(e.authSecret)),t}function y(e,t){var r=Buffer.from(e),a=r.readUIntBE(r.length-6,6);return r.writeUIntBE(((a^t)&0xffffff)+((a/0x1000000^t/0x1000000)&0xffffff)*0x1000000,r.length-6,6),i("nonce"+t,r),r}i="1"===process.env.ECE_KEYLOG?function(e,t){return console.warn(e+" ["+t.length+"]: "+t.toString("base64url")),t}:function(e,t){return t},t.exports={decrypt:function(e,t,r){var o=g(t);if("aes128gcm"===o.version){var u,c,d=(c=(u=e).readUIntBE(20,1),o.salt=u.slice(0,16),o.rs=u.readUIntBE(16,4),o.keyid=u.slice(21,21+c),21+c);e=e.slice(d)}var h=f(o,l,r),p=0,m=Buffer.alloc(0),w=o.rs;"aes128gcm"!==o.version&&(w+=16);for(var b=0;p<e.length;++b){var E=p+w;if("aes128gcm"!==o.version&&E===e.length)throw Error("Truncated payload");if((E=Math.min(E,e.length))-p<=16)throw Error("Invalid block: too small at "+b);var S=function(e,t,r,o,l){i("decrypt",r);var u=y(e.nonce,t),c=a.createDecipheriv(n,e.key,u);c.setAuthTag(r.slice(r.length-16));var d=c.update(r.slice(0,r.length-16));if(d=Buffer.concat([d,c.final()]),i("decrypted",d),"aes128gcm"!==o.version)return function(e,t){var r=s[t],a=e.readUIntBE(0,r);if(a+r>e.length)throw Error("padding exceeds block size");i("padding",e.slice(0,r+a));var n=Buffer.alloc(a);if(n.fill(0),0!==n.compare(e.slice(r,r+a)))throw Error("invalid padding");return e.slice(r+a)}(d,o.version);for(var h=d,p=h.length-1;p>=0;){if(h[p]){if(l){if(2!==h[p])throw Error("last record needs to start padding with a 2")}else if(1!==h[p])throw Error("last record needs to start padding with a 2");return h.slice(0,p)}--p}throw Error("all zero plaintext")}(h,b,e.slice(p,E),o,E>=e.length);m=Buffer.concat([m,S]),p=E}return m},encrypt:function(e,t,r){if(!Buffer.isBuffer(e))throw Error("buffer argument must be a Buffer");var l,u=g(t);u.salt||(u.salt=a.randomBytes(16)),"aes128gcm"===u.version?(u.privateKey&&!u.keyid&&(u.keyid=u.privateKey.getPublicKey()),l=function(e){var t=Buffer.alloc(5),r=Buffer.from(e.keyid||[]);if(r.length>255)throw Error("keyid is too large");return t.writeUIntBE(e.rs,0,4),t.writeUIntBE(r.length,4,1),Buffer.concat([e.salt,t,r])}(u)):l=Buffer.alloc(0);var c=f(u,o,r),d=0,h=s[u.version],p=h;"aes128gcm"===u.version&&(p+=16);for(var m=isNaN(parseInt(t.pad,10))?0:parseInt(t.pad,10),w=0,b=!1;!b;){var E=Math.min(u.rs-p-1,m);"aes128gcm"!==u.version&&(E=Math.min((1<<8*h)-1,E)),m>0&&0===E&&++E,m-=E;var S=d+u.rs-p-E;b=(b="aes128gcm"!==u.version?S>e.length:S>=e.length)&&m<=0;var v=function(e,t,r,o,l,u){i("encrypt",r),o=o||0;var c=y(e.nonce,t),d=a.createCipheriv(n,e.key,c),h=[],p=s[l.version],m=Buffer.alloc(o+p);if(m.fill(0),"aes128gcm"!==l.version){if(m.writeUIntBE(o,0,p),i("padding",m),h.push(d.update(m)),h.push(d.update(r)),!u&&m.length+r.length<l.rs)throw Error("Unable to pad to record size")}else h.push(d.update(r)),m.writeUIntBE(u?2:1,0,1),i("padding",m),h.push(d.update(m));d.final();var f=d.getAuthTag();if(16!==f.length)throw Error("invalid tag generated");return h.push(f),i("encrypted",Buffer.concat(h))}(c,w,e.slice(d,S),E,u,b);l=Buffer.concat([l,v]),d=S,++w}return l}}},44703,(e,t,r)=>{"use strict";let i=e.r(254799),a=e.r(792320);t.exports={encrypt:function(e,t,r,n){if(!e)throw Error("No user public key provided for encryption.");if("string"!=typeof e)throw Error("The subscription p256dh value must be a string.");if(65!==Buffer.from(e,"base64url").length)throw Error("The subscription p256dh value should be 65 bytes long.");if(!t)throw Error("No user auth provided for encryption.");if("string"!=typeof t)throw Error("The subscription auth key must be a string.");if(Buffer.from(t,"base64url").length<16)throw Error("The subscription auth key should be at least 16 bytes long");if("string"!=typeof r&&!Buffer.isBuffer(r))throw Error("Payload must be either a string or a Node Buffer.");("string"==typeof r||r instanceof String)&&(r=Buffer.from(r));let s=i.createECDH("prime256v1"),o=s.generateKeys(),l=i.randomBytes(16).toString("base64url"),u=a.encrypt(r,{version:n,dh:e,privateKey:s,salt:l,authSecret:t});return{localPublicKey:o,salt:l,cipherText:u}}}},469719,e=>{"use strict";var t=e.i(562810);e.s(["z",0,t])},524214,(e,t,r)=>{t.exports={name:"ai-development-environment",version:"0.1.0",private:!0,workspaces:["packages/*"],engines:{node:">=24.16.0 <25"},scripts:{dev:"npm run generate && npm run dev:generated","dev:generated":"npm run db:migrate && next dev","dev:all":'PORT=${PORT:-3000} AGENT_WS_HOSTNAME=${AGENT_WS_HOSTNAME:-127.0.0.1} AGENT_WS_PORT=${AGENT_WS_PORT:-3092} NEXT_PUBLIC_AGENT_WS_URL=${NEXT_PUBLIC_AGENT_WS_URL:-ws://127.0.0.1:${AGENT_WS_PORT:-3092}/graphql} concurrently --kill-others --names server,agent --prefix-colors blue,magenta "npm run dev" "npm run agent:dev"',build:"npm run generate && npm run build:generated","build:generated":"next build",postbuild:"cp -R public .next/standalone/ && cp -R .next/static .next/standalone/.next/",start:"node .next/standalone/server.js","agent:build":"npm run build --workspace @ai-development-environment/control-agent","agent:dev":"npm run dev --workspace @ai-development-environment/control-agent","agent:format":"npm run format --workspace @ai-development-environment/control-agent","agent:format:check":"npm run format:check --workspace @ai-development-environment/control-agent","agent:lint":"npm run lint --workspace @ai-development-environment/control-agent","agent:lint:fix":"npm run lint:fix --workspace @ai-development-environment/control-agent","agent:test":"npm run test --workspace @ai-development-environment/control-agent","agent:test:run":"npm run test:run --workspace @ai-development-environment/control-agent","agent:type-check":"npm run type-check --workspace @ai-development-environment/control-agent","agent:full-check":"npm run full-check --workspace @ai-development-environment/control-agent","agent:full-check:ci":"npm run full-check:ci --workspace @ai-development-environment/control-agent","agent:full-check:dev":"npm run full-check:dev --workspace @ai-development-environment/control-agent",generate:"npm run generate:prisma && npm run generate:schema && npm run generate:graphql","generate:prisma":"prisma generate","generate:schema":"tsx scripts/prebuild-schema.ts","generate:graphql":"graphql-codegen --config codegen.ts","db:migrate":"prisma migrate dev","db:deploy":"prisma migrate deploy","db:studio":"prisma studio","db:audit-re2":"tsx scripts/audit-re2-patterns.ts","db:vacuum":"node scripts/vacuum-database.mjs",supergraph:"rover supergraph compose --elv2-license accept --config ./supergraph.yaml > supergraph.graphql",clean:"rm -rf .next coverage src/generated prisma/dev.db* supergraph.graphql",format:"prettier --write --ignore-path .gitignore --ignore-path .prettierignore .","format:check":"prettier --check --ignore-path .gitignore --ignore-path .prettierignore .",lint:"eslint .","lint:fix":"eslint --fix .","pretype-check":"npm run generate","type-check":"npm run type-check:generated","type-check:generated":"next typegen && tsc --noEmit --project tsconfig.typecheck.json && npm run agent:type-check",test:"vitest","test:run":"vitest run","test:coverage":"vitest run --coverage","test:standalone-credentials":"node scripts/test-standalone-credentials.mjs","check-translations":"npx tsx scripts/check-translations.ts","telemetry:mock":"tsx scripts/send-mock-telemetry.ts","mock:db":"rm -f prisma/mock.db prisma/mock.db-shm prisma/mock.db-wal && node -e \"const fs=require('node:fs');fs.closeSync(fs.openSync('prisma/mock.db','w'))\" && DATABASE_URL=file:./prisma/mock.db prisma migrate deploy","mock:seed":"DATABASE_URL=file:./prisma/mock.db tsx scripts/seed-mock-data.ts","mock:reset":"npm run generate:prisma && npm run mock:db && npm run mock:seed","screenshots:build":"SCREENSHOT_DIST_DIR=.next-mock AGENT_WS_HOSTNAME=127.0.0.1 next build","screenshots:browsers":"playwright install chromium webkit",screenshots:"node scripts/run-screenshots.mjs","screenshots:run":"node scripts/run-screenshots.mjs --skip-setup","screenshots:walkthrough":"node scripts/run-screenshots.mjs --skip-setup playwright/walkthrough.spec.ts","screenshots:copy":"node scripts/copy-screenshots.mjs","screenshots:copy:walkthrough":"node scripts/copy-screenshots.mjs --include-videos","schema:copy":"node scripts/copy-schema.mjs","schema:publish":"node scripts/publish-schema.mjs","full-check":"npm run generate && npm run format && npm run lint:fix && npm run type-check:generated && npm run test:run && npm run agent:test:run && npm run check-translations && npm run build:generated && npm run postbuild","full-check:ci":"npm run generate && npm run format:check && npm run lint && npm run type-check:generated && npm run test:run && npm run agent:test:run && npm run check-translations && npm run build:generated && npm run postbuild","full-check:dev":"npm run full-check && npm run dev:generated",upgrade:"ncu -u --cooldown 48h && npm install --min-release-age=2 && npm upgrade --min-release-age=2","upgrade:check":"ncu --cooldown 48h"},dependencies:{"@ai-development-environment/agent-contract":"*","@apollo/server":"5.5.1","@apollo/subgraph":"2.14.4","@as-integrations/next":"4.1.0","@base-ui/react":"1.7.0","@better-auth/api-key":"^1.7.2","@better-auth/prisma-adapter":"^1.7.2","@expo-google-fonts/noto-emoji":"0.4.6","@fontpkg/unifont":"15.0.1","@graphql-tools/merge":"9.2.3","@lobehub/icons-static-svg":"^1.94.0","@mdx-js/loader":"3.1.1","@modelcontextprotocol/sdk":"1.30.0","@napi-rs/keyring":"1.3.0","@next/mdx":"16.3.3","@peculiar/x509":"2.0.0","@prisma/adapter-better-sqlite3":"7.10.0","@prisma/client":"7.10.0","@tailwindcss/typography":"0.5.20","@xterm/addon-fit":"^0.11.0","@xterm/addon-search":"^0.16.0","@xterm/xterm":"^6.0.0","@xyflow/react":"^12.11.5",asn1js:"3.0.10","better-auth":"^1.7.2","better-sqlite3":"12.11.1","class-variance-authority":"0.7.1",clsx:"2.1.1",cmdk:"1.1.1","date-fns":"4.4.0",diff:"9.0.0","extended-markdown-adf-parser":"2.4.0",graphql:"^16","graphql-tag":"2.12.7","graphql-ws":"6.2.1","jira.js":"6.2.0",jira2md:"3.0.1",jose:"6.2.10","lucide-react":"1.34.0",next:"16.3.3","next-intl":"4.13.7",pdfkit:"0.20.1",pixelmatch:"^7.2.0",pkijs:"3.4.0","quickjs-emscripten":"0.32.0","radix-ui":"1.6.7",re2:"1.26.1",react:"19.2.8","react-day-picker":"10.0.1","react-dom":"19.2.8","react-markdown":"10.1.0",recharts:"3.10.1","reflect-metadata":"0.2.2","remark-gfm":"4.0.1","server-only":"0.0.1",shadcn:"4.19.0","tailwind-merge":"3.6.0","tw-animate-css":"1.4.0",undici:"8.10.0","web-push":"3.6.7",ws:"8.21.3",zod:"4.4.3"},devDependencies:{"@babel/plugin-transform-runtime":"7.29.0","@graphql-codegen/cli":"7.3.1","@graphql-codegen/typescript":"6.1.0","@graphql-codegen/typescript-resolvers":"6.1.0","@mdx-js/rollup":"3.1.1","@playwright/test":"1.62.1","@svgr/webpack":"^8.1.0","@tailwindcss/postcss":"4.3","@testing-library/dom":"10.4.1","@testing-library/react":"16.3.2","@types/better-sqlite3":"9.6.0","@types/node":"^24","@types/pdfkit":"0.17.6","@types/react":"19.2","@types/react-dom":"19.2","@types/web-push":"3.6.4","@types/ws":"8.18.1","@vitejs/plugin-react":"6.1.0","@vitest/coverage-v8":"^4.1.11",concurrently:"10.0.5",dotenv:"17.4.2",esbuild:"0.28.2",eslint:"^9","eslint-config-next":"16.3.3",jsdom:"30.0.1","npm-check-updates":"23.1.0",prettier:"3.9.6",prisma:"7.10.0",tailwindcss:"4.3",tsx:"4.23.12",typescript:"^6",vitest:"4.1.11"},overrides:{"@better-auth/core":"1.7.2"},optionalDependencies:{"@apollo/rover":"0.41.0"},allowScripts:{"better-sqlite3@12.11.1":!0,"esbuild@0.28.2":!0,"prisma@7.10.0":!0,"sharp@0.34.5":!0,"unrs-resolver@1.12.2":!0,"@apollo/protobufjs@1.2.8":!0,"@parcel/watcher@2.6.0":!0,"@prisma/engines@7.10.0":!0,"@swc/core@1.15.47":!0,"re2@1.26.1":!0}}},169349,(e,t,r)=>{t.exports={name:"@ai-development-environment/control-agent",version:"0.1.0",description:"Control agent for the AI Development Environment",license:"MIT",repository:{type:"git",url:"git+https://github.com/bludesign/ai-development-environment.git",directory:"packages/control-agent"},type:"module",engines:{node:">=24.16.0 <25"},bin:{"control-agent":"dist/control-agent.js"},files:["dist"],publishConfig:{access:"public"},dependencies:{"@anthropic-ai/claude-agent-sdk":"0.3.247","@openai/codex-sdk":"0.150.1","@opencode-ai/sdk":"1.18.23",ws:"8.21.3"},scripts:{build:"node esbuild.config.mjs",smoke:"node dist/control-agent.js --help",prepublishOnly:"npm run build",dev:"node --watch --watch-preserve-output --import tsx src/index.ts dev",format:"prettier --write --ignore-path ../../.gitignore --ignore-path ../../.prettierignore .","format:check":"prettier --check --ignore-path ../../.gitignore --ignore-path ../../.prettierignore .",lint:"eslint .","lint:fix":"eslint --fix .","type-check":"tsc --noEmit -p tsconfig.json",test:"vitest","test:run":"vitest run","full-check":"npm run format && npm run lint:fix && npm run type-check && npm run test:run && npm run build && npm run smoke","full-check:ci":"npm run format:check && npm run lint && npm run type-check && npm run test:run && npm run build && npm run smoke","full-check:dev":"npm run full-check && npm run dev",upgrade:"ncu -u --cooldown 48h && npm install --min-release-age=2 && npm upgrade --min-release-age=2","upgrade:check":"ncu --cooldown 48h"},devDependencies:{"@ai-development-environment/agent-contract":"*","@types/node":"^24","@types/ws":"8.18.1",esbuild:"0.28.2",eslint:"^9","eslint-config-next":"16.3.3",graphql:"16.0.0","graphql-ws":"6.2.1","npm-check-updates":"23.1.0",prettier:"3.9.6",tsx:"4.23.12",typescript:"^6",vitest:"4.1.11"}}},650457,e=>{"use strict";var t=e.i(666680),r=e.i(642582),i=e.i(524214),a=e.i(169349),n=e.i(243783);e.i(805422);var s=e.i(661983),o=e.i(694355);let l="default",u=["QUEUED","RUNNING","CANCELLING"],c=[{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}],d={id:"builtin-github",name:"GitHub",command:"gh auth status",builtIn:!0},h={id:"builtin-gitlab",name:"GitLab",command:"glab auth status",builtIn:!0};function p(e){try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}catch{return[]}}function m(e){return!!(e.lastSeenAt&&Date.now()-e.lastSeenAt.getTime()<=(0,o.agentOnlineWindowMs)(e)&&null===e.disconnectedAt)}e.s(["CliHealthService",0,class{agentControl;gitHub;gitLab;startingAgents;constructor(e,t,i){this.agentControl=e,this.gitHub=t,this.gitLab=i,this.startingAgents=new Set,this.agentControl.registerCompletionObserver(async e=>{e.kind===r.CLI_HEALTH_JOB_KIND&&this.publish(e.agentId)})}publish(e){s.agentEventBus.publish(s.CLI_HEALTH_CHANGED_TOPIC,{cliHealthStatusChanged:{agentId:e}})}async customChecks(){let e=await (0,n.getPrismaClient)(),t=await e.cliHealthSettings.findUnique({where:{id:l}});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:[...c,...t.tokenConfigured?[d]:[],...r.configured?[h]:[],...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 i=await (0,n.getPrismaClient)(),a=t??(await this.definitions()).checks,[s,o]=await Promise.all([i.agentJob.findFirst({where:{agentId:e.id,kind:r.CLI_HEALTH_JOB_KIND,status:{in:u}},orderBy:{createdAt:"desc"}}),i.agentJob.findFirst({where:{agentId:e.id,kind:r.CLI_HEALTH_JOB_KIND,status:"SUCCEEDED"},orderBy:{finishedAt:"desc"}})]),l=p(e.capabilitiesJson).includes(r.CLI_HEALTH_JOB_KIND),c=this.resultViews(a,function(e){if(!e)return null;try{let t=JSON.parse(e);return Array.isArray(t.checks)?t:null}catch{return null}}(o?.resultJson??null)),d=c.filter(e=>"NOT_RUN"!==e.state),h=l?s?"RUNNING":0===d.length?"NOT_CHECKED":d.length===c.length&&d.every(e=>"HEALTHY"===e.state)?"HEALTHY":"ISSUES":"UNSUPPORTED";return{agentId:e.id,name:e.name,hostname:e.hostname,version:e.version,connectionStatus:m(e)?"ONLINE":"OFFLINE",supported:l,activeJobId:s?.id??null,lastCheckedAt:o?.finishedAt?.toISOString()??null,overall:h,results:c}}async installationStatus(){let[{checks:e,customChecks:t},r]=await Promise.all([this.definitions(),this.agentControl.listAgents()]);return{version:process.env.AIDE_VERSION||i.default.version,dependencies:[{name:"Next.js",version:i.default.dependencies.next},{name:"Claude SDK",version:a.default.dependencies["@anthropic-ai/claude-agent-sdk"]},{name:"Codex SDK",version:a.default.dependencies["@openai/codex-sdk"]},{name:"OpenCode SDK",version:a.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:i},a]=await Promise.all([this.definitions(),this.agentControl.listAgents()]),n=e?a.filter(t=>t.id===e):a;if(e&&0===n.length)throw Error("Agent not found");let s=n.filter(e=>m(e)&&p(e.capabilitiesJson).includes(r.CLI_HEALTH_JOB_KIND));return await Promise.all(s.map(async e=>{if(!this.startingAgents.has(e.id)){this.startingAgents.add(e.id);try{if((await this.agentStatus(e,i)).activeJobId)return;await this.agentControl.createJob({agentId:e.id,kind:r.CLI_HEALTH_JOB_KIND,payload:{checks:i},idempotencyKey:`cli-health:${(0,t.randomUUID)()}`,timeoutSeconds:600,visibility:"SYSTEM"}),this.publish(e.id)}finally{this.startingAgents.delete(e.id)}}})),this.installationStatus()}async saveSettings(e){let r=function(e){if(e.length>20)throw Error("At most 20 custom CLI health checks are allowed");let r=new Set,i=new Set;return e.map(e=>{let a=e.name?.trim()??"",n=e.command?.trim()??"",s=e.id?.trim()||(0,t.randomUUID)();if(!a||a.length>100||a.includes("\0"))throw Error("Check names must be between 1 and 100 characters and cannot contain NUL characters");if(!n||n.length>4096||n.includes("\0"))throw Error("Check commands must be between 1 and 4096 characters and cannot contain NUL characters");let o=a.toLocaleLowerCase();if(r.has(o))throw Error("Custom check names must be unique");if(s.length>100||s.includes("\0")||s.startsWith("builtin-")||i.has(s))throw Error("Custom check identifiers must be unique and valid");return r.add(o),i.add(s),{id:s,name:a,command:n,enabled:!1!==e.enabled}})}(e),i=await (0,n.getPrismaClient)();return await i.cliHealthSettings.upsert({where:{id:l},create:{id:l,checksJson:JSON.stringify(r)},update:{checksJson:JSON.stringify(r)}}),this.publish(null),this.installationStatus()}}])},141859,e=>{"use strict";e.i(650457),e.s([])},682954,e=>{"use strict";function t(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}let r={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};function i(e,t){let r=t;for(;;){let t=e.indexOf("<",r);if(t<0)return null;if(e.startsWith("<!--",t)){let i=e.indexOf("-->",t);if(i<0)return null;r=i+3;continue}if(e.startsWith("<?",t)||e.startsWith("<!",t)){let i=e.indexOf(">",t);if(i<0)return null;r=i+1;continue}let i=e.indexOf(">",t);if(i<0)return null;let a=e.slice(t+1,i),n=a.startsWith("/"),s=a.endsWith("/");return{name:a.slice(+!!n,s?a.length-1:a.length).trim().split(/\s/)[0],closing:n,selfClosing:s,end:i+1}}}function a(e,t,i){let a=e.indexOf(`</${i}`,t);if(a<0)throw Error(`Unterminated <${i}> in plist`);let n=e.indexOf(">",a);return[e.slice(t,a).replace(/&(#x?[0-9a-fA-F]+|[a-z]+);/g,(e,t)=>t.startsWith("#x")||t.startsWith("#X")?String.fromCodePoint(Number.parseInt(t.slice(2),16)):t.startsWith("#")?String.fromCodePoint(Number.parseInt(t.slice(1),10)):r[t]??e),n+1]}e.s(["parsePlist",0,function(e){let t=e.indexOf("<plist"),r=t<0?0:e.indexOf(">",t)+1;return function e(t,r,n){if(n>64)throw Error("plist nesting is too deep");let s=i(t,r);if(!s||s.closing)throw Error("Expected a plist value");if(s.selfClosing)switch(s.name){case"true":return[!0,s.end];case"false":return[!1,s.end];case"dict":return[{},s.end];case"array":return[[],s.end];default:return["",s.end]}switch(s.name){case"dict":{let r={},o=s.end;for(;;){let s=i(t,o);if(!s)throw Error("Unterminated <dict> in plist");if(s.closing&&"dict"===s.name)return[r,s.end];if("key"!==s.name)throw Error("Expected <key> in <dict>");let[l,u]=a(t,s.end,"key"),[c,d]=e(t,u,n+1);r[l]=c,o=d}}case"array":{let r=[],a=s.end;for(;;){let s=i(t,a);if(!s)throw Error("Unterminated <array> in plist");if(s.closing&&"array"===s.name)return[r,s.end];let[o,l]=e(t,a,n+1);r.push(o),a=l}}case"integer":case"real":{let[e,r]=a(t,s.end,s.name);return[Number(e.trim()),r]}case"string":case"date":case"data":{let[e,r]=a(t,s.end,s.name);return["string"===s.name?e:e.trim(),r]}default:{let[,e]=a(t,s.end,s.name);return[null,e]}}}(e,r,0)[0]},"plistDocument",0,function(e){return`<?xml version="1.0" encoding="UTF-8"?>
|
|
64
64
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
65
65
|
<plist version="1.0">${function e(r){if("boolean"==typeof r)return r?"<true/>":"<false/>";if("string"==typeof r)return`<string>${t(r)}</string>`;if("number"==typeof r&&Number.isInteger(r))return`<integer>${r}</integer>`;if(Array.isArray(r))return`<array>${r.map(t=>e(t)).join("")}</array>`;if(r&&"object"==typeof r)return`<dict>${Object.entries(r).map(([r,i])=>`<key>${t(r)}</key>${e(i)}`).join("")}</dict>`;throw Error("Unsupported plist value")}(e)}</plist>
|
|
66
|
-
`}])},735255,e=>{"use strict";let t=Symbol("unattributed");function r(){return{inputTokens:0,outputTokens:0,cacheCreationTokens:0,cacheReadTokens:0,totalTokens:0,totalCost:0}}function i(e,t){e.inputTokens+=t.inputTokens,e.outputTokens+=t.outputTokens,e.cacheCreationTokens+=t.cacheCreationTokens,e.cacheReadTokens+=t.cacheReadTokens,e.totalTokens+=t.totalTokens,e.totalCost+=t.totalCost}function a(e,t){return t.totalCost-e.totalCost||t.totalTokens-e.totalTokens||(e.modelName??e.agentName??"").localeCompare(t.modelName??t.agentName??"")}function n(e){let t=e=>String(e).padStart(2,"0");return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}`}function s(e){let t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)throw Error("Usage date must be a valid date in YYYY-MM-DD format");let[,r,i,a]=t,n=Number(r),s=Number(i),o=Number(a),l=new Date(0);if(l.setHours(0,0,0,0),l.setFullYear(n,s-1,o),l.getFullYear()!==n||l.getMonth()!==s-1||l.getDate()!==o)throw Error("Usage date must be a valid date in YYYY-MM-DD format");return l}function o(e){let t=new Date(864e5*e),r=e=>String(e).padStart(2,"0");return`${t.getUTCFullYear()}-${r(t.getUTCMonth()+1)}-${r(t.getUTCDate())}`}function l(e,t){if(0===e.days.length)return null;let r=e.days.map(e=>{let t,r;return{ordinal:(t=s(e.period),(r=new Date(0)).setUTCHours(0,0,0,0),r.setUTCFullYear(t.getFullYear(),t.getMonth(),t.getDate()),Math.floor(r.getTime()/864e5)),totalCost:e.totalCost}}).sort((e,t)=>e.ordinal-t.ordinal),i=new Map(r.map(e=>[e.ordinal,e.totalCost])),a=r[0].ordinal,n=r.at(-1).ordinal,l=0,u=a,c=-1/0;for(let e=a;e<=n;e+=1)l+=i.get(e)??0,((l-=i.get(e-t)??0)>c||l===c&&e>u)&&(c=l,u=e);return{startDate:o(u-(t-1)),endDate:o(u),totalCost:c}}e.s(["aggregateUsage",0,function(e){let n=new Map,s=r();for(let{agent:a,report:o}of e)for(let e of(i(s,o.totals),o.daily)){let s=n.get(e.period);s||(s={...r(),period:e.period,models:new Map,sourceSet:new Set},n.set(e.period,s)),i(s,e),e.metadata.agents.forEach(e=>s.sourceSet.add(e));let o=0;for(let t of e.modelBreakdowns){let n={inputTokens:t.inputTokens,outputTokens:t.outputTokens,cacheCreationTokens:t.cacheCreationTokens,cacheReadTokens:t.cacheReadTokens,totalTokens:t.inputTokens+t.outputTokens+t.cacheCreationTokens+t.cacheReadTokens,totalCost:t.cost};o+=n.totalTokens;let l=s.models.get(t.modelName);l||(l={...r(),modelName:t.modelName,agents:new Map},s.models.set(t.modelName,l)),i(l,n);let u=l.agents.get(a.id);u||(u={...r(),agentId:a.id,agentName:a.name,hostname:a.hostname,sources:[],sourceSet:new Set},l.agents.set(a.id,u)),i(u,n),e.metadata.agents.forEach(e=>u.sourceSet.add(e))}!function(e,i,a,n){if(n<=0)return;let s=e.models.get(t);s||(s={...r(),modelName:"Unattributed tokens",agents:new Map,unattributed:!0},e.models.set(t,s)),s.totalTokens+=n;let o=s.agents.get(i.id);o||(o={...r(),agentId:i.id,agentName:i.name,hostname:i.hostname,sources:[],sourceSet:new Set},s.agents.set(i.id,o)),o.totalTokens+=n,a.forEach(e=>o.sourceSet.add(e))}(s,a,e.metadata.agents,e.totalTokens-o)}return{totals:s,days:[...n.values()].sort((e,t)=>t.period.localeCompare(e.period)).map(e=>({inputTokens:e.inputTokens,outputTokens:e.outputTokens,cacheCreationTokens:e.cacheCreationTokens,cacheReadTokens:e.cacheReadTokens,totalTokens:e.totalTokens,totalCost:e.totalCost,period:e.period,sources:[...e.sourceSet].sort(),models:[...e.models.values()].sort(a).map(e=>({inputTokens:e.inputTokens,outputTokens:e.outputTokens,cacheCreationTokens:e.cacheCreationTokens,cacheReadTokens:e.cacheReadTokens,totalTokens:e.totalTokens,totalCost:e.totalCost,modelName:e.modelName,...e.unattributed?{unattributed:!0}:{},agents:[...e.agents.values()].sort(a).map(e=>({inputTokens:e.inputTokens,outputTokens:e.outputTokens,cacheCreationTokens:e.cacheCreationTokens,cacheReadTokens:e.cacheReadTokens,totalTokens:e.totalTokens,totalCost:e.totalCost,agentId:e.agentId,agentName:e.agentName,hostname:e.hostname,sources:[...e.sourceSet].sort()}))}))}))}},"filterUsageByDays",0,function(e,t,a=new Date){if(null===t)return e;let o="string"==typeof a?s(a):new Date(a);o.setHours(0,0,0,0);let l=new Date(o);l.setDate(l.getDate()-(t-1));let u=n(l),c=n(o),d=e.days.filter(e=>e.period>=u&&e.period<=c),h=r();return d.forEach(e=>i(h,e)),{days:d,totals:h}},"usageSpendPeaks",0,function(e,t,a){let n,s,o=t?(n=r(),{days:e.days.flatMap(e=>{let a=new Set,s=e.models.flatMap(e=>{let n=e.agents.filter(e=>e.agentId===t);if(0===n.length)return[];let s=r();return n.forEach(e=>{i(s,e),e.sources.forEach(e=>a.add(e))}),[{...s,modelName:e.modelName,agents:n,...e.unattributed?{unattributed:!0}:{}}]});if(0===s.length)return[];let o=r();return s.forEach(e=>i(o,e)),i(n,o),[{...o,period:e.period,sources:[...a].sort(),models:s}]}),totals:n}):e,u=a?(s=r(),{days:o.days.flatMap(e=>{let t=e.models.filter(e=>!e.unattributed&&e.modelName===a);if(0===t.length)return[];let n=r(),o=new Set;return t.forEach(e=>{i(n,e),e.agents.forEach(e=>e.sources.forEach(e=>o.add(e)))}),i(s,n),[{...n,period:e.period,sources:[...o].sort(),models:t}]}),totals:s}):o;return{last7Days:l(u,7),last30Days:l(u,30)}}])},497800,248626,361617,e=>{"use strict";var t=e.i(469719),r=e.i(807055),i=e.i(184015),a=e.i(119909),n=e.i(835544),s=e.i(499162);function o(e){return{kind:"static",options:e.map(e=>({value:e,label:e.charAt(0)+e.slice(1).toLowerCase().replace(/_/g," ")}))}}function l(e){return{kind:"static",options:e}}let u={agent:"agent.id",codebase:"codebase.id",worktree:"worktree.id",githubRepository:"repo.id",githubPullRequest:"pr.number",jiraTicket:"ticket.key",agentRun:"run.id",githubWorkflowRun:"pipeline.runId"};function c(e,t){return{kind:"resource",resource:e,scopeFrom:t,sessionPath:u[e]}}let d=["literal","session","interpolation"],h=["literal","interpolation"],p=(e,t,r={})=>({key:e,label:t,control:"text",valueModes:d,...r}),m=(e,t,r={})=>p(e,t,{multiline:!0,...r}),f=(e,t,r={})=>({key:e,label:t,control:"number",valueModes:["literal","session"],...r}),g=(e,t,r={})=>({key:e,label:t,control:"boolean",...r}),y=(e,t,r,i={})=>({key:e,label:t,control:"enum",options:r,...i}),w=(e,t,r,i={})=>{let{scopeFrom:a,...n}=i;return{key:e,label:t,control:"resource",options:c(r,a),valueModes:d,...n}},b=(e,t,r,i={})=>{let{scopeFrom:a,...n}=i;return{key:e,label:t,control:"resourceMulti",options:c(r,a),valueModes:h,...n}},E=(e,t,r={})=>({key:e,label:t,control:"stringList",valueModes:h,...r}),S=e=>({key:"mcpPresetIds",label:"MCP tool presets",control:"mcpPresetMulti",presetKind:e,default:[]}),v=(e,t,r={})=>({key:e,label:t,control:"record",valueModes:h,...r}),I=(e,t,r={})=>({key:e,label:t,control:"json",valueModes:h,...r}),A=(e,t,r={})=>({key:e,label:t,control:"triggerChoices",...r}),k=l([{value:"EQ",label:"Equals"},{value:"NE",label:"Not equal"},{value:"GT",label:"Greater than"},{value:"GTE",label:"Greater or equal"},{value:"LT",label:"Less than"},{value:"LTE",label:"Less or equal"},{value:"CONTAINS",label:"Contains"},{value:"MATCHES",label:"Matches RE2"},{value:"EXISTS",label:"Exists"}]),_=o(a.WORKTREE_OPERATIONS.filter(e=>"OPEN_EDITOR"!==e)),T=()=>[p("owner","Repository owner",{placeholder:"octocat",help:"Defaults to the repository from session data."}),p("name","Repository name",{placeholder:"hello-world"})],C=e=>[w("worktreeId","Worktree","worktree"),w("jiraIssueKey","Jira issue key","jiraTicket",{placeholder:"APP-123"}),{key:"model",label:"Model",control:"model",required:!0,valueModes:["literal","session"],modelKeys:{provider:"provider",model:"model",effort:"effort",scopeFrom:"worktreeId"}},g("webSearchEnabled","Enable web search"),S(e),f("worktreeConcurrencyLimit","Worktree concurrency limit",{default:"PLAN"===e?0:"SESSION"===e?1:void 0,minimum:0,maximum:32,integer:!0,help:"PLAN"===e?"Maximum plans admitted on this worktree. Use 0 for unlimited.":"SESSION"===e?"Maximum sessions admitted on this worktree. Use 0 for unlimited.":"Maximum same-kind runs admitted on this worktree. Use 0 for unlimited; leave empty for the source kind's default."}),m("prompt","Prompt",{required:!0}),E("attachmentIds","Attachment IDs")],R={JIRA_LOAD_TICKET:{fields:[w("issueKey","Issue key","jiraTicket",{placeholder:"APP-123"}),g("force","Bypass cache")]},JIRA_TRANSITION:{fields:[w("issueKey","Issue key","jiraTicket",{placeholder:"APP-123"}),p("transitionId","Transition ID",{required:!0})]},JIRA_COMMENT:{fields:[w("issueKey","Issue key","jiraTicket",{placeholder:"APP-123"}),m("content","Comment",{required:!0}),y("format","Format",l([{value:"MARKDOWN",label:"Markdown"},{value:"JIRA_WIKI",label:"Jira wiki"}]))]},JIRA_ASSIGN:{fields:[w("issueKey","Issue key","jiraTicket",{placeholder:"APP-123"}),w("accountId","Assignee","jiraUser",{scopeFrom:"issueKey",help:"Leave empty to unassign the ticket."})]},JIRA_UPDATE_FIELDS:{fields:[w("issueKey","Issue key","jiraTicket",{placeholder:"APP-123"}),I("fields","Fields",{placeholder:'{ "labels": ["ready"] }'})]},JIRA_RESOLVE_BRANCH:{fields:[w("issueKey","Issue key","jiraTicket",{placeholder:"APP-123"}),w("codebaseId","Codebase","codebase")]},GITHUB_LOAD_PR:{fields:[...T(),f("number","Pull request number")]},GITHUB_MERGE_PR:{fields:[...T(),f("number","Pull request number"),y("method","Merge method",l([{value:"SQUASH",label:"Squash"},{value:"MERGE",label:"Merge"},{value:"REBASE",label:"Rebase"}])),p("commitHeadline","Commit headline"),m("commitBody","Commit body"),p("authorEmail","Author email")]},GITHUB_COLLECT_REVIEW_THREADS:{fields:[...T(),f("number","Pull request number")]},GITHUB_REPLY_REVIEW_THREAD:{fields:[p("threadId","Review thread ID",{required:!0}),m("body","Reply",{required:!0})]},GITHUB_SET_REVIEW_THREAD_RESOLVED:{fields:[p("threadId","Review thread ID",{required:!0}),g("resolved","Mark resolved")]},GITHUB_CREATE_PR:{fields:[...T(),p("baseRefName","Base branch"),p("headRefName","Head branch"),p("title","Title"),m("body","Body"),g("draft","Open as draft")]},GITHUB_SET_PR_LABELS:{fields:[...T(),f("number","Pull request number"),E("labels","Labels")]},GITHUB_RETRY_PIPELINE:{fields:[w("repositoryId","Repository","githubRepository"),p("checkSuiteId","Check suite ID")]},GITHUB_RETRY_JOB:{fields:[w("repositoryId","Repository","githubRepository"),p("checkSuiteId","Check suite ID",{required:!0}),p("jobId","Workflow job ID",{required:!0})]},GITHUB_CANCEL_WORKFLOW_RUN:{fields:[p("codebaseRepositoryId","Codebase repository ID"),w("workflowRunId","Workflow run","githubWorkflowRun",{scopeFrom:"codebaseRepositoryId"}),g("force","Force cancel")]},GITHUB_SAVE_AUTO_RETRY:{fields:[I("input","Auto-retry rule",{required:!0})]},GITHUB_WAIT_CHECKS:{fields:[p("repositoryId","Repository ID"),p("workflowRunId","Workflow run ID")]},GITLAB_LOAD_MR:{fields:[p("projectId","Project ID"),f("iid","Merge request IID")]},GITLAB_CREATE_MR:{fields:[p("projectId","Project ID"),p("sourceBranch","Source branch"),p("targetBranch","Target branch"),p("title","Title"),m("description","Description"),g("removeSourceBranch","Remove source branch"),g("squash","Squash commits"),E("reviewerIds","Reviewer IDs"),E("labels","Labels")]},GITLAB_UPDATE_MR:{fields:[p("projectId","Project ID"),f("iid","Merge request IID"),p("title","Title"),m("description","Description"),y("stateEvent","State",o(["CLOSE","REOPEN"])),E("reviewerIds","Reviewer IDs"),E("labels","Labels")]},GITLAB_SUBMIT_REVIEW:{fields:[p("projectId","Project ID"),f("iid","Merge request IID"),y("outcome","Review outcome",o(["APPROVE","COMMENT","REQUEST_CHANGES"])),m("body","Review body")]},GITLAB_REPLY_DISCUSSION:{fields:[p("projectId","Project ID"),f("iid","Merge request IID"),p("discussionId","Discussion ID",{required:!0}),m("body","Reply",{required:!0})]},GITLAB_SET_DISCUSSION_RESOLVED:{fields:[p("projectId","Project ID"),f("iid","Merge request IID"),p("discussionId","Discussion ID",{required:!0}),g("resolved","Mark resolved")]},GITLAB_MERGE_MR:{fields:[p("projectId","Project ID"),f("iid","Merge request IID"),g("squash","Squash commits"),g("removeSourceBranch","Remove source branch"),g("autoMerge","Enable auto-merge"),p("sha","Expected source SHA")]},GITLAB_SET_MR_LABELS:{fields:[p("projectId","Project ID"),f("iid","Merge request IID"),E("labels","Labels")]},GITLAB_REQUEST_REVIEWERS:{fields:[p("projectId","Project ID"),f("iid","Merge request IID"),E("reviewerIds","Reviewer IDs")]},GITLAB_CREATE_PIPELINE:{fields:[p("projectId","Project ID"),p("ref","Git ref"),I("variables","Pipeline variables")]},GITLAB_RETRY_PIPELINE:{fields:[p("projectId","Project ID"),p("pipelineId","Pipeline ID")]},GITLAB_RETRY_JOB:{fields:[p("projectId","Project ID"),p("jobId","Job ID")]},GITLAB_CANCEL_PIPELINE:{fields:[p("projectId","Project ID"),p("pipelineId","Pipeline ID")]},GITLAB_SAVE_AUTO_RETRY:{fields:[I("input","Auto-retry rule",{required:!0})]},GITLAB_WAIT_PIPELINE:{fields:[p("projectId","Project ID"),p("pipelineId","Pipeline ID")]},WORKTREE_CREATE:{fields:[w("codebaseId","Codebase","codebase"),y("mode","Branch mode",o(["NEW","EXISTING","TICKET"])),p("branchName","Branch name"),p("ticketKey","Ticket key",{placeholder:"APP-123"}),p("baseBranch","Base branch")]},WORKTREE_CHANGE_BRANCH:{fields:[w("worktreeId","Worktree","worktree"),y("mode","Branch mode",o(["NEW","EXISTING","TICKET"])),p("branchName","Branch name"),p("ticketKey","Ticket key",{placeholder:"APP-123"}),p("baseBranch","Base branch"),g("stashOnFailure","Stash on failure")]},WORKTREE_COMMIT:{fields:[w("worktreeId","Worktree","worktree"),m("message","Commit message",{required:!0}),g("signed","Signed commit"),g("stageAll","Stage all",{default:!0}),I("paths","Selected paths")]},WORKTREE_REFRESH_PULL_REQUEST:{fields:[w("worktreeId","Worktree","worktree")]},WORKTREE_OPERATION:{fields:[w("worktreeId","Worktree","worktree"),y("operation","Operation",_),g("forcePreparations","Force preparation conflicts",{help:"Destructively resets preparation-managed paths before Sync or Rebase, then reapplies the current rules."})]},WORKTREE_PREPARATION:{fields:[w("worktreeId","Worktree","worktree"),y("action","Action",o(a.WORKTREE_PREPARATION_ACTIONS))]},WORKTREE_SET_AUTO_SYNC:{fields:[w("worktreeId","Worktree","worktree"),y("action","Action",o(["ENABLE","RETRY","FORCE","CANCEL"])),p("conflictWorkflowId","Conflict workflow ID"),p("conflictWorkflowChoice","Conflict workflow choice")]},WORKTREE_SET_AUTO_MERGE:{fields:[w("worktreeId","Worktree","worktree"),y("action","Action",o(["ENABLE","RETRY","CANCEL"])),p("repositoryNameWithOwner","Repository",{placeholder:"owner/repository"}),f("pullRequestNumber","Pull request number"),y("method","Merge method",o(["MERGE","REBASE","SQUASH"])),p("commitHeadline","Commit headline"),m("commitBody","Commit body"),p("authorEmail","Author email"),g("deleteWorktree","Delete worktree after merge"),g("moveTicketToDone","Move Jira ticket to done")]},WORKTREE_DELETE:{fields:[w("worktreeId","Worktree","worktree"),g("deleteRemoteBranch","Delete remote branch")]},WORKTREE_MOVE:{fields:[w("worktreeId","Source worktree","worktree"),w("targetCodebaseId","Target codebase","codebase",{required:!0}),w("targetWorktreeId","Target worktree","worktree"),g("deleteSource","Delete source")]},WORKTREE_INSPECT:{fields:[w("worktreeId","Worktree","worktree")]},WORKTREE_INSPECT_GIT:{fields:[w("worktreeId","Worktree","worktree")]},WORKTREE_GIT_OPERATION:{fields:[w("worktreeId","Worktree","worktree"),y("operation","Operation",o(a.WORKTREE_GIT_OPERATIONS)),p("branch","Branch"),p("stashOid","Stash OID"),g("stashChanges","Stash changes first")]},WORKTREE_WAIT_PUSH_READY:{fields:[w("worktreeId","Worktree","worktree")]},WORKTREE_SNAPSHOT:{fields:[p("kind","Checkpoint kind",{placeholder:"STEP"})]},CODEBASE_FETCH_REFRESH:{fields:[w("codebaseId","Codebase","codebase"),y("operation","Operation",o(["FETCH","REFRESH"]))]},CODEBASE_INSPECT_GIT:{fields:[w("codebaseId","Codebase","codebase")]},CODEBASE_GIT_OPERATION:{fields:[w("codebaseId","Codebase","codebase"),y("operation","Operation",o(i.CODEBASE_GIT_OPERATIONS)),p("branch","Branch"),p("stashOid","Stash OID"),g("stashChanges","Stash changes first")]},BUILD_START:{fields:[w("worktreeId","Worktree","worktree"),p("configurationId","Build configuration ID",{required:!0}),y("action","Action",o(r.BUILD_ACTIONS)),I("destination","Destination"),b("scriptIds","Build scripts","buildScript"),I("advancedSettings","Advanced settings"),g("exportWhenComplete","Export when complete"),I("exportSettings","Export settings"),g("worktreeCoverage","Collect worktree coverage")]},BUILD_READ_TEST_RESULTS:{fields:[p("buildId","Build ID")]},BUILD_READ_COVERAGE:{fields:[p("buildId","Build ID")]},BUILD_IMPORT_COVERAGE:{fields:[w("worktreeId","Worktree","worktree"),p("buildName","Build name",{default:"{{workflow.name}}",help:"Name shown on the build and coverage pages. Defaults to the workflow name."}),p("reportPath","Coverage file",{required:!0,default:"coverage/lcov.info",help:"Path inside the worktree, written by whichever test command ran first."}),y("format","Coverage format",o(["AUTO","LCOV","ISTANBUL"]))]},BUILD_EXPORT:{fields:[p("buildId","Build ID"),I("settings","Export settings",{required:!0})]},BUILD_DEPLOY:{fields:[p("buildId","Build ID"),I("destinations","Destinations")]},BUILD_CANCEL:{fields:[p("buildId","Build ID")]},DISK_SPACE_LOAD:{fields:[w("agentId","Agent","agent")]},DISK_SPACE_REFRESH:{fields:[w("agentId","Agent","agent")]},DISK_SPACE_UPDATE_THRESHOLDS:{fields:[f("normalThresholdGiB","Normal threshold (GiB)",{required:!0}),f("pressureThresholdGiB","Pressure threshold (GiB)",{required:!0})]},DISK_SPACE_SET_MONITORING:{fields:[w("agentId","Agent","agent"),g("enabled","Monitoring enabled",{required:!0,default:!0})]},DISK_SPACE_SET_PRESSURE_MODE:{fields:[w("agentId","Agent","agent"),g("enabled","Manual pressure mode",{required:!0,default:!0})]},SKILL_APPLY:{fields:[w("groupId","Skill group","skillGroup",{help:"Leave empty to sync all skills."})]},NOTIFICATION_SEND:{fields:[p("title","Title",{required:!0}),m("body","Body",{required:!0}),p("href","Link")]},IOS_PUSH_SEND:{fields:[y("targetMode","Target mode",o(["ALL","DEVICES","BROADCAST","DIRECT"])),b("registrationIds","Registrations","apnsRegistration"),w("channelId","Broadcast channel","apnsChannel"),I("editor","Notification editor"),p("directToken","Direct device token"),y("directTokenEncoding","Token encoding",o(["HEX","BASE64"])),y("directEnvironment","Environment",o(["SANDBOX","PRODUCTION"]))]},COMMAND_RERUN:{fields:[p("commandRunId","Command run ID",{required:!0})]},COMMAND_TERMINATE:{fields:[p("commandRunId","Command run ID",{required:!0})]},COMMAND_READ_OUTPUT:{fields:[p("commandRunId","Command run ID",{required:!0}),f("first","Maximum chunks")]},WORKTREE_INSPECT_DIFF:{fields:[p("worktreeId","Worktree ID"),p("scope","Diff scope",{required:!0}),p("path","Path"),p("previousPath","Previous path"),p("commitSha","Commit SHA")]},WORKTREE_UPDATE_METADATA:{fields:[p("worktreeId","Worktree ID"),p("baseBranch","Base branch"),p("highlightColor","Highlight color")]},WORKTREE_MOVE_CONTROL:{fields:[p("moveId","Move ID",{required:!0}),y("operation","Operation",o(["RETRY_WITH_STASH","CANCEL"]))]},BUILD_REBUILD:{fields:[p("buildId","Build ID")]},BUILD_GENERATE_REPORT:{fields:[p("buildId","Build ID"),y("reportKind","Report kind",o(["TEST_RESULTS","CODE_COVERAGE"]))]},BUILD_DELETE:{fields:[E("buildIds","Build IDs")]},SKILL_PREPARE_SYNC:{fields:[y("syncKind","Sync kind",o(["ALL","GROUP"])),p("groupId","Skill group ID")]},SKILL_RESOLVE_SYNC:{fields:[p("runId","Sync run ID",{required:!0}),p("itemId","Conflict item ID",{required:!0}),y("resolution","Resolution",o(["LOCAL","REMOTE","SKIP"]))]},SKILL_SKIP_SYNC:{fields:[p("runId","Sync run ID",{required:!0})]},BUILD_DATA_REFRESH:{fields:[]},BUILD_DATA_DELETE:{fields:[p("collectionId","Collection ID",{required:!0}),E("entryIds","Entry IDs"),g("overrideProtection","Override protection")]},BUILD_DATA_SET_LOCK:{fields:[p("collectionId","Collection ID",{required:!0}),p("entryId","Entry ID",{required:!0}),g("locked","Locked")]},TAILSCALE_SERVE_INSPECT:{fields:[b("agentIds","Agents","agent")]},TAILSCALE_SERVE_UPSERT_TEMPLATE:{fields:[p("templateId","Template ID"),f("expectedRevision","Expected revision",{minimum:1,integer:!0}),p("name","Template name",{required:!0}),y("protocol","Listener protocol",o(["HTTP","HTTPS","TCP","TLS_TERMINATED_TCP"]),{required:!0,default:"HTTPS"}),f("listenPort","Incoming port",{required:!0,default:443,minimum:1,maximum:65535,integer:!0}),p("mountPath","Mount path",{default:"/"}),y("destinationProtocol","Destination protocol",o(["HTTP","HTTPS","HTTPS_INSECURE","TCP"]),{required:!0,default:"HTTP"}),f("destinationPort","Destination port",{required:!0,default:3e3,minimum:1,maximum:65535,integer:!0}),p("destinationPath","Destination path",{default:""}),g("funnel","Public Funnel"),E("appCapabilities","App capabilities"),y("proxyProtocol","PROXY protocol",o(["NONE","V1","V2"]),{required:!0,default:"NONE"}),b("agentIds","Enabled agents","agent",{required:!0})]},TAILSCALE_SERVE_SET_AGENT_ENABLED:{fields:[p("templateId","Template ID",{required:!0}),w("agentId","Agent","agent",{required:!0}),g("enabled","Enabled"),f("expectedRevision","Expected revision",{required:!0})]},TAILSCALE_SERVE_DELETE_TEMPLATE:{fields:[p("templateId","Template ID",{required:!0}),f("expectedRevision","Expected revision",{required:!0})]},SIGNING_REFRESH:{fields:[E("agentIds","Agent IDs")]},SIGNING_SYNC_PROFILE:{fields:[p("uuid","Profile UUID",{required:!0}),p("sourceAgentId","Source agent ID",{required:!0}),E("targetAgentIds","Target agent IDs")]},SIGNING_DELETE_EXPIRED:{fields:[E("agentIds","Agent IDs")]},IOS_DEVICE_REGISTER:{fields:[p("deviceId","Device ID",{required:!0})]},IOS_DEVICE_REJECT:{fields:[p("deviceId","Device ID",{required:!0})]},AGENT_RECONCILE:{fields:[E("agentIds","Agent IDs")]},AGENT_UPDATE_CADENCE:{fields:[p("agentId","Agent ID",{required:!0}),I("settings","Cadence settings")]},CCUSAGE_COLLECT:{fields:[]},MODEL_COST_REFRESH:{fields:[]},GITHUB_UPDATE_PR:{fields:[p("owner","Owner",{required:!0}),p("name","Repository",{required:!0}),f("number","Pull request number",{required:!0}),p("title","Title"),m("body","Body"),g("draft","Draft")]},GITHUB_SUBMIT_REVIEW:{fields:[p("owner","Owner",{required:!0}),p("name","Repository",{required:!0}),f("number","Pull request number",{required:!0}),y("event","Review event",o(["APPROVE","REQUEST_CHANGES","COMMENT"])),m("body","Body")]},GITHUB_REQUEST_REVIEWERS:{fields:[p("owner","Owner",{required:!0}),p("name","Repository",{required:!0}),f("number","Pull request number",{required:!0}),E("reviewers","Reviewers"),E("teamReviewers","Team reviewers")]},GITHUB_DISPATCH_WORKFLOW:{fields:[p("repositoryId","Repository ID",{required:!0}),p("workflowId","Workflow ID",{required:!0}),p("ref","Git ref",{required:!0}),v("inputs","Workflow inputs")]},JIRA_CREATE_TICKET:{fields:[p("projectKey","Project key",{required:!0}),p("issueTypeId","Issue type ID",{required:!0}),p("summary","Summary",{required:!0}),m("description","Description"),I("fields","Additional fields")]},JIRA_ADD_WORKLOG:{fields:[p("issueKey","Issue key"),f("timeSpentSeconds","Time spent (seconds)",{required:!0}),p("startedAt","Started at"),m("comment","Comment")]},JIRA_LINK_TICKETS:{fields:[p("inwardIssueKey","Inward issue key",{required:!0}),p("outwardIssueKey","Outward issue key",{required:!0}),p("linkType","Link type",{required:!0})]},MCP_CALL:{fields:[w("groupId","MCP server","mcpServer",{required:!0}),p("name","Tool name",{required:!0}),I("arguments","Arguments")]},SSE_ENDPOINT_ACTION:{fields:[y("operation","Operation",o(["CREATE","UPDATE","SET_MODE","ROTATE_TOKEN","DELETE"]),{required:!0}),p("endpointId","Endpoint ID"),I("input","Endpoint input")]},SSE_MOCK_ACTION:{fields:[y("operation","Operation",o(["SAVE_TEMPLATE","DELETE_TEMPLATE","SAVE_COMPOSITION","ACTIVATE_COMPOSITION","DELETE_COMPOSITION"]),{required:!0}),p("endpointId","Endpoint ID"),p("resourceId","Template or composition ID"),I("input","Mock input")]},SSE_STORAGE_ACTION:{fields:[y("operation","Operation",o(["SET","COMPARE_AND_SET","INCREMENT","DELETE"]),{required:!0}),p("key","Storage key",{required:!0}),I("value","JSON value"),f("expectedVersion","Expected version"),f("delta","Increment amount")]},SSE_BREAKPOINT_RESOLVE:{fields:[p("breakpointId","Breakpoint ID",{required:!0}),f("version","Version",{required:!0,integer:!0}),y("resolution","Resolution",o(["FORWARD","SAVED_MOCK","AD_HOC"]),{required:!0}),p("mockCompositionId","Mock composition ID"),I("adHocComposition","Ad hoc composition")]},SSE_HISTORY_CLEAR:{fields:[p("endpointId","Endpoint ID"),E("ids","Request IDs")]},SSE_SCRIPT_TEST:{fields:[m("source","JavaScript",{required:!0}),I("context","Script context"),f("timeoutMs","Timeout (ms)",{integer:!0}),f("memoryLimitMb","Memory limit (MiB)",{integer:!0}),f("fetchTimeoutMs","Fetch timeout (ms)",{integer:!0})]},RUN_CREATE_PLAN:{fields:C("PLAN")},RUN_CREATE_SESSION:{fields:C("SESSION")},RUN_PLAY_PLAN:{fields:[p("runId","Plan run ID"),S("SESSION"),f("worktreeConcurrencyLimit","Worktree concurrency limit",{default:1,minimum:0,maximum:32,integer:!0,help:"Maximum sessions admitted on this worktree. Use 0 for unlimited."})]},RUN_FOLLOW_UP:{fields:[p("runId","Source run ID"),...C(null),y("followUpMode","Follow-up mode",o(["RESUME","FRESH","RESEND"])),p("contextMode","Context mode")]},RUN_STEER:{fields:[p("runId","Run ID"),m("prompt","Steering prompt",{required:!0}),E("attachmentIds","Attachment IDs")]},RUN_ANSWER:{fields:[p("batchId","Question batch ID",{required:!0}),I("answers","Answers")]},RUN_PAUSE:{fields:[p("runId","Run ID")]},RUN_CONTINUE:{fields:[p("runId","Run ID")]},RUN_CANCEL:{fields:[p("runId","Run ID")]},RUN_REVISE_ANSWER:{fields:[p("batchId","Question batch ID",{required:!0}),I("answers","Answers"),g("stash","Stash before revision"),g("rollback","Roll back to the question")]},RUN_READ_RESULT:{fields:[p("runId","Run ID")]},RUN_CAPTURE_CHECKPOINT:{fields:[p("runId","Run ID")]},RUN_ARCHIVE_DELETE:{fields:[p("runId","Run ID"),g("delete","Delete permanently"),g("archived","Archive")]},HUMAN_CONFIRM:{fields:[m("prompt","Prompt")]},HUMAN_CHOICE:{fields:[m("prompt","Prompt"),g("multiSelect","Allow multiple selections"),g("allowCustom","Allow a custom answer"),((e,t,r={})=>({key:e,label:t,control:"choiceOptions",valueModes:h,...r}))("options","Buttons")]},CONTROL_IF:{fields:[((e,t,r={})=>({key:e,label:t,control:"condition",valueModes:h,...r}))("condition","Condition",{required:!0})]},CONTROL_JOIN:{fields:[y("mode","Join mode",l([{value:"ALL",label:"All — wait for every branch"},{value:"ANY",label:"Any — continue on the first branch"}]),{help:"All (default) waits until every incoming branch has finished before continuing. Any continues as soon as the first incoming branch arrives, and the remaining branches keep running on their own. Either way, branches that were skipped do not block the join, and the join itself is skipped when no branch reaches it."})]},CONTROL_DELAY:{fields:[f("seconds","Delay (seconds)",{required:!0})]},CONTROL_WAIT_UNTIL:{fields:[I("condition","Condition",{required:!0})]},CONTROL_FOR_EACH:{fields:[p("listPath","List session path",{placeholder:"pr.unresolvedThreads"}),I("items","Inline items"),y("errorMode","Error handling",l([{value:"FAIL_FAST",label:"Fail fast"},{value:"COLLECT_ERRORS",label:"Collect errors"}]))]},CONTROL_TRY:{fields:[]},CONTROL_SET_VARIABLE:{fields:[p("path","Output path",{required:!0,placeholder:"flags.ready"}),I("value","Value"),m("script","Script")]},CONTROL_SUBWORKFLOW:{fields:[p("versionId","Sub-workflow version ID",{required:!0}),I("inputMapping","Input mapping")]},SAVED_COMMAND:{fields:[w("commandId","Saved command ID","savedCommand",{required:!0}),y("completionMode","Completion",o(["WAIT_FOR_EXIT","FIRE_AND_FORGET"])),y("targetMode","Target",o(["CONTEXT","FIXED_AGENT","FIXED_WORKTREE"])),p("agentId","Fixed agent ID",{visibleWhen:{key:"targetMode",equals:"FIXED_AGENT"}}),p("worktreeId","Fixed worktree ID",{visibleWhen:{key:"targetMode",equals:"FIXED_WORKTREE"}}),p("outputPattern","Output match pattern (RE2)",{placeholder:"ready on port ([0-9]+)",help:"Optional case-sensitive regex. Requires Wait for exit and emits through the match connector while the command runs.",valueModes:["literal"]}),y("outputMatchMode","Output match behavior",o(["ONCE","EACH_MATCH"]),{default:"ONCE"})]},CUSTOM_COMMAND:{fields:[m("script","Script",{required:!0}),y("completionMode","Completion",o(["WAIT_FOR_EXIT","FIRE_AND_FORGET"])),y("targetMode","Target",o(["CONTEXT","FIXED_AGENT","FIXED_WORKTREE"])),p("agentId","Fixed agent ID",{visibleWhen:{key:"targetMode",equals:"FIXED_AGENT"}}),p("worktreeId","Fixed worktree ID",{visibleWhen:{key:"targetMode",equals:"FIXED_WORKTREE"}}),p("outputPattern","Output match pattern (RE2)",{placeholder:"ready on port ([0-9]+)",help:"Optional case-sensitive regex. Requires Wait for exit and emits through the match connector while the command runs.",valueModes:["literal"]}),y("outputMatchMode","Output match behavior",o(["ONCE","EACH_MATCH"]),{default:"ONCE"})]},TERMINAL_RUN:{fields:[m("script","Script",{required:!0}),y("interpreter","Interpreter",o(["SHELL","NODE"])),v("environment","Environment variables"),I("credentials","Credential environment",{help:"JSON array of { name, credential: { id, kind, ownerId } } entries."})]}},N=()=>f("timeoutSeconds","Timeout (seconds)",{help:"How long to keep waiting before the step fails. Leave empty to wait for as long as the work takes."});function O(e,t){for(let r of e){let e=R[r];if(!e)continue;let i=new Set(e.fields.map(({key:e})=>e));e.fields=[...e.fields,...t().filter(({key:e})=>!i.has(e))]}}function D(e=[]){return{fields:[...e,v("filters","Filters",{help:"Match when each session path equals the given value.",recordValueType:"json"})]}}O(["WORKTREE_CREATE","WORKTREE_CHANGE_BRANCH","WORKTREE_OPERATION","WORKTREE_PREPARATION","WORKTREE_SET_AUTO_SYNC","WORKTREE_DELETE","WORKTREE_GIT_OPERATION","WORKTREE_MOVE","WORKTREE_WAIT_PUSH_READY","WORKTREE_SNAPSHOT","CODEBASE_FETCH_REFRESH","CODEBASE_GIT_OPERATION","BUILD_START","BUILD_IMPORT_COVERAGE","BUILD_EXPORT","BUILD_DEPLOY","DISK_SPACE_REFRESH","TERMINAL_RUN","RUN_CREATE_PLAN","RUN_CREATE_SESSION","RUN_PLAY_PLAN","RUN_FOLLOW_UP","RUN_REVISE_ANSWER","SAVED_COMMAND","CUSTOM_COMMAND","COMMAND_RERUN","BUILD_REBUILD","BUILD_DATA_REFRESH","TAILSCALE_SERVE_INSPECT","TAILSCALE_SERVE_UPSERT_TEMPLATE","TAILSCALE_SERVE_SET_AGENT_ENABLED","TAILSCALE_SERVE_DELETE_TEMPLATE","SIGNING_REFRESH","SIGNING_SYNC_PROFILE","SIGNING_DELETE_EXPIRED","SKILL_APPLY","GITHUB_WAIT_CHECKS","GITLAB_WAIT_PIPELINE","CONTROL_SUBWORKFLOW","CONTROL_WAIT_UNTIL"],()=>[f("cadenceSeconds","Poll cadence (seconds)",{help:"How often to check whether the work has finished. Leave empty for this step's default."}),N()]),O(["HUMAN_CONFIRM","HUMAN_CHOICE"],()=>[N()]);let P=["BUILD_TEST_THRESHOLD","BUILD_COVERAGE_THRESHOLD","AGENT_DISK_THRESHOLD","CCUSAGE_THRESHOLD","RUN_USAGE_THRESHOLD","BUILD_DATA_THRESHOLD","AGENT_RESOURCE_THRESHOLD","SIGNING_ASSET_EXPIRING"],x=Object.fromEntries(["MANUAL","MANUAL_CHOICE","RESOURCE_MANUAL","RESOURCE_MANUAL_CHOICE","SCHEDULE","WORKFLOW_FINISHED","GITHUB_PR_STATE","GITHUB_REVIEW_CHANGES_REQUESTED","GITHUB_REVIEW_COMMENT","GITHUB_PR_CLOSED","GITHUB_CHECK_FAILED","GITHUB_PUSH_DEFAULT","GITHUB_WORKFLOW_SUCCEEDED","GITHUB_ISSUE_COMMAND","GITHUB_ACTIONS_RESULT","GITHUB_PR_LABEL","GITLAB_MR_STATE","GITLAB_REVIEW_CHANGES_REQUESTED","GITLAB_REVIEW_COMMENT","GITLAB_MR_CLOSED","GITLAB_PIPELINE_FAILED","GITLAB_PUSH_DEFAULT","GITLAB_PIPELINE_SUCCEEDED","GITLAB_NOTE_COMMAND","GITLAB_PIPELINE_RESULT","GITLAB_MR_LABEL","BUILD_RESULT","BUILD_TEST_THRESHOLD","BUILD_COVERAGE_THRESHOLD","BUILD_HOOK_FAILED","AGENT_CONNECTION","AGENT_JOB_FAILED","AGENT_DISK_REPORT","AGENT_DISK_THRESHOLD","AGENT_DISK_STATE_CHANGED","AGENT_DISK_CLEANUP_RESULT","CCUSAGE_THRESHOLD","WORKTREE_CREATED","WORKTREE_BEHIND","WORKTREE_CONFLICT","WORKTREE_MISSING","WORKTREE_DIVERGED","WORKTREE_DIRTY_DURATION","WORKTREE_NEW_COMMIT","CODEBASE_REMOTE_BRANCH","JIRA_STATUS","JIRA_LABEL","JIRA_ASSIGNED_SELF","JIRA_SOURCE_NEW_TICKET","JIRA_MENTION","JIRA_SPRINT_STARTED","JIRA_ISSUE_CREATED","JIRA_ISSUE_DELETED","JIRA_ISSUE_COMMAND","JIRA_ATTACHMENT_ADDED","JIRA_ISSUE_LINKED","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","COMMAND_RUN_RESULT","COMMAND_OUTPUT_MATCH","SKILL_SYNC_RESULT","SKILL_SYNC_CONFLICT","GITHUB_PIPELINE_STATUS_CHANGED","GITHUB_PR_SYNCHRONIZED","GITHUB_REVIEW_APPROVED","GITLAB_PIPELINE_STATUS_CHANGED","GITLAB_MR_SYNCHRONIZED","GITLAB_REVIEW_APPROVED","GITLAB_JOB_STATUS_CHANGED","JIRA_TICKET_UPDATED","JIRA_COMMENT_ADDED","JIRA_WORKLOG_ADDED","JIRA_SPRINT_ENDED","CODEBASE_SYNC_STATE_CHANGED","CODEBASE_OPERATION_FAILED","WORKTREE_SYNC_STATE_CHANGED","WORKTREE_AUTOMATION_RESULT","WORKTREE_CLEAN","PUSH_NOTIFICATION_RESULT","IOS_DEVICE_ENROLLED","IOS_DEVICE_REGISTRATION_RESULT","SIGNING_OPERATION_RESULT","SIGNING_ASSET_EXPIRING","BUILD_DATA_THRESHOLD","BUILD_DATA_CLEANUP_RESULT","POLLING_OPERATION_STATE","MODEL_COST_CATALOG_CHANGED","CREDENTIAL_STORE_DEGRADED","AGENT_RESOURCE_THRESHOLD","AGENT_VERSION_CHANGED","TOOL_CALL_RESULT","SSE_REQUEST_OPENED","SSE_EVENT_EMITTED","SSE_BREAKPOINT_WAITING","SSE_BREAKPOINT_RESOLVED","SSE_STREAM_COMPLETED","SSE_STREAM_FAILED"].map(e=>{if("RESOURCE_MANUAL"===e||"RESOURCE_MANUAL_CHOICE"===e)return[e,D([y("resourceKind","Resource kind",o(n.WORKFLOW_RESOURCE_KINDS),{required:!0}),..."RESOURCE_MANUAL_CHOICE"===e?[A("choices","Choices",{required:!0})]:[]])];if("MANUAL_CHOICE"===e)return[e,D([A("choices","Choices",{required:!0})])];if("SCHEDULE"===e)return[e,D([f("cadenceSeconds","Cadence (seconds)",{required:!0})])];if("GITHUB_ISSUE_COMMAND"===e||"GITLAB_NOTE_COMMAND"===e){let t="GITLAB_NOTE_COMMAND"===e;return[e,D([E(t?"allowedUsernames":"allowedLogins",t?"Allowed usernames":"Allowed logins",{placeholder:"octocat",required:!0}),p("commandPattern","Command pattern (RE2)",{placeholder:"^/deploy\\b$",required:!0,valueModes:["literal","interpolation"]})])]}return"JIRA_ISSUE_COMMAND"===e?[e,D([E("allowedAccountIds","Allowed account IDs",{placeholder:"5b10a2844c20165700ede21g",required:!0}),p("commandPattern","Command pattern (RE2)",{placeholder:"^/deploy\\b$",required:!0,valueModes:["literal","interpolation"]})])]:"COMMAND_OUTPUT_MATCH"===e?[e,D([p("outputPattern","Output pattern (RE2)",{placeholder:"error|failed",required:!0,valueModes:["literal","interpolation"]})])]:P.includes(e)?[e,D([p("thresholdPath","Threshold path",{placeholder:"build.testSummary.failed"}),y("thresholdOperator","Operator",k),I("thresholdValue","Threshold value")])]:[e,D()]}));function L(e,t){return"step"===t?R[e]:x[e]}function U(e,t,r){let i=function(e,t){let r=L(e,t);if(!r)return null;let i=new Set,a=new Set;for(let e of r.fields){for(let t of"model"===e.control&&e.modelKeys?[e.modelKeys.provider,e.modelKeys.model,e.modelKeys.effort]:[e.key])i.add(t);e.required&&a.add(e.key)}return{described:i,required:a}}(e,t);if(!i||!r||"object"!=typeof r||Array.isArray(r))return(0,s.workflowValueSessionPaths)(r);let a=new Set;for(let[e,t]of Object.entries(r))(!i.described.has(e)||i.required.has(e))&&(0,s.workflowValueSessionPaths)(t,a);return a}e.s(["getConfigDescriptor",0,L,"requiredConfigSessionPaths",0,U],248626);let B=["EQ","NE","GT","GTE","LT","LTE","CONTAINS","MATCHES","EXISTS"],M={type:"object",title:"Session binding",description:"Reads the value from run session data at `path` instead of hard-coding it.",properties:{source:{const:"SESSION"},path:{type:"string",description:"Dotted session path, e.g. `ticket.key` or `pr.number`."}},required:["source","path"],additionalProperties:!1},q={type:"object",title:"Literal wrapper",description:"An explicit constant. Equivalent to writing the value directly; the editor uses it to record that a field was pinned rather than bound.",properties:{source:{const:"LITERAL"},value:{}},required:["source"],additionalProperties:!1};function j(e,t,r){let i=r.valueModes??[],a=[i.includes("session")?"May also be a session binding.":null,i.includes("interpolation")?"Strings here — including strings nested inside the value — may carry `{{path}}` interpolation tokens, e.g. `{{worktree.baseBranch}}`.":null].filter(Boolean),n=a.length?{...t,description:[t.description,...a].filter(Boolean).join(" ")}:t;return i.includes("session")?{anyOf:[e,M,q],...n}:{...e,...n}}function $(e){let t=e.options?function(e){if("static"===e.kind){let t=e.options.filter(({label:e})=>e);return t.length?t.map(({value:e,label:t})=>`\`${e}\` — ${t}`).join("; "):null}let t=e.scopeFrom?` Scoped by the sibling \`${e.scopeFrom}\` value.`:"",r=e.sessionPath?` Usually bound to \`${e.sessionPath}\`.`:"";return`Identifier of a ${e.resource} known to the control plane.${r}${t}`}(e.options):null,r={description:[e.label,e.help,t].filter(Boolean).join(" — ")};return e.placeholder&&(r.examples=[e.placeholder]),void 0!==e.default&&(r.default=e.default),j(function(e){switch(e.control){case"number":return{type:e.integer?"integer":"number",...void 0===e.minimum?{}:{minimum:e.minimum},...void 0===e.maximum?{}:{maximum:e.maximum}};case"boolean":return{type:"boolean"};case"enum":{let t=e.options;if(t?.kind==="static")return{type:"string",enum:t.options.map(({value:e})=>e)};return{type:"string"}}case"resource":case"model":case"text":default:return{type:"string"};case"resourceMulti":case"stringList":case"mcpPresetMulti":return{type:"array",items:{type:"string"}};case"record":return{type:"object",additionalProperties:"json"===e.recordValueType?{}:{type:"string"}};case"condition":return{$ref:"#/$defs/condition"};case"choiceOptions":return{type:"array",description:"Buttons offered to the person answering.",items:{type:"object",properties:{label:{type:"string"},description:{type:"string"}},required:["label"],additionalProperties:!1}};case"triggerChoices":return{type:"array",minItems:1,description:"Options this trigger offers. Each `key` names an outgoing handle on the trigger, so edges stay attached when a label is renamed.",items:{type:"object",properties:{key:{type:"string",pattern:n.WORKFLOW_CHOICE_KEY_PATTERN.source},label:{type:"string"},description:{type:"string"}},required:["key","label"],additionalProperties:!1}};case"json":return{}}}(e),r,e)}function G(e,t){let r=L(e,t);if(!r)return{type:"object",additionalProperties:!0};let i={},a=[],n=!1;for(let e of r.fields){for(let[t,r]of("condition"===e.control&&(n=!0),"model"===e.control?function(e){let t=e.modelKeys;if(!t)return[[e.key,$(e)]];let r=(t,r)=>[t,j({type:"string"},{description:r},e)];return[r(t.provider,"AI provider that serves the model."),r(t.model,"Model identifier, as listed by the provider catalog."),r(t.effort,"Reasoning effort, when the model supports it.")]}(e):[[e.key,$(e)]]))i[t]=r;e.required&&a.push(e.key)}let s={type:"object",properties:i,additionalProperties:!0};return a.length&&(s.required=a),n&&(s.$defs={condition:{type:"object",description:"A condition tree. `ALL`/`ANY` combine nested conditions, `NOT` negates one, and the comparison operators test `left` against `right`.",anyOf:[{properties:{op:{enum:["ALL","ANY"]},conditions:{type:"array",items:{$ref:"#/$defs/condition"}}},required:["op","conditions"]},{properties:{op:{const:"NOT"},condition:{$ref:"#/$defs/condition"}},required:["op","condition"]},{properties:{op:{enum:[...B]},left:{description:"Value to test — usually a session binding. `EXISTS` needs only this side."},right:{description:"Value to compare against."}},required:["op","left"]}]}}),s}function F(e){let t=e?.outputPattern;return"string"==typeof t&&t.length?t:null}function z(e){if(!e.length)throw Error("Output pattern cannot be empty");if(e.length>1024)throw Error("Output pattern must not exceed 1024 characters")}e.s(["COMMAND_OUTPUT_MATCH_BUFFER_BYTES",0,0x1000000,"commandOutputMatchMode",0,function(e){return e?.outputMatchMode==="EACH_MATCH"?"EACH_MATCH":"ONCE"},"commandOutputPattern",0,F,"validateCommandOutputPattern",0,z],361617);let H="aide.workflow";function V(e){let t=e?.choices;if(!Array.isArray(t))return[];let r=[],i=new Set;for(let e of t)!(!e||"object"!=typeof e||Array.isArray(e))&&(!(0,n.isWorkflowChoiceKey)(e.key)||i.has(e.key)||(i.add(e.key),r.push({key:e.key,label:"string"==typeof e.label&&e.label.trim()?e.label:e.key,description:"string"==typeof e.description?e.description:""})));return r}let K={BUILD:["build.*","worktree.*","codebase.*","agent.*","repo.*","ticket.*"],CODEBASE:["codebase.*","agent.*","repo.*"],JIRA_TICKET:["ticket.*","comment.*"],AGENT_RUN:["run.*","worktree.*","codebase.*","agent.*","repo.*","ticket.*"],GITHUB_PIPELINE:["pipeline.*","repo.*","pr.*","worktree.*","codebase.*","agent.*","ticket.*"],GITHUB_JOB:["job.*","pipeline.*","repo.*","pr.*","worktree.*","codebase.*","agent.*","ticket.*"],GITLAB_MERGE_REQUEST:["pr.*","repo.*","worktree.*","ticket.*"],GITLAB_PIPELINE:["pipeline.*","repo.*","pr.*","worktree.*","ticket.*"],GITLAB_JOB:["job.*","pipeline.*","repo.*","pr.*","worktree.*","ticket.*"],PULL_REQUEST:["pr.number","repo.displayOrigin"],WORKTREE:["worktree.*","codebase.*","agent.*","repo.*","ticket.*","pr.*"],COMMAND_RUN:["command.*","agent.*","worktree.*","codebase.*","repo.*"],SKILL:["skill.*","repo.*","codebase.*"],SKILL_SYNC:["skillSync.*","skill.*","repo.*","codebase.*","worktree.*"],IOS_DEVICE:["device.*"],SIGNING_PROFILE:["signingProfile.*","device.*","agent.*"],PUSH_NOTIFICATION_BATCH:["pushBatch.*"],BUILD_DATA_COLLECTION:["buildData.*","agent.*","worktree.*","codebase.*"]};function W(e){let t=e?.resourceKind;return"string"==typeof t&&n.WORKFLOW_RESOURCE_KINDS.includes(t)?t:null}function J(e,t){if(!(0,n.isResourceTriggerKind)(e))return[];let r=W(t);return r?K[r]:[]}let Y=(e,t,r,i,a,s,o)=>({kind:e,category:t,label:r,description:o.description,details:o.details,execution:i,configSchema:G(e,"step"),capabilityFlags:[i,...o.mutatesExternal?["MUTATES_EXTERNAL"]:[],...o.mutatesWorktree?["MUTATES_WORKTREE"]:[]],requiredPaths:a,providedPaths:s,sourceHandles:(0,n.workflowStaticSourceHandles)(e),mutatesExternal:o.mutatesExternal??!1,mutatesWorktree:o.mutatesWorktree??!1}),Q=["worktree.*","codebase.*","agent.*","repo.*","ticket.*","pr.*"],Z=["codebase.*","agent.*","repo.*"],X=(e,t,r,i=[],a=["steps.<stepId>.*"],n={})=>Y(e,t,r,"SERVER",i,a,{description:`${r} using the control plane's typed service API.`,details:`${r} is a first-class action with validated configuration, audit-friendly output, resource links where available, and normal workflow failure routing.`,...n}),ee=[X("COMMAND_RERUN","Commands","Rerun command",["command.id"],["command.*"]),X("COMMAND_TERMINATE","Commands","Terminate command",["command.id"],["command.*"]),X("COMMAND_READ_OUTPUT","Commands","Read command output",["command.id"],["command.*"]),X("WORKTREE_INSPECT_DIFF","Worktrees","Inspect worktree diff",["worktree.id"],["worktree.diff.*"]),X("WORKTREE_UPDATE_METADATA","Worktrees","Update worktree metadata",["worktree.id"],Q),X("WORKTREE_MOVE_CONTROL","Worktrees","Control worktree move",[],Q,{mutatesWorktree:!0}),X("BUILD_REBUILD","Builds","Rebuild build",["build.id"],["build.*"]),X("BUILD_GENERATE_REPORT","Builds","Generate build report",["build.id"],["build.*"]),X("BUILD_DELETE","Builds","Delete builds",[],["build.*"]),X("SKILL_PREPARE_SYNC","Skills","Prepare skill sync",[],["skillSync.*"]),X("SKILL_RESOLVE_SYNC","Skills","Resolve skill sync conflict",["skillSync.id"],["skillSync.*"]),X("SKILL_SKIP_SYNC","Skills","Skip skill sync",["skillSync.id"],["skillSync.*"]),X("BUILD_DATA_REFRESH","Build Data","Refresh build data",[],["buildData.*"]),X("BUILD_DATA_DELETE","Build Data","Delete build data",["buildData.id"],["buildData.*"]),X("BUILD_DATA_SET_LOCK","Build Data","Set build-data lock",["buildData.id"],["buildData.*"]),X("TAILSCALE_SERVE_INSPECT","Tailscale","Inspect Tailscale Serve",[],["tailscale.*"],{mutatesExternal:!0}),X("TAILSCALE_SERVE_UPSERT_TEMPLATE","Tailscale","Upsert Tailscale Serve template",[],["tailscale.*"],{mutatesExternal:!0}),X("TAILSCALE_SERVE_SET_AGENT_ENABLED","Tailscale","Set Tailscale Serve agent enabled",["tailscale.templateId"],["tailscale.*"],{mutatesExternal:!0}),X("TAILSCALE_SERVE_DELETE_TEMPLATE","Tailscale","Delete Tailscale Serve template",["tailscale.templateId"],["tailscale.*"],{mutatesExternal:!0}),X("SIGNING_REFRESH","Signing","Refresh signing assets",[],["signing.*"]),X("SIGNING_SYNC_PROFILE","Signing","Sync signing profile",["signingProfile.id"],["signing.*"]),X("SIGNING_DELETE_EXPIRED","Signing","Delete expired profiles",[],["signing.*"]),X("IOS_DEVICE_REGISTER","Devices","Register iOS device",["device.id"],["device.*"],{mutatesExternal:!0}),X("IOS_DEVICE_REJECT","Devices","Reject iOS device",["device.id"],["device.*"],{mutatesExternal:!0}),X("AGENT_RECONCILE","Agents","Reconcile agents",[],["agent.*"]),X("AGENT_UPDATE_CADENCE","Agents","Update agent cadence",["agent.id"],["agent.*"]),X("CCUSAGE_COLLECT","Operations","Collect usage",[],["usage.*"]),X("MODEL_COST_REFRESH","Operations","Refresh model costs",[],["modelCosts.*"],{mutatesExternal:!0}),X("GITHUB_UPDATE_PR","GitHub","Update pull request",["pr.number","repo.*"],["pr.*"],{mutatesExternal:!0}),X("GITHUB_SUBMIT_REVIEW","GitHub","Submit pull request review",["pr.number","repo.*"],["pr.*"],{mutatesExternal:!0}),X("GITHUB_REQUEST_REVIEWERS","GitHub","Request pull request reviewers",["pr.number","repo.*"],["pr.*"],{mutatesExternal:!0}),X("GITHUB_DISPATCH_WORKFLOW","GitHub","Dispatch GitHub workflow",["repo.*"],["pipeline.*"],{mutatesExternal:!0}),...[["GITLAB_LOAD_MR","Load merge request",!1],["GITLAB_CREATE_MR","Create merge request",!0],["GITLAB_UPDATE_MR","Update merge request",!0],["GITLAB_SUBMIT_REVIEW","Submit merge request review",!0],["GITLAB_REPLY_DISCUSSION","Reply to discussion",!0],["GITLAB_SET_DISCUSSION_RESOLVED","Resolve discussion",!0],["GITLAB_MERGE_MR","Merge merge request",!0],["GITLAB_SET_MR_LABELS","Set merge request labels",!0],["GITLAB_REQUEST_REVIEWERS","Request merge request reviewers",!0],["GITLAB_CREATE_PIPELINE","Create pipeline",!0],["GITLAB_RETRY_PIPELINE","Retry pipeline",!0],["GITLAB_RETRY_JOB","Retry job",!0],["GITLAB_CANCEL_PIPELINE","Cancel pipeline",!0]].map(([e,t,r])=>X(e,"GitLab",String(t),[],String(e).includes("PIPELINE")||String(e).includes("JOB")?["pipeline.*","job.*"]:["pr.*"],{mutatesExternal:!!r})),X("GITLAB_SAVE_AUTO_RETRY","GitLab Pipelines","Install auto-retry rule",["pipeline.id"],[],{mutatesExternal:!0}),X("GITLAB_WAIT_PIPELINE","GitLab Pipelines","Wait for pipeline",["pipeline.id"],["pipeline.*"]),X("JIRA_CREATE_TICKET","Jira","Create Jira ticket",[],["ticket.*"],{mutatesExternal:!0}),X("JIRA_ADD_WORKLOG","Jira","Add Jira worklog",["ticket.key"],["ticket.*"],{mutatesExternal:!0}),X("JIRA_LINK_TICKETS","Jira","Link Jira tickets",["ticket.key"],["ticket.*"],{mutatesExternal:!0})],et=[Y("JIRA_LOAD_TICKET","Jira","Load Jira ticket","SERVER",[],["ticket.*"],{description:"Reads a Jira issue and puts its fields — key, title, type, status, assignee, labels — into session data as `ticket.*`.",details:'Needs a configured Jira credential. Leave the identifier unset to take it from session data. Results are served from cache unless "Bypass cache" is set, so a step that reads a ticket right after changing it should force a refresh. Fails when the issue does not exist or the credential cannot see it. Read-only: it changes nothing in Jira.'}),Y("JIRA_TRANSITION","Jira","Transition Jira ticket","SERVER",["ticket.key"],["ticket.*"],{description:"Moves a ticket to another status by applying one of its workflow transitions.",details:"Takes a transition id, not a status name — the ids are board-specific, so read them from the ticket's available transitions rather than hard-coding a guess. Fails when the transition is not currently available on that issue, which is what happens if an earlier step already moved it. Refreshes `ticket.*` from the response.",mutatesExternal:!0}),Y("JIRA_COMMENT","Jira","Add Jira comment","SERVER",["ticket.key"],["ticket.*"],{description:"Posts a comment on a Jira issue, written in Markdown or Jira wiki markup.",details:"The comment body is converted from Markdown by default; choose Jira wiki format to pass markup through untouched. Comments are never deduplicated, so a step that runs twice comments twice — guard it with a condition if the workflow can retry. Refreshes `ticket.*` from the response.",mutatesExternal:!0}),Y("JIRA_ASSIGN","Jira","Assign Jira ticket","SERVER",["ticket.key"],["ticket.*"],{description:"Sets the assignee of a Jira issue, or clears it when no account is given.",details:"Takes a Jira account id rather than a display name or email. Leaving the assignee empty unassigns the ticket. Fails when the account cannot be assigned on that project. Refreshes `ticket.*` from the response.",mutatesExternal:!0}),Y("JIRA_UPDATE_FIELDS","Jira","Update Jira fields","SERVER",["ticket.key"],["ticket.*"],{description:"Patches arbitrary fields on a Jira issue — labels, summary, custom fields — from a JSON object.",details:"The escape hatch for anything the dedicated Jira steps do not cover. Keys are passed to the Jira update API as given, so an unknown or screen-hidden field fails the step. Prefer the specific steps for status and assignee. Refreshes `ticket.*` from the response.",mutatesExternal:!0}),Y("JIRA_RESOLVE_BRANCH","Jira","Resolve ticket branch","SERVER",["ticket.key","ticket.title","ticket.type"],["worktree.branch","ticket.key","ticket.title","ticket.type"],{description:"Works out the branch name a ticket would get under the codebase's naming convention, without creating anything.",details:"A preview step: it writes `worktree.branch` plus the ticket key, title, and type into session data and touches neither Git nor Jira. Use it before Create worktree when you want the branch name available to earlier steps — for a worktree keyed off a ticket, Create worktree in TICKET mode derives the same name on its own."}),Y("GITHUB_LOAD_PR","GitHub","Load pull request","SERVER",[],["pr.*"],{description:"Reads a pull request and puts its state, branches, labels, checks, and review threads into session data as `pr.*`.",details:"Needs a configured GitHub credential. Owner and repository default to the repository already in session data, and the number to `pr.number`. Fails when the pull request does not exist or the credential cannot see it. Read-only."}),Y("GITHUB_MERGE_PR","GitHub","Merge pull request","SERVER",["pr.number"],["pr.state"],{description:"Merges an open pull request using squash, merge, or rebase, optionally overriding the commit message.",details:"Checks mergeability first and fails with GitHub's own blocking reason — conflicts, failing required checks, missing approvals, an already-closed pull request — rather than forcing the merge. Commit headline and body default to what GitHub would use. Squash is the default method. Irreversible, and repository policy may delete the head branch as a side effect, which strands any worktree still on it. Writes `pr.state`.",mutatesExternal:!0}),Y("GITHUB_COLLECT_REVIEW_THREADS","GitHub","Collect review comments","SERVER",["pr.number"],["pr.unresolvedThreads"],{description:"Gathers the unresolved review threads on a pull request into `pr.unresolvedThreads`.",details:"Resolved threads are filtered out. The result is a list, so it pairs with For each to work through the comments one at a time — the reply and resolve steps take a single thread id from the iteration. Read-only."}),Y("GITHUB_REPLY_REVIEW_THREAD","GitHub","Reply to review thread","SERVER",["pr.unresolvedThreads"],[],{description:"Posts a reply into an existing pull request review thread.",details:"Takes the thread id from Collect review comments, usually inside a For each. Replies are not deduplicated, so a retried step comments twice. Replying does not resolve the thread — follow with Resolve review thread when that is the intent.",mutatesExternal:!0}),Y("GITHUB_SET_REVIEW_THREAD_RESOLVED","GitHub","Resolve review thread","SERVER",["pr.unresolvedThreads"],[],{description:"Marks a pull request review thread resolved, or reopens it.",details:"Takes the thread id from Collect review comments. Resolving is the default; clear the flag to unresolve. Reviewers see this as the bot resolving their comment, so it is usually paired with a reply that explains what changed.",mutatesExternal:!0}),Y("GITHUB_CREATE_PR","GitHub","Open pull request","SERVER",["worktree.branch","worktree.baseBranch"],["pr.*"],{description:"Opens a pull request from the worktree's branch, optionally as a draft.",details:"Head branch defaults to `worktree.branch`, base to `worktree.baseBranch`, and the title to `ticket.title`. The head branch must already be pushed — put Wait for push-ready or a push operation in front of this step. Fails when a pull request is already open for the same branch pair. Writes the new pull request to `pr.*`.",mutatesExternal:!0}),Y("GITHUB_SET_PR_LABELS","GitHub","Set pull request labels","SERVER",["pr.number"],["pr.labels"],{description:"Replaces the labels on a pull request with the given list.",details:"This sets rather than adds — labels not in the list are removed, so include the ones you want to keep. Labels must already exist in the repository. Writes `pr.labels`.",mutatesExternal:!0}),Y("GITHUB_RETRY_PIPELINE","GitHub Actions","Retry failed pipeline","SERVER",["pipeline.runId"],["pipeline.status"],{description:"Re-runs the failed jobs of a check suite, leaving the jobs that passed alone.",details:"Targets a check suite rather than a single job — use Retry workflow job for that. Re-running consumes Actions minutes and re-executes whatever those jobs do, including deployments. Pair it with a Time delay and a retry limit so a permanently broken pipeline is not retried forever. Writes `pipeline.status`.",mutatesExternal:!0}),Y("GITHUB_RETRY_JOB","GitHub Actions","Retry workflow job","SERVER",["pipeline.failedJobs"],[],{description:"Re-runs one job of a GitHub Actions workflow run.",details:"Needs the repository, check suite, and job ids together — typically read out of `pipeline.failedJobs` inside a For each. Use Retry failed pipeline to re-run every failed job at once instead.",mutatesExternal:!0}),Y("GITHUB_CANCEL_WORKFLOW_RUN","GitHub Actions","Cancel workflow run","SERVER",["pipeline.runId"],["pipeline.status"],{description:"Cancels an in-progress GitHub Actions workflow run.",details:"Falls back to `repo.id` and `pipeline.runId` from session data. Force-cancel skips the graceful shutdown that lets `always()` cleanup jobs finish, so leave it off unless a run is stuck. Cancelling a run that has already finished is an error. Writes `pipeline.status`.",mutatesExternal:!0}),Y("GITHUB_SAVE_AUTO_RETRY","GitHub Actions","Install auto-retry rule","SERVER",["pipeline.runId"],[],{description:"Saves a standing rule that automatically retries matching GitHub Actions failures.",details:"Persists configuration rather than acting once — the rule keeps applying after this run ends, and stays until something removes it. Takes the rule as a JSON object. Treat it as a settings change, not a step you re-run casually.",mutatesExternal:!0}),Y("GITHUB_WAIT_CHECKS","GitHub Actions","Wait for checks","WAIT",["pipeline.runId"],["pipeline.status","pipeline.conclusion","pipeline.jobs"],{description:"Parks the run until a GitHub Actions workflow run finishes, then continues on its conclusion.",details:"Polls until the run reaches a terminal status. Anything other than success fails the step, so route the failure handle to the recovery path — or set the step's failure policy to continue and branch on `pipeline.conclusion` yourself. Also refreshes `pipeline.jobs`. Without a timeout the wait is open-ended; a hung pipeline holds the workflow run indefinitely. Falls back to `repo.id` and `pipeline.runId`."}),Y("WORKTREE_CREATE","Worktrees","Create worktree","SERVER",["codebase.id"],Q,{description:"Creates a Git worktree on the agent for a new, existing, or ticket-derived branch.",details:"Dispatches a job to the agent that owns the codebase and waits for it, so the agent must be online. Branch mode NEW cuts a branch from the base, EXISTING checks one out, and TICKET derives the name from `ticket.key`. Base branch falls back to `worktree.baseBranch` then `repo.defaultBranch`. Refreshes the created worktree, codebase, owning agent, repository, and any linked ticket. Creates real directories on disk.",mutatesWorktree:!0}),Y("WORKTREE_CHANGE_BRANCH","Worktrees","Change worktree branch","SERVER",["worktree.id"],Q,{description:"Switches an existing worktree to a different branch, creating it if needed.",details:'Same branch modes as Create worktree. Uncommitted changes block the switch unless "Stash on failure" is set, which stashes them and retries — the stash is left for a human to deal with. Refreshes the worktree and all of its related resource context.',mutatesWorktree:!0}),Y("WORKTREE_COMMIT","Worktrees","Commit worktree changes","SERVER",["worktree.id"],Q,{description:"Stages selected worktree changes and creates a Git commit on the agent.",details:"Stage all defaults on. Disable it and provide an exact list of changed paths for a partial commit; paths omitted from that list are left uncommitted. Signed commits follow effective Git configuration when the signed option is omitted. Dispatches an agent job, waits for completion, and refreshes worktree context.",mutatesWorktree:!0}),Y("WORKTREE_REFRESH_PULL_REQUEST","Worktrees","Refresh pull request","SERVER",["worktree.id"],["pr.*"],{description:"Forces exact-branch pull request discovery and refreshes the worktree's persisted pull request context.",details:"Uses the configured worktree, falling back to `worktree.id`. The step succeeds with `found: false` and clears `pr` when the branch has no open pull request.",mutatesWorktree:!0,mutatesExternal:!1}),Y("WORKTREE_OPERATION","Worktrees","Run worktree operation","SERVER",["worktree.id"],Q,{description:"Runs one of the built-in worktree maintenance operations, such as syncing with the base branch or pushing.",details:"Dispatches an agent job and waits for it. Opening an editor is rejected here — it needs a human at the machine. Sync and push touch the remote and can conflict; check `worktree.pushStatus` afterwards or follow with Inspect worktree Git state.",mutatesWorktree:!0}),Y("WORKTREE_PREPARATION","Worktrees","Run worktree preparations","SERVER",["worktree.id"],[],{description:"Inspects, applies, or undoes the repository preparation rules for one worktree.",details:"Dispatches a preparation job to the owning agent and waits for its per-file result. Apply and Undo can overwrite managed paths, while Inspect only refreshes persisted status. Unsupported, offline, and unavailable worktrees fail with the service's explicit skip reason.",mutatesWorktree:!0}),Y("WORKTREE_SET_AUTO_SYNC","Worktrees","Set worktree Auto Sync","SERVER",["worktree.id"],["worktree.autoSync"],{description:"Enables, updates, retries, or cancels persistent Auto Sync for a worktree.",details:"An enabled rule rebases on the target branch whenever it changes and force-pushes with lease. A merge-conflict quick-action workflow can be selected as the automatic recovery path; unresolved conflicts pause the rule. Force is accepted only when preparations paused Auto Sync, destructively resets managed paths, and resumes the rule after a successful sync.",mutatesWorktree:!0,mutatesExternal:!0}),Y("WORKTREE_SET_AUTO_MERGE","Worktrees","Set worktree Auto Merge","SERVER",["worktree.id"],["worktree.autoMerge"],{description:"Enables, updates, retries, or cancels GitHub-native Auto Merge for a worktree.",details:"GitHub remains the authority for required checks and reviews. Optional post-merge actions can move the linked Jira ticket to its configured done status and safely delete a clean linked worktree.",mutatesWorktree:!0,mutatesExternal:!0}),Y("WORKTREE_DELETE","Worktrees","Delete worktree","SERVER",["worktree.id"],Z,{description:"Removes a worktree from the agent, optionally deleting its remote branch too.",details:"Destroys the directory and any uncommitted work in it — there is no undo. Deleting the remote branch as well affects everyone, and closes any pull request from that branch. Do not put this before steps that still read `worktree.*`.",mutatesWorktree:!0}),Y("WORKTREE_MOVE","Worktrees","Move worktree","SERVER",["worktree.id"],Q,{description:"Moves a worktree's branch and changes into another codebase, optionally deleting the source.",details:"Waits for the move job to finish. Used when a branch was started against the wrong checkout. Deleting the source destroys the original directory; leaving it keeps both, which means two worktrees on one branch. Refreshes `worktree.*` to point at wherever the work now lives.",mutatesWorktree:!0}),Y("WORKTREE_INSPECT","Worktrees","Inspect worktree","SERVER",["worktree.id"],["worktree.commits","worktree.changes","worktree.branchChanges","worktree.commitsTruncated","worktree.changesTruncated","worktree.branchChangesTruncated"],{description:"Reads the worktree's commits and changed files into `worktree.commits` and `worktree.changes`.",details:"Read-only. Use it to give a later condition or AI prompt something concrete to work from — for example to skip opening a pull request when nothing changed. For push/dirty state use Inspect worktree Git state instead, which is cheaper."}),Y("WORKTREE_INSPECT_GIT","Worktrees","Inspect worktree Git state","SERVER",["worktree.id"],["worktree.*"],{description:"Reads the worktree's Git status — dirty flag, ahead/behind counts, push status, conflicts — into `worktree.*`.",details:"Read-only and the cheap way to branch on repository state: gate a commit on `worktree.dirty`, or a sync on the worktree being behind. Use Inspect worktree when you need the actual commits and diffs."}),Y("WORKTREE_GIT_OPERATION","Worktrees","Run worktree Git operation","SERVER",["worktree.id"],Q,{description:"Runs a specific Git operation in the worktree — pull, push, rebase, stash, and the rest.",details:'Dispatches an agent job and waits for it. Operations that rewrite history or touch the remote can fail on conflicts; "Stash changes first" clears the way for operations that need a clean tree. Prefer Run worktree operation for the higher-level sync and push flows, which handle more of the edge cases.',mutatesWorktree:!0}),Y("WORKTREE_WAIT_PUSH_READY","Worktrees","Wait for push-ready","WAIT",["worktree.id"],Q,{description:"Parks the run until the worktree's branch is pushed and tracking a remote.",details:"The step to put between an AI session that commits and Open pull request, which needs the branch to exist on the remote. Resolves as soon as the branch is push-ready; without a timeout it waits indefinitely, so set one if a human may never push. Writes `worktree.pushStatus`."}),Y("WORKTREE_SNAPSHOT","Worktrees","Snapshot Git state","AGENT",["worktree.path"],["steps.<stepId>.snapshotId"],{description:"Captures a restorable checkpoint of the worktree's Git state before a risky step.",details:"Runs on the agent, so it needs `worktree.path` and an online agent. The snapshot id it writes is what run replay restores from, which makes this the step to place before anything that rewrites the tree. Snapshots cost disk on the agent."}),Y("CODEBASE_FETCH_REFRESH","Codebases","Fetch or refresh codebase","SERVER",["codebase.id"],Z,{description:"Fetches remote refs for a codebase, or fully refreshes its cached metadata.",details:"Fetch updates remote-tracking branches; refresh re-reads the whole checkout and is slower. Runs as an agent job and waits. Fails when the agent skips the operation — usually because the codebase is missing or already busy. Put a fetch in front of steps that check whether a remote branch exists.",mutatesWorktree:!0}),Y("CODEBASE_INSPECT_GIT","Codebases","Inspect codebase Git state","SERVER",["codebase.id"],["codebase.*"],{description:"Reads the codebase checkout's Git status into `codebase.*`.",details:"Read-only. This is the primary checkout, not a worktree — use Inspect worktree Git state for per-branch work. Useful for refusing to start work when the base checkout is dirty or on an unexpected branch."}),Y("CODEBASE_GIT_OPERATION","Codebases","Run codebase Git operation","SERVER",["codebase.id"],Z,{description:"Runs a Git operation against the codebase's primary checkout.",details:'Same operations as the worktree version, aimed at the main checkout that every worktree branches from — so a bad rebase or reset here affects all of them. "Stash changes first" clears local modifications out of the way. Runs as an agent job and waits.',mutatesWorktree:!0}),Y("BUILD_START","Builds","Start build or test","SERVER",["codebase.id","worktree.id"],["build.*"],{description:"Queues an iOS build, test, or archive run on the agent and waits for it to finish.",details:"Needs a build configuration id and an online agent; the destination and build scripts are optional. The step parks until the build reaches a terminal status, so a long test suite holds the workflow run. Failing builds fail the step — route the failure handle if you want to read the results anyway. Writes `build.*`, which the read-results and coverage steps then consume.",mutatesExternal:!0}),Y("BUILD_READ_TEST_RESULTS","Builds","Read test results","SERVER",["build.id"],["build.testSummary","build.tests"],{description:"Reads a finished build's test report into `build.testSummary` and `build.tests`.",details:"Fails outright when the report is not ready, so it belongs after Start build or test rather than in parallel with it. The summary carries the passed/failed counts a condition can branch on; the per-test list is the detail an AI prompt can be pointed at. Read-only."}),Y("BUILD_READ_COVERAGE","Builds","Read code coverage","SERVER",["build.id"],["build.coverageSummary","build.coverageFiles","build.changedCoverageFiles"],{description:"Reads a finished build's coverage report into `build.coverageSummary` and the per-file breakdowns.",details:'Fails when the coverage report is not ready — the build must have been run with coverage collection on. Also writes the changed-files breakdown, which is what a "coverage on this branch\'s changes" gate should read rather than the whole-project number. Read-only.'}),Y("BUILD_IMPORT_COVERAGE","Builds","Import coverage report","SERVER",["worktree.id"],["build.id","build.coverageSummary"],{description:"Reads a coverage file a test command wrote in the worktree and records it as a coverage report.",details:"Pair it with a Terminal command step that runs the test suite first: this step only reads what that run left behind, at the path given in `Coverage file`. The build name defaults to the workflow name and can be overridden. LCOV and Istanbul (`coverage-final.json`) are both understood, and AUTO tells them apart by the file itself. Runs as an agent job and waits. The report is attached to a new build record of its own, so it shows up on that build's coverage page and in the coverage picker on Changes; changed-line coverage is measured against the worktree's base branch, and is left out when that branch cannot be resolved. Writes the totals to `build.coverageSummary` and the new id to `build.id` — follow with Read code coverage for the per-file breakdown. Fails when the file is missing, unreadable, or describes no files."}),Y("BUILD_EXPORT","Builds","Export archive","SERVER",["build.id"],["build.exportId",...Q],{description:"Exports a finished archive build into a distributable package on the agent.",details:"Needs export settings and an archive-action build. Runs as an agent job and waits. Writes files to the agent's disk and may talk to Apple's servers for signing, so it can fail on expired certificates or provisioning profiles.",mutatesExternal:!0}),Y("BUILD_DEPLOY","Builds","Deploy build","SERVER",["build.id"],Q,{description:"Installs and launches an existing build on its destinations without rebuilding.",details:"Reuses the artifacts from a previous build, so it is much faster than building again. Destinations default to the ones the build already targeted. Waits for the deployment job. This puts the app on real or simulated devices — treat it as an external effect.",mutatesExternal:!0}),Y("BUILD_CANCEL","Builds","Cancel build","SERVER",["build.id"],["build.id","build.status"],{description:"Cancels a queued or running build.",details:"Aimed at a different build from the one this run started — Start build or test already waits for its own. Cancelling an already-finished build is a no-op rather than an error. Writes `build.status`.",mutatesExternal:!0}),Y("DISK_SPACE_LOAD","Disk space","Load disk-space monitor","SERVER",[],["agent.*","disk.*"],{description:"Loads the current Derived Data disk-space monitor snapshot for an agent.",details:"Targets the configured agent, then falls back to `agent.id` or `codebase.agentId`. The least-free monitored Derived Data volume supplies `disk.freeBytes`, `disk.freeGiB`, and the percentage fields; root and base-repository volumes remain in `disk.volumes` for context only. Read-only and does not request a new report."}),Y("DISK_SPACE_REFRESH","Disk space","Refresh disk-space monitor","WAIT",[],["agent.*","disk.*"],{description:"Requests an immediate disk report from an agent and waits for fresh telemetry.",details:"Targets the configured agent, then falls back to `agent.id` or `codebase.agentId`. Monitoring must be enabled. The step waits until `lastReportedAt` advances, then refreshes `agent.*` and `disk.*`; by default it polls every two seconds and times out after 180 seconds."}),Y("DISK_SPACE_UPDATE_THRESHOLDS","Disk space","Update disk thresholds","SERVER",[],["disk.normalThresholdGiB","disk.pressureThresholdGiB","disk.pollIntervalSeconds","disk.staleAfterSeconds"],{description:"Updates the global normal and pressure free-space thresholds.",details:"Changes the thresholds used for every monitored agent, automatic cleanup, and admission control. The pressure threshold must be positive and lower than the normal threshold. Writes the resulting global settings into `disk.*`."}),Y("DISK_SPACE_SET_MONITORING","Disk space","Set agent disk monitoring","SERVER",[],["agent.*","disk.*"],{description:"Enables or disables Derived Data disk-space monitoring for an agent.",details:"Targets the configured agent, then falls back to `agent.id` or `codebase.agentId`. Disabling monitoring also clears manual and automatic pressure mode and releases cleanup leases that have not started a job. Refreshes `agent.*` and `disk.*`."}),Y("DISK_SPACE_SET_PRESSURE_MODE","Disk space","Set disk pressure mode","SERVER",[],["agent.*","disk.*"],{description:"Enables or clears manual disk pressure mode for an agent.",details:"Targets the configured agent, then falls back to `agent.id` or `codebase.agentId`. Manual pressure mode uses the lower pressure threshold; automatic pressure mode remains controlled by cleanup availability. Refreshes `agent.*` and `disk.*`."}),Y("SKILL_APPLY","Skills","Apply skill group","SERVER",["worktree.id","repo.id"],["steps.<stepId>.status"],{description:"Syncs a skill group's files into the target checkout, or every skill when no group is chosen.",details:"Starts a skill sync run and waits for it. Writes skill files into the repository, which shows up as uncommitted changes — commit or discard them before a step that needs a clean tree. Leave the group empty to sync everything.",mutatesWorktree:!0}),Y("RUN_CREATE_PLAN","AI runs","Create plan and wait","SERVER",["worktree.id"],["run.<stepId>.*"],{description:"Starts an AI planning run against the worktree and waits for the plan to be produced.",details:"Requires a worktree, a provider/model, and a prompt. Plans use a separate FIFO worktree queue and allow unlimited concurrent plans by default; set the worktree concurrency limit to 1–32 to cap them, or 0 for unlimited. Planning inspects the code but does not change it — use Run AI session and wait to actually make edits, or follow with Run completed plan. If the run asks a question it parks until someone answers, so pair long workflows with a question-needed trigger. Writes the run under `run.<stepId>.*`, which later steps reference by this step's id."}),Y("RUN_CREATE_SESSION","AI runs","Run AI session and wait","SERVER",["worktree.id"],["run.<stepId>.*"],{description:"Starts an AI coding session against the worktree and waits for it to finish.",details:"The workhorse step: the agent edits files in the worktree, so the tree is dirty afterwards and the changes still need committing and pushing. Sessions use a separate FIFO worktree queue with one active session by default; set the worktree concurrency limit to 2–32 for parallel sessions or 0 for unlimited. Requires a worktree, a provider/model, and a prompt; attachments and web search are optional. Parks on questions until answered. Writes `run.<stepId>.*`.",mutatesWorktree:!0}),Y("RUN_PLAY_PLAN","AI runs","Run completed plan","SERVER",[],["run.<stepId>.*"],{description:"Executes a plan that has already been produced, turning it into real code changes.",details:"Takes the plan's run id — usually `run.<planStepId>.id` from an earlier Create plan step. The plan must have completed. The resulting Session joins the worktree's FIFO Session queue, which allows one active Session by default; use 0 for unlimited or 2–32 for a larger limit. This is the half of the plan/execute split that touches the worktree. Writes a new run under `run.<stepId>.*`.",mutatesWorktree:!0}),Y("RUN_FOLLOW_UP","AI runs","Follow up run","SERVER",[],["run.<stepId>.*"],{description:"Starts a new AI run that continues from an existing one, resuming its context or starting fresh.",details:'RESUME keeps the previous conversation, FRESH starts over in the same worktree, and RESEND replays the original prompt. The new run joins the source kind\'s separate FIFO worktree queue and defaults to unlimited concurrency for Plans or one active run for Sessions; use 0 for unlimited or 1–32 for a finite limit. Needs the source run id plus a new prompt. The natural step for "fix the review comments" loops after a first session. Writes `run.<stepId>.*`.'}),Y("RUN_STEER","AI runs","Steer active run","SERVER",[],["run.<stepId>.*"],{description:"Sends extra instructions into a run that is already in progress.",details:"Only affects a run that is still going — it does not restart a finished one, which is what Follow up run is for. Because the steps in this workflow that start runs also wait for them, steering usually targets a run started elsewhere, reached through a run trigger."}),Y("RUN_ANSWER","AI runs","Answer run question","SERVER",[],["run.<stepId>.*"],{description:"Answers a question an AI run is blocked on so it can carry on.",details:"Needs the question batch id, typically from `run.questions` seeded by a run-needs-an-answer trigger, and answers keyed by question id. This answers questions asked by an AI run — the Request confirmation and Ask user to choose steps ask questions of a human about the workflow itself."}),Y("RUN_PAUSE","AI runs","Pause run","SERVER",[],["run.<stepId>.*"],{description:"Pauses an in-progress AI run.",details:"The run stops at its next checkpoint and stays paused until something continues it. Falls back to `run.id`. Pausing an already-finished run fails."}),Y("RUN_CONTINUE","AI runs","Continue run","SERVER",[],["run.<stepId>.*"],{description:"Resumes a paused AI run.",details:"The counterpart to Pause run. Fails when the run is not paused. Falls back to `run.id`."}),Y("RUN_CANCEL","AI runs","Cancel run","SERVER",[],["run.<stepId>.*"],{description:"Cancels an AI run, stopping its work.",details:"Whatever the run already wrote to the worktree stays — cancelling stops further work, it does not roll anything back. Falls back to `run.id`."}),Y("RUN_REVISE_ANSWER","AI runs","Revise answer and rewind","SERVER",[],["run.<stepId>.*"],{description:"Rewinds a run to an earlier question, replaces the answer, and replays from there.",details:"Two-phase: the step prepares the revision, parks, and applies it once the run is ready. Rolling back restores the worktree to the checkpoint at that question, discarding work done since — stash first if that work matters. The heavy way to correct a wrong answer; Follow up run is usually enough.",mutatesWorktree:!0}),Y("RUN_READ_RESULT","AI runs","Read run result","SERVER",[],["run.<stepId>.*"],{description:"Loads a finished run's events, questions, token usage, and linked items into session data.",details:"Read-only. Gives later steps the run's actual output to work from — a summary to put in a Jira comment, usage figures to threshold on, or the linked pull request. Falls back to `run.id`."}),Y("RUN_CAPTURE_CHECKPOINT","AI runs","Capture run checkpoint","SERVER",[],["steps.<stepId>.snapshotId"],{description:"Records the run's most recent checkpoint so a later replay can restore from it.",details:"Reads an existing checkpoint rather than creating one, and fails when the run has none. Use Snapshot Git state to capture a fresh checkpoint of the worktree instead. Writes the checkpoint id to `steps.<stepId>.snapshotId`."}),Y("RUN_ARCHIVE_DELETE","AI runs","Archive or delete run","SERVER",[],[],{description:"Archives a run out of the active list, or permanently deletes it.",details:"Archiving is reversible; deleting removes the run and its history for good. Delete wins when both flags are set. Housekeeping for workflows that generate many short-lived runs.",mutatesExternal:!0}),Y("NOTIFICATION_SEND","Human loop","Send notification","SERVER",[],[],{description:"Posts a notification into the app's notification list with a title, body, and link.",details:"Deduplicated per run, step, and generation, so a retried attempt does not notify twice. The link defaults to this workflow run. Fire-and-forget: it tells a human something happened but does not wait — use Request confirmation when the workflow needs an answer.",mutatesExternal:!0}),Y("IOS_PUSH_SEND","Human loop","Push to iOS device","SERVER",[],[],{description:"Sends an Apple push notification to registered devices, a broadcast channel, or one raw device token.",details:"Needs APNs credentials. Target mode picks between all registrations, a chosen few, a broadcast channel, or a direct token — the direct mode also needs the token's encoding and whether it is a sandbox or production token. Leaves the device once delivered; nothing about the run waits on it.",mutatesExternal:!0}),Y("HUMAN_CONFIRM","Human loop","Request confirmation","WAIT",[],["steps.<stepId>.answer"],{description:"Parks the run and asks a human to confirm before continuing.",details:"The approval gate to put in front of anything irreversible. Without a timeout the run waits indefinitely; with one it fails when nobody answers in time, which the failure handle can route to a safe default. The answer lands in `steps.<stepId>.answer`."}),Y("HUMAN_CHOICE","Human loop","Ask user to choose","WAIT",[],["steps.<stepId>.answer"],{description:"Parks the run and asks a human to pick from a set of options, optionally allowing several or a free-text answer.",details:"Like Request confirmation but with named buttons — branch on `steps.<stepId>.answer` with an If step afterwards. Multi-select returns a list. Allowing a custom answer means the value may be anything the person typed, so handle the unexpected case."}),Y("CONTROL_IF","Control flow","If / else","CONTROL",[],[],{description:"Evaluates a condition and sends the run down its `true` or `false` branch.",details:"Exactly one branch is taken; steps on the other are skipped, and a skipped branch does not block a downstream join. Conditions compare session values with the usual operators and combine with ALL/ANY/NOT. Both branches may be left unconnected, which simply ends that path."}),Y("CONTROL_JOIN","Control flow","Join branches","CONTROL",[],[],{description:"Brings parallel branches back together, waiting for all of them or continuing on the first.",details:"Required wherever more than one branch reaches the same step — the validator rejects a plain step with several incoming edges. ALL waits for every branch, ANY continues on the first and lets the others keep running. Skipped branches never block it, and the join is skipped when no branch reaches it. A join that closes a For each also reports the iteration failures."}),Y("CONTROL_DELAY","Control flow","Time delay","WAIT",[],[],{description:"Pauses the run for a fixed number of seconds.",details:"Accepts up to a year. The run is parked rather than held open, so a long delay costs nothing while it waits. Use it to space out polling or to give an external system time to settle; use Wait until when you are waiting for a condition rather than a duration."}),Y("CONTROL_WAIT_UNTIL","Control flow","Wait until","WAIT",[],[],{description:"Parks the run until a condition over session data becomes true, re-checking on a cadence.",details:"Evaluates immediately and continues at once if the condition already holds. Session data only changes when a step writes it, so the condition must be able to become true through some other branch — otherwise the wait never resolves. Default cadence is 15 seconds; set a timeout to bound it."}),Y("CONTROL_FOR_EACH","Control flow","For each","CONTROL",[],["steps.<stepId>.items"],{description:"Runs its `body` branch once per item in a list, or takes the `empty` branch when there is nothing to iterate.",details:"Reads the list from a session path or from inline items, and caps at 1,000. Iterations run in parallel and each sees its own item. Fail-fast stops the whole run on the first failing iteration; collect-errors lets them all finish and reports failures at the closing join. Writes the items to `steps.<stepId>.items`."}),Y("CONTROL_TRY","Control flow","Try / catch","CONTROL",[],[],{description:"Marks the start of a protected region whose failures route out of the `catch` handle.",details:"Takes no config — the recovery path is drawn in the graph. Steps on the `success` branch run normally; when one of them fails, the run continues from `catch` instead of failing outright. Use a step's own failure handle for a single fallible step; reach for this when a whole sequence shares one recovery path."}),Y("CONTROL_SET_VARIABLE","Control flow","Set or compute variable","CONTROL",[],[],{description:"Writes a value into session data at a chosen path, either a constant or the result of a small script.",details:"The script runs in a sandboxed JavaScript interpreter with the session data available and no network or filesystem access; its return value is what gets written. Without a script the literal value is used. The path may be any dotted path — write under a namespace of your own to avoid colliding with what steps produce. Because the path comes from config, the catalog cannot advertise it: list it in this step's own `providedPaths` too, or a later step that binds it fails to publish with REQUIREMENT_UNSATISFIED."}),Y("CONTROL_SUBWORKFLOW","Control flow","Call sub-workflow","SERVER",[],[],{description:"Runs another published workflow as a child and waits for it to finish.",details:"Must pin a specific published version — the validator rejects an unpinned reference, so a sub-workflow cannot change under a caller. The input mapping seeds the child's session data. The child appears as a nested run; its failure fails this step."}),Y("SAVED_COMMAND","Extensibility","Run saved command","AGENT",[],["steps.<stepId>.*"],{description:"Starts a saved command on an eligible agent home or worktree target.",details:"Uses the saved command snapshot, target rules, output log, and restart policy. Wait for exit fails the workflow when the command ultimately fails or is cancelled; fire and forget succeeds after durable dispatch and remains independent if the workflow is later cancelled. An optional RE2 output pattern emits the match connector before exit and records captures in session data; matching requires wait for exit. Always-restart commands can only use fire and forget.",mutatesWorktree:!0}),Y("CUSTOM_COMMAND","Extensibility","Run custom command","AGENT",[],["steps.<stepId>.*"],{description:"Runs a one-off shell command on an agent home or worktree and records it in Commands run history.",details:"The script is retained only in the immutable command-run snapshot, not as a reusable saved command. Context targeting prefers the current worktree, then the current agent. Wait for exit fails the workflow when the command fails or is cancelled; fire and forget succeeds after durable dispatch. An optional RE2 output pattern emits the match connector before exit and records captures in session data; matching requires wait for exit.",mutatesWorktree:!0}),...ee,Y("TERMINAL_RUN","Extensibility","Run terminal script","AGENT",["worktree.path"],["steps.<stepId>.*"],{description:"Runs a shell or Node script on the agent inside the worktree, capturing its output.",details:"Needs `worktree.path` and an online agent. A non-zero exit fails the step. Named credentials can be injected as environment variables so secrets never sit in the definition — the validator rejects secret-looking literals in config. Arbitrary code on the agent's machine: it can change anything the agent user can reach. Writes stdout, stderr, and the exit code under `steps.<stepId>.*`; to publish anything else the script produces into a named path, declare it in this step's own `providedPaths`.",mutatesWorktree:!0}),Y("MCP_CALL","Extensibility","Call MCP tool","SERVER",[],["steps.<stepId>.output"],{description:"Calls a tool on a configured MCP server — built-in or external — with a JSON argument object.",details:"The general escape hatch to anything reachable over MCP. Needs the server (tool group) and the exact tool name; arguments must match that tool's own schema. What it does depends entirely on the tool, so treat it as externally mutating. The result lands in `steps.<stepId>.output`.",mutatesExternal:!0}),...[["SSE_ENDPOINT_ACTION","Manage SSE endpoint"],["SSE_MOCK_ACTION","Manage SSE mock"],["SSE_STORAGE_ACTION","Manage SSE storage"],["SSE_BREAKPOINT_RESOLVE","Resolve SSE breakpoint"],["SSE_HISTORY_CLEAR","Clear SSE history"],["SSE_SCRIPT_TEST","Test SSE script"]].map(([e,t])=>X(e,"SSE",t,[],["sse.*","steps.<stepId>.output"],{mutatesExternal:!1}))],er=new Map(et.map(e=>[e.kind,e])),ei=["run.*","worktree.*","codebase.*","agent.*","repo.*","ticket.*"],ea=["build.*","worktree.*","codebase.*","agent.*","repo.*","ticket.*"],en=["worktree.*","codebase.*","agent.*","repo.*","ticket.*","pr.*"],es=["ticket.*","comment.*","changelog.*"],eo=["repo.*","pr.*","ticket.*","worktree.*","codebase.*","agent.*"],el=[...eo,"comment.*"],eu=["repo.*","pr.*","ticket.*","worktree.*","codebase.*","agent.*"],ec="Filters narrow it further: each session path must equal the given value, or be one of a list of values.",ed="Set a threshold path, operator, and value to fire only on the crossing: it fires when the comparison first becomes true and stays quiet until it goes false again, so a metric hovering over the line does not fire repeatedly.",eh=(e,t,r,i,a)=>({kind:e,category:t,label:r,description:a.description,details:a.details,configSchema:G(e,"trigger"),capabilityFlags:["DURABLE","DEDUPLICATED"],seedPaths:i,sourceHandles:(0,n.workflowStaticSourceHandles)(e)}),ep=(e,t,r,i)=>eh(e,t,r,i,{description:`${r} emits a normalized, filterable workflow event.`,details:`${r} uses the canonical domain event and deduplicates deliveries by subject and revision. ${ec}`}),em=[ep("COMMAND_RUN_RESULT","Commands","Command run result",["command.*","agent.*","worktree.*"]),ep("COMMAND_OUTPUT_MATCH","Commands","Command output match",["command.*","output.*"]),ep("SKILL_SYNC_RESULT","Skills","Skill sync result",["skillSync.*","skill.*","repo.*"]),ep("SKILL_SYNC_CONFLICT","Skills","Skill sync conflict",["skillSync.*","skill.*","repo.*"]),ep("GITHUB_PIPELINE_STATUS_CHANGED","GitHub","Pipeline status changed",["pipeline.*","repo.*","pr.*","worktree.*","codebase.*","agent.*","ticket.*"]),ep("GITHUB_PR_SYNCHRONIZED","GitHub","Pull request synchronized",eo),ep("GITHUB_REVIEW_APPROVED","GitHub","Pull request review approved",eo),...[["GITLAB_MR_STATE","Merge request opened or ready",eu],["GITLAB_REVIEW_CHANGES_REQUESTED","Changes requested",eu],["GITLAB_REVIEW_COMMENT","Review comment created",[...eu,"comment.*"]],["GITLAB_MR_CLOSED","Merge request merged or closed",eu],["GITLAB_PIPELINE_FAILED","Pipeline failed",["pipeline.*","repo.*","pr.*"]],["GITLAB_PUSH_DEFAULT","Push to default branch",["repo.*","push.*"]],["GITLAB_PIPELINE_SUCCEEDED","Pipeline succeeded",["pipeline.*","repo.*","pr.*"]],["GITLAB_NOTE_COMMAND","Note command",[...eu,"comment.*"]],["GITLAB_PIPELINE_RESULT","Pipeline result",["pipeline.*","repo.*","pr.*"]],["GITLAB_MR_LABEL","Merge request label set",eu],["GITLAB_PIPELINE_STATUS_CHANGED","Pipeline status changed",["pipeline.*","repo.*","pr.*"]],["GITLAB_MR_SYNCHRONIZED","Merge request synchronized",eu],["GITLAB_REVIEW_APPROVED","Merge request approved",eu],["GITLAB_JOB_STATUS_CHANGED","Job status changed",["job.*","pipeline.*","repo.*"]]].map(([e,t,r])=>ep(String(e),"GitLab",String(t),r)),ep("JIRA_TICKET_UPDATED","Jira","Jira ticket updated",es),ep("JIRA_COMMENT_ADDED","Jira","Jira comment added",es),ep("JIRA_WORKLOG_ADDED","Jira","Jira worklog added",es),ep("JIRA_SPRINT_ENDED","Jira","Jira sprint ended",es),ep("CODEBASE_SYNC_STATE_CHANGED","Codebases","Codebase sync state changed",["codebase.*","agent.*","repo.*"]),ep("CODEBASE_OPERATION_FAILED","Codebases","Codebase operation failed",["codebase.*","agent.*","repo.*","operation.*"]),ep("WORKTREE_SYNC_STATE_CHANGED","Worktrees","Worktree sync state changed",en),ep("WORKTREE_AUTOMATION_RESULT","Worktrees","Worktree automation result",[...en,"automation.*"]),ep("WORKTREE_CLEAN","Worktrees","Worktree became clean",en),ep("PUSH_NOTIFICATION_RESULT","Notifications","Push notification result",["pushBatch.*"]),ep("IOS_DEVICE_ENROLLED","Devices","iOS device enrolled",["device.*"]),ep("IOS_DEVICE_REGISTRATION_RESULT","Devices","iOS device registration result",["device.*"]),ep("SIGNING_OPERATION_RESULT","Signing","Signing operation result",["signing.*","signingProfile.*","agent.*"]),ep("SIGNING_ASSET_EXPIRING","Signing","Signing asset expiring",["signing.*","signingProfile.*","agent.*"]),ep("BUILD_DATA_THRESHOLD","Build Data","Build-data threshold",["buildData.*","agent.*","worktree.*"]),ep("BUILD_DATA_CLEANUP_RESULT","Build Data","Build-data cleanup result",["buildData.*","cleanup.*","agent.*"]),ep("POLLING_OPERATION_STATE","Operations","Polling operation state",["polling.*"]),ep("MODEL_COST_CATALOG_CHANGED","Operations","Model-cost catalog changed",["modelCosts.*"]),ep("CREDENTIAL_STORE_DEGRADED","Operations","Credential store degraded",["credentials.*"]),ep("AGENT_RESOURCE_THRESHOLD","Agents","Agent resource threshold",["agent.*"]),ep("AGENT_VERSION_CHANGED","Agents","Agent version changed",["agent.*"]),ep("TOOL_CALL_RESULT","Tools","Tool call result",["toolCall.*"]),ep("SSE_REQUEST_OPENED","SSE","SSE request opened",["sse.*","endpoint.*","request.*"]),ep("SSE_EVENT_EMITTED","SSE","SSE event emitted",["sse.*","endpoint.*","request.*","event.*"]),ep("SSE_BREAKPOINT_WAITING","SSE","SSE breakpoint waiting",["sse.*","endpoint.*","request.*","breakpoint.*"]),ep("SSE_BREAKPOINT_RESOLVED","SSE","SSE breakpoint resolved",["sse.*","endpoint.*","request.*","breakpoint.*"]),ep("SSE_STREAM_COMPLETED","SSE","SSE stream completed",["sse.*","endpoint.*","request.*"]),ep("SSE_STREAM_FAILED","SSE","SSE stream failed",["sse.*","endpoint.*","request.*"])],ef=[eh("MANUAL","Manual","Manual run",[],{description:"Fires when someone presses Run on the workflow. The default entry point.",details:"Seeds nothing beyond `workflow.*`, so steps hanging off it can only bind to values that later steps produce. A caller may still pass session data explicitly when starting the run. A workflow that has only a choice trigger refuses a plain run."}),eh("MANUAL_CHOICE","Manual","Manual run with a choice",[],{description:"Fires when someone picks an option from the menu under the run button, and routes the run out of that option's own handle.",details:"Declare at least one option, each with a unique key — the key names the outgoing handle, so renaming a label leaves edges attached. One workflow can fan out into several entry paths without a step in front of them. Every edge must leave a handle that still exists, or publishing fails."}),eh("RESOURCE_MANUAL","Manual","Run from a resource",[],{description:"Fires when someone starts the workflow from a specific resource page — a worktree, pull request, build, codebase, ticket, or run.",details:"Must target exactly one resource kind; add a second trigger to accept another. The page seeds that resource's namespace into session data, so a worktree-launched run gets its worktree, codebase, owning agent, repository, and any linked ticket. Those seeds are an optimistic contract — an optional link that is absent resolves to nothing at run time. A worktree does not seed `pr.*`; use a pull-request trigger or Load pull request to bring one into session data. This is also what makes the workflow show up on that resource's page."}),eh("RESOURCE_MANUAL_CHOICE","Manual","Run from a resource with a choice",[],{description:"Fires from a resource page after the person picks an option, routing out of that option's handle.",details:"The resource and choice triggers combined: pick a resource kind and declare keyed options. Same rules as both — one resource kind per trigger, unique option keys, and every edge on a live handle."}),eh("SCHEDULE","Schedule","On a schedule",[],{description:"Fires repeatedly on a fixed cadence measured in seconds.",details:'A cadence, not a cron expression — there is no way to say "weekdays at 9am". The clock runs while the workflow is enabled, and pausing the workflow stops it. Seeds nothing, so scheduled workflows normally start by loading whatever they operate on. Mind the overlap policy: a cadence shorter than the run takes will queue or coalesce.'}),eh("WORKFLOW_FINISHED","Workflows","Another workflow finished",["workflow.*"],{description:"Fires when a different workflow run reaches a terminal state.",details:`Chains workflows without making one a sub-workflow of the other, so the two stay independently runnable. Filter on \`workflow.id\` to watch a specific one and on the finishing status to react only to failures. ${ec}`}),eh("GITHUB_PR_STATE","GitHub","Pull request opened or ready",eo,{description:"Fires when a pull request is opened, or when a draft is marked ready for review.",details:`Needs GitHub polling configured for the repository. Seeds \`pr.*\` and \`repo.*\`, so steps can act on the pull request straight away. ${ec} Filter on \`pr.isDraft\` or the base branch to avoid firing on every pull request in the repository.`}),eh("GITHUB_REVIEW_CHANGES_REQUESTED","GitHub","Changes requested",eo,{description:"Fires when a reviewer submits a review requesting changes.",details:`The entry point for an automated "address the review" loop: pair it with Collect review comments and an AI session. Approvals and plain comments do not fire it. ${ec}`}),eh("GITHUB_REVIEW_COMMENT","GitHub","Review comment created",el,{description:"Fires when a new review comment is posted on a pull request.",details:`Fires per comment rather than per review, so a reviewer leaving five comments fires it five times — take care with steps that start AI runs. Use Changes requested when you want one event per review. ${ec}`}),eh("GITHUB_PR_CLOSED","GitHub","Pull request merged or closed",eo,{description:"Fires when a pull request is merged or closed without merging.",details:`Both outcomes fire it; branch on \`pr.state\` to tell them apart. The natural place to hang cleanup — deleting the worktree, moving the ticket on. ${ec}`}),eh("GITHUB_CHECK_FAILED","GitHub","Check suite or run failed",["repo.*","pipeline.*","worktree.*","codebase.*","agent.*","pr.*","ticket.*"],{description:"Fires when a check suite or check run reports a failure.",details:`Seeds \`pipeline.*\`, including the ids the retry and cancel steps need. Flaky suites fire this often, so gate an automatic retry on a count or a delay rather than retrying unconditionally. ${ec}`}),eh("GITHUB_PUSH_DEFAULT","GitHub","Push to default branch",["repo.*","push.*","ticket.*"],{description:"Fires when a commit lands on the repository's default branch.",details:`Seeds \`repo.*\` and \`push.*\`, plus a ticket key when the pushed branch contains one. There is no pull request or worktree in scope, so a workflow hanging off it usually starts by creating one. Fires on merges too, since a merge is a push. ${ec}`}),eh("GITHUB_WORKFLOW_SUCCEEDED","GitHub","Workflow run succeeded",["repo.*","pipeline.*","worktree.*","codebase.*","agent.*","pr.*","ticket.*"],{description:"Fires when a GitHub Actions workflow run completes successfully.",details:`The success counterpart to the failure triggers — useful for gating a deploy or a merge on a green pipeline. Filter on the workflow name so every unrelated Actions run does not start this workflow. ${ec}`}),eh("GITHUB_ISSUE_COMMAND","GitHub","Issue comment command",["repo.*","pr.*","ticket.*","comment.*"],{description:"Fires when a comment from an allow-listed GitHub user matches a command pattern, such as `/deploy`.",details:`The only trigger that lets outside text start a workflow, so it is deliberately strict: an explicit list of GitHub logins is required, and the pattern must be anchored with \`^\` and \`$\` — publishing fails otherwise. Both checks must pass. Keep the allow-list tight, since anyone on it can start whatever the workflow does. ${ec}`}),eh("GITHUB_ACTIONS_RESULT","GitHub Actions","Workflow result",["repo.*","pipeline.*","worktree.*","codebase.*","agent.*","pr.*","ticket.*"],{description:"Fires when a tracked GitHub Actions run finishes, whatever its conclusion.",details:`The richest of the Actions triggers: it correlates the run back to its worktree, owning agent, pull request, and ticket when those links exist. Branch on the conclusion rather than adding separate success and failure triggers. ${ec}`}),eh("GITHUB_PR_LABEL","GitHub","Pull request label set",eo,{description:"Fires when a label is applied to a pull request.",details:`Turns a label into a manual switch — label a pull request \`automerge\` and let a workflow take it from there. Filter on the label name, or every label change in the repository starts the workflow. ${ec}`}),eh("BUILD_RESULT","Builds","Build result",ea,{description:"Fires when a build finishes, succeeded or failed.",details:`Seeds \`build.*\` along with the worktree it ran in, so the read-results and coverage steps can follow directly. Branch on \`build.status\` to separate the outcomes. ${ec}`}),eh("BUILD_TEST_THRESHOLD","Builds","Test failure threshold",ea,{description:"Fires when a build's failing-test count crosses a threshold you set.",details:`Point the threshold path at \`build.testSummary.failed\` and pick an operator and value. ${ed} ${ec}`}),eh("BUILD_COVERAGE_THRESHOLD","Builds","Coverage threshold",ea,{description:"Fires when a build's code coverage crosses a threshold you set.",details:`Point the threshold path at the coverage summary — usually the changed-files percentage rather than the whole-project number — and compare with a less-than operator. ${ed} ${ec}`}),eh("BUILD_HOOK_FAILED","Builds","Build hook failed",ea,{description:"Fires when one of a build's pre- or post-build scripts fails.",details:`Distinguishes a broken build script from a genuine compile or test failure, which is what Build result reports. Seeds \`build.*\`. ${ec}`}),eh("AGENT_CONNECTION","Agents","Agent connection changed",["agent.*","codebase.agentId"],{description:"Fires when an agent comes online or goes offline.",details:`Seeds the agent id, name, connection state, and capacity metrics. A workflow hanging off it is usually about notifying a human rather than doing repository work — an offline agent cannot run agent steps anyway. Filter on the connection status to react to one direction only. ${ec}`}),eh("AGENT_JOB_FAILED","Agents","Agent job failed",["steps.trigger.*","agent.*","codebase.*","worktree.*","repo.*","ticket.*"],{description:"Fires when a job dispatched to an agent fails — a build, a Git operation, a terminal script.",details:`The failing job is seeded under \`steps.trigger.*\`, including its kind and error. When it targeted a worktree, the owning agent, codebase, repository, and ticket are included too. Catches infrastructure failures that a workflow's own failure handles never see, because the job belonged to a different run. ${ec}`}),eh("AGENT_DISK_REPORT","Agents","Agent disk report",["agent.*","codebase.agentId","disk.*"],{description:"Fires whenever the Derived Data monitor accepts a new agent disk report.",details:`Seeds the complete monitor snapshot under \`disk.*\`, while \`agent.diskFreeBytes\` remains the legacy root-disk inventory value. This can fire at the agent poll cadence; use filters when every report is not needed. ${ec}`}),eh("AGENT_DISK_THRESHOLD","Agents","Agent disk threshold",["agent.*","codebase.agentId","disk.*"],{description:"Fires when monitored Derived Data free space crosses a threshold you set.",details:`Use \`disk.freeGiB\`, \`disk.freeBytes\`, or \`disk.freePercent\` to evaluate the least-free monitored Derived Data volume. \`agent.diskFreeBytes\` remains available for older root-disk workflows. ${ed} ${ec}`}),eh("AGENT_DISK_STATE_CHANGED","Agents","Agent disk state changed",["agent.*","codebase.agentId","disk.*"],{description:"Fires when an agent's disk monitor changes status, pressure mode, health, or monitored volume.",details:`Filter on \`disk.status\`, \`disk.pressureMode\`, \`disk.enabled\`, or errors and warnings to react to a specific transition. Cleanup start appears as \`DELETING\`; recovery can be selected with \`IDLE\`. Repeated reports in the same state stay quiet. ${ec}`}),eh("AGENT_DISK_CLEANUP_RESULT","Agents","Automatic disk cleanup result",["agent.*","codebase.agentId","disk.*","cleanup.*"],{description:"Fires whenever a monitor-managed automatic Derived Data cleanup finishes.",details:`Seeds the terminal agent job under \`cleanup.*\`, including status, error, targets, and deleted entries. Every cleanup job is independent, so two successive successes both fire. Manual Build Data deletions remain outside this trigger. ${ec}`}),eh("CCUSAGE_THRESHOLD","Agents","Usage threshold",["run.usage.*","agent.*"],{description:"Fires when aggregate AI usage crosses a threshold you set.",details:`Watches usage across runs rather than one run's spend — Run usage threshold does that. The cost guardrail: notify, or pause workflows that start AI runs. ${ed} ${ec}`}),eh("WORKTREE_CREATED","Worktrees","Worktree created",en,{description:"Fires after a new worktree is successfully created.",details:`Fires once after the created worktree is projected into the control plane. Seeds the worktree, repository, codebase, and owning agent, plus a linked pull request and Jira ticket when the branch resolves to them. ${ec}`}),eh("WORKTREE_BEHIND","Worktrees","Worktree behind base",en,{description:"Fires when a worktree's branch falls behind the branch it was cut from.",details:`Pairs with a sync operation to keep long-lived branches current. Fires again as the base moves on, so a workflow that reacts should either sync or be filtered narrowly. ${ec}`}),eh("WORKTREE_CONFLICT","Worktrees","Worktree has conflicts",en,{description:"Fires when a worktree is left with Git conflicts after a merge or rebase.",details:`Only fires when the worktree is genuinely marked conflicted. Conflicts need resolving before most other worktree steps will work, so this usually leads to a notification or an AI session pointed at the conflict. ${ec}`}),eh("WORKTREE_MISSING","Worktrees","Worktree missing",en,{description:"Fires when a worktree the control plane knows about is no longer on disk.",details:`Only fires once the worktree is actually recorded as missing — usually someone deleted the directory by hand, or the agent's disk was cleaned. Steps that need the worktree will fail, so react by recreating it or clearing the record. ${ec}`}),eh("WORKTREE_DIVERGED","Worktrees","Worktree diverged",en,{description:"Fires when a worktree's branch and its remote have both moved on independently.",details:`Only fires when the push status is genuinely diverged. Resolving it means a rebase, a merge, or a force push — all destructive enough that this usually routes to a human rather than to an automatic fix. ${ec}`}),eh("WORKTREE_DIRTY_DURATION","Worktrees","Worktree dirty too long",en,{description:"Fires when a worktree has had uncommitted changes for longer than expected.",details:`Catches work that stalled — an AI session that edited files and was never followed up, or a human who wandered off. Usually a nudge rather than an automatic commit. ${ec}`}),eh("WORKTREE_NEW_COMMIT","Worktrees","New worktree commit",en,{description:"Fires when a new commit lands in a worktree.",details:`Fires per commit, so a rebase or a batch of commits fires it repeatedly — keep the reaction cheap, or filter to one branch. Useful for kicking off a build or lint pass as work lands. ${ec}`}),eh("CODEBASE_REMOTE_BRANCH","Codebases","Matching remote branch",["codebase.*","agent.*","repo.*"],{description:"Fires when a remote branch matching the codebase's conventions appears.",details:`Lets a branch pushed from elsewhere pull work into this system — creating a worktree for it, or opening a pull request. Needs a fetch to have run for the branch to be visible. ${ec}`}),eh("JIRA_STATUS","Jira","Ticket status changed",es,{description:"Fires when a Jira ticket moves to another status.",details:`Needs Jira polling configured. Seeds \`ticket.*\`. Filter on \`ticket.status\` to react to one column only — without a filter, every transition on every polled ticket starts the workflow. ${ec}`}),eh("JIRA_LABEL","Jira","Jira label set",es,{description:"Fires when a label is applied to a Jira ticket.",details:`The Jira counterpart to the pull request label trigger: a label becomes a manual switch for automation. Filter on the label name. ${ec}`}),eh("JIRA_ASSIGNED_SELF","Jira","Ticket assigned to me",es,{description:"Fires when a ticket is assigned to the account behind the configured Jira credential.",details:`"Me" is whoever the Jira credential authenticates as, not whoever is looking at the screen. The usual start of a "pick up my next ticket" workflow — create a worktree, start a plan. ${ec}`}),eh("JIRA_SOURCE_NEW_TICKET","Jira","New ticket in source",es,{description:"Fires when a ticket appears in a configured Jira source — a saved JQL query or board.",details:`Fires on tickets newly matching the source, which includes existing tickets edited into range, not only freshly created ones. The source itself does the filtering, so keep its JQL tight. Seeds \`ticket.*\`. ${ec}`}),eh("JIRA_MENTION","Jira","Jira comment mention",es,{description:"Fires when the configured Jira account is mentioned in a ticket comment.",details:`Lets someone pull automation into a conversation by mentioning the bot. The comment is seeded under \`comment.*\`, so an AI step can read what was actually asked — treat that text as untrusted input rather than instructions. ${ec}`}),eh("JIRA_SPRINT_STARTED","Jira","Sprint started",es,{description:"Fires when a Jira sprint is started.",details:`Fires per ticket in the sprint, so a sprint of thirty tickets starts thirty runs — mind the workflow's concurrency settings. Good for sprint-opening bookkeeping. ${ec}`}),eh("JIRA_ISSUE_CREATED","Jira","Ticket created",es,{description:"Fires when a Jira ticket is created.",details:`Needs the Jira webhook configured in Settings — the polled Jira triggers only observe tickets something already fetched, so they cannot see a brand-new one. Scope the webhook's JQL filter to the projects you care about, since every created ticket otherwise starts a run. ${ec}`}),eh("JIRA_ISSUE_DELETED","Jira","Ticket deleted",es,{description:"Fires when a Jira ticket is deleted.",details:`Needs the Jira webhook. The ticket is gone by the time this runs, so only the payload's \`ticket.*\` snapshot is available — a step that loads the ticket will fail. Use it for cleanup: close the worktree, cancel the run, archive the branch. ${ec}`}),eh("JIRA_ISSUE_COMMAND","Jira","Ticket comment command",es,{description:"Fires when a comment from an allow-listed Jira account matches a command pattern, such as `/deploy`.",details:`The Jira counterpart to the GitHub issue comment command, and just as strict: an explicit list of Jira account IDs is required, and the pattern must be anchored with \`^\` and \`$\` — publishing fails otherwise. Jira identifies people by opaque account ID, not display name, so copy the ID from the user's Jira profile URL. Treat the comment body as untrusted input rather than instructions. Needs the Jira webhook. ${ec}`}),eh("JIRA_ATTACHMENT_ADDED","Jira","Attachment added",[...es,"attachment.*"],{description:"Fires when a file is attached to a Jira ticket.",details:`Needs the Jira webhook. Seeds \`attachment.*\` with the filename, MIME type, and author. Filter on \`attachment.mimeType\` to react to one kind of upload — a crash log, a design export. ${ec}`}),eh("JIRA_ISSUE_LINKED","Jira","Ticket linked",[...es,"link.*"],{description:"Fires when a Jira issue link is created.",details:`Needs the Jira webhook. Seeds \`link.*\` with the link type and both issue IDs. Filter on \`link.type\` to react to one relationship — "blocks", "duplicates" — rather than every link. ${ec}`}),eh("RUN_STARTED","Plans and sessions","Run started",ei,{description:"Fires when an AI plan or session run begins.",details:`Every run trigger seeds the same shape — \`run.*\` plus the worktree, codebase, repository, and ticket it is attached to. Filter on \`run.kind\` to separate plans from sessions. ${ec}`}),eh("RUN_COMPLETED","Plans and sessions","Run completed",ei,{description:"Fires when an AI run finishes successfully.",details:`The place to hang everything that happens after the agent is done — committing, pushing, opening a pull request, moving the ticket. Filter on \`run.kind\` to react only to plans or only to sessions. ${ec}`}),eh("RUN_QUESTION_NEEDED","Plans and sessions","Run needs an answer",ei,{description:"Fires when an AI run pauses to ask a question, with the pending questions in session data.",details:`The questions arrive under \`run.questions\`, so the Answer run question step can respond without a human — the basis for unattended runs. Answer carefully: an automatic answer to a question the agent should have asked a person is how unwanted changes get made. ${ec}`}),eh("RUN_QUESTION_ANSWERED","Plans and sessions","Run question answered",ei,{description:"Fires when a pending question on an AI run is answered.",details:`Fires however the answer arrived — from a person or from another workflow. Use it to record decisions, or to resume work that was gated on the answer. ${ec}`}),eh("RUN_PAUSED","Plans and sessions","Run paused",ei,{description:"Fires when an AI run is paused.",details:`Covers pauses from any source, including a run that paused itself. A run needing an answer reports separately through Run needs an answer. ${ec}`}),eh("RUN_CONTINUED","Plans and sessions","Run continued",ei,{description:"Fires when a paused AI run resumes.",details:`The counterpart to Run paused. Fires on each resume, so a run that stops and starts repeatedly fires it repeatedly. ${ec}`}),eh("RUN_FAILED","Plans and sessions","Run failed",ei,{description:"Fires when an AI run ends in failure.",details:`The error is in the seeded run data, so a follow-up run can be pointed at what went wrong. Beware of loops — a workflow that reacts by starting another run that fails the same way will keep going. ${ec}`}),eh("RUN_CANCELLED","Plans and sessions","Run cancelled",ei,{description:"Fires when an AI run is cancelled.",details:`Cancellation leaves whatever the run already wrote in the worktree, so cleanup usually means inspecting or reverting rather than assuming nothing happened. ${ec}`}),eh("RUN_PLAN_PLAYED","Plans and sessions","Plan played",ei,{description:"Fires when a run is created by executing a previously completed plan.",details:`Distinguishes plan execution from an ordinary session, which Run started cannot. Lets a workflow treat planned work differently from ad-hoc work. ${ec}`}),eh("RUN_FOLLOW_UP","Plans and sessions","Run follow-up created",ei,{description:"Fires when a run is created as a follow-up to another run.",details:`Does not fire for plan execution, which reports through Plan played. The parent run is in the seeded data, so a workflow can count how deep a follow-up chain has gone and stop it. ${ec}`}),eh("RUN_IMPORTED","Plans and sessions","Provider run imported",ei,{description:"Fires when a run started outside this system is imported from a provider.",details:`Lets work begun in another tool pick up the same automation — labelling, ticket updates, pull requests. The run did not originate here, so its worktree and ticket links may be incomplete. ${ec}`}),eh("RUN_USAGE_THRESHOLD","Plans and sessions","Run usage threshold",ei,{description:"Fires when a single run's token or cost usage crosses a threshold you set.",details:`Scoped to one run, unlike the aggregate Usage threshold. Point the threshold path at the usage figure you care about — a runaway session can then be cancelled automatically. ${ed} ${ec}`}),eh("RUN_EVENT_MATCH","Plans and sessions","Run event or tool matched",ei,{description:"Fires on individual events inside an AI run, including each tool call it makes.",details:`The finest-grained run trigger, and by far the most talkative — a single run produces hundreds of events, and every one is a candidate. Always filter, on the event type or the tool name. Useful for reacting to a specific tool being used; a poor choice for anything expensive. ${ec}`}),...em],eg=new Map(ef.map(e=>[e.kind,e])),ey=t.z.string().min(1).max(128).regex(/^[A-Za-z0-9][A-Za-z0-9_-]*$/),ew=t.z.string().min(1).max(256).regex(/^[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_*\[\]-]+)*$/),eb=t.z.record(t.z.string(),t.z.unknown()).default({}),eE=t.z.object({id:ey,kind:t.z.enum(n.WORKFLOW_TRIGGER_KINDS),name:t.z.string().min(1).max(200).optional(),position:t.z.object({x:t.z.number().finite(),y:t.z.number().finite()}),config:eb}),eS=t.z.object({id:ey,kind:t.z.enum(n.WORKFLOW_STEP_KINDS),name:t.z.string().min(1).max(200).optional(),position:t.z.object({x:t.z.number().finite(),y:t.z.number().finite()}),config:eb,requiredPaths:t.z.array(ew).max(100).default([]),providedPaths:t.z.array(ew).max(100).default([]),retry:t.z.object({maxAttempts:t.z.number().int().min(1).max(20).default(1),strategy:t.z.enum(["FIXED","EXPONENTIAL"]).default("EXPONENTIAL"),delaySeconds:t.z.number().int().min(1).max(86400).default(5)}).default({maxAttempts:1,strategy:"EXPONENTIAL",delaySeconds:5}),failurePolicy:t.z.enum(["FAIL","CONTINUE"]).default("FAIL")}),ev=t.z.object({id:ey,source:ey,target:ey,sourceHandle:t.z.string().min(1).max(100).default("success"),targetHandle:t.z.string().min(1).max(100).default("input")}),eI=t.z.object({format:t.z.literal(H),schemaVersion:t.z.literal(1),name:t.z.string().min(1).max(200),description:t.z.string().max(2e3).default(""),triggers:t.z.array(eE).max(100).default([]),nodes:t.z.array(eS).max(1e3).default([]),edges:t.z.array(ev).max(5e3).default([]),editor:t.z.object({viewport:t.z.object({x:t.z.number(),y:t.z.number(),zoom:t.z.number().positive()}).optional(),handleLayout:t.z.enum(["SIDES","TOP_BOTTOM"]).default("SIDES"),displayLayout:t.z.enum(["REGULAR","BASIC"]).default("REGULAR")}).default({handleLayout:"SIDES",displayLayout:"REGULAR"})});function eA(e,t){return t.map(t=>t.replaceAll("<stepId>",e.id))}function ek(e,t){return e===t||"*"===e||e.endsWith(".*")&&t.startsWith(e.slice(0,-1))}function e_(e){return e.length?new Set([...e[0]].filter(t=>e.every(e=>e.has(t)))):new Set}function eT(e,t){return[...e].some(e=>ek(e,t))}let eC={stepPaths(e){let t=er.get(e);return{requiredPaths:t?.requiredPaths??[],providedPaths:t?.providedPaths??[]}},triggerSeedPaths:e=>eg.get(e)?.seedPaths??[]};function eR(e,t=eC){let r=new Set(e.nodes.map(({id:e})=>e)),i=new Map(e.nodes.map(e=>[e.id,e])),a=new Map,n=new Map;for(let t of e.edges)a.set(t.source,[...a.get(t.source)??[],t.target]),n.set(t.target,[...n.get(t.target)??[],t.source]);let s=new Map(e.nodes.map(e=>[e.id,0]));for(let t of e.edges)r.has(t.source)&&r.has(t.target)&&s.set(t.target,(s.get(t.target)??0)+1);let o=[...s].filter(([,e])=>0===e).map(([e])=>e),l=[];for(;o.length;){let e=o.shift();for(let t of(l.push(e),a.get(e)??[])){if(!r.has(t))continue;let e=(s.get(t)??0)-1;s.set(t,e),0===e&&o.push(t)}}let u=e=>{let t=new Set,r=[...a.get(e)??[]];for(;r.length;){let e=r.shift();t.has(e)||(t.add(e),r.push(...a.get(e)??[]))}return t},c=new Map;for(let t of[...e.triggers,...e.nodes])c.set(t.id,u(t.id));let d=new Map;for(let r of e.nodes){let e=t.stepPaths(r.kind);d.set(r.id,[...eA(r,e.providedPaths),...r.providedPaths,`steps.${r.id}.*`])}let h=new Map,p=[];for(let r of e.triggers){let e=new Set(["workflow.*"]);for(let i of t.triggerSeedPaths(r.kind))e.add(i);for(let t of J(r.kind,r.config))e.add(t);let a=new Map;for(let s of l){if(!c.get(r.id)?.has(s))continue;let o=i.get(s),l=(n.get(s)??[]).filter(e=>e===r.id||a.has(e));if(!l.length)continue;let u=e_(l.map(t=>t===r.id?e:a.get(t))),m=h.get(s);h.set(s,m?e_([m,u]):new Set(u));let f=new Set(d.get(s)??[]),g=[...U(o.kind,"step",o.config)].filter(e=>!eT(f,e));for(let e of new Set([...eA(o,t.stepPaths(o.kind).requiredPaths),...o.requiredPaths,...g]))eT(u,e)||p.push({nodeId:o.id,triggerId:r.id,triggerName:r.name??r.kind,path:e});let y=new Set(u);for(let e of d.get(s)??[])y.add(e);a.set(s,y)}}return{availableBefore:new Map([...h].map(([e,t])=>[e,[...t]])),provides:d,requirementViolations:p}}function eN(e,t=""){return Array.isArray(e)?e.some(e=>eN(e,t)):e&&"object"==typeof e?Object.entries(e).some(([e,t])=>eN(t,e)):"string"==typeof e&&/(token|secret|password|passwd|private.?key|api.?key|authorization)/i.test(t)&&!/(credential.?id|credential.?ids)$/i.test(t)}function eO(e){return Array.isArray(e)?e.some(eO):!!e&&"object"==typeof e&&("UNRESOLVED"===e.referenceStatus||Object.values(e).some(eO))}e.s(["WORKFLOW_SCHEMA_VERSION",0,1,"WORKFLOW_STEP_BY_KIND",0,er,"WORKFLOW_STEP_CATALOG",0,et,"WORKFLOW_TRIGGER_CATALOG",0,ef,"computeWorkflowPathAvailability",0,eR,"emptyWorkflowDefinition",0,function(e="Untitled workflow"){return eI.parse({format:H,schemaVersion:1,name:e,description:"",triggers:[{id:"manual",kind:"MANUAL",position:{x:0,y:100},config:{}}],nodes:[],edges:[],editor:{}})},"hasWorkflowErrors",0,function(e){return e.some(({severity:e})=>"ERROR"===e)},"parseWorkflowDefinition",0,function(e){return eI.parse(e)},"resourceManualSeedPaths",0,J,"sanitizeWorkflowExportDefinition",0,function(e){let t=(e,r="")=>Array.isArray(e)?e.map(e=>t(e,r)):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,r])=>[e,t(r,e)])):"string"==typeof e&&/(token|secret|password|passwd|private.?key|api.?key|authorization)/i.test(r)&&!/(credential.?id|credential.?ids)$/i.test(r)||"string"==typeof e&&/^(?:\/|[A-Za-z]:[\\/]|\\\\)/.test(e)&&/^(?:cwd|folder|path|directory)$/i.test(r)?null:e;return eI.parse(t(e))},"validateWorkflowDefinition",0,function(e){let t=eI.safeParse(e);if(!t.success)return{definition:null,diagnostics:t.error.issues.map(e=>({severity:"ERROR",code:"SCHEMA_INVALID",message:e.message,path:e.path.join(".")}))};let r=t.data,i=[],a=new Set;for(let e of[...r.triggers,...r.nodes])a.has(e.id)&&i.push({severity:"ERROR",code:"DUPLICATE_NODE_ID",message:`Duplicate graph id ${e.id}`,nodeId:e.id}),a.add(e.id);let o=new Set;for(let e of r.edges)o.has(e.id)&&i.push({severity:"ERROR",code:"DUPLICATE_EDGE_ID",message:`Duplicate edge id ${e.id}`}),o.add(e.id),a.has(e.source)&&a.has(e.target)||i.push({severity:"ERROR",code:"EDGE_ENDPOINT_MISSING",message:`Edge ${e.id} references a missing endpoint`}),r.triggers.some(({id:t})=>t===e.target)&&i.push({severity:"ERROR",code:"TRIGGER_HAS_INPUT",message:"Triggers cannot have incoming edges",triggerId:e.target});r.triggers.length||i.push({severity:"ERROR",code:"TRIGGER_REQUIRED",message:"At least one trigger is required"}),r.nodes.length||i.push({severity:"ERROR",code:"STEP_REQUIRED",message:"At least one step is required"});let l=new Set(r.nodes.map(({id:e})=>e)),u=new Map,c=new Map;for(let e of r.edges)u.set(e.source,[...u.get(e.source)??[],e.target]),c.set(e.target,[...c.get(e.target)??[],e.source]);for(let e of r.nodes)(c.get(e.id)??[]).filter(e=>l.has(e)).length>1&&"CONTROL_JOIN"!==e.kind&&i.push({severity:"ERROR",code:"EXPLICIT_JOIN_REQUIRED",message:"Nodes with multiple incoming branches must be explicit join nodes",nodeId:e.id});let d=new Map(r.nodes.map(e=>[e.id,0]));for(let e of r.edges)l.has(e.source)&&l.has(e.target)&&d.set(e.target,(d.get(e.target)??0)+1);let h=[...d].filter(([,e])=>0===e).map(([e])=>e),p=[];for(;h.length;){let e=h.shift();for(let t of(p.push(e),u.get(e)??[])){if(!l.has(t))continue;let e=(d.get(t)??0)-1;d.set(t,e),0===e&&h.push(t)}}p.length!==r.nodes.length&&i.push({severity:"ERROR",code:"DAG_CYCLE",message:"Workflow graphs cannot contain free-form cycles"});let m=new Map,f=e=>{let t=new Set,r=[...u.get(e)??[]];for(;r.length;){let e=r.shift();t.has(e)||(t.add(e),r.push(...u.get(e)??[]))}return t};for(let e of[...r.triggers,...r.nodes])m.set(e.id,f(e.id));for(let e of r.nodes){for(let t of(r.triggers.some(t=>m.get(t.id)?.has(e.id))||i.push({severity:"ERROR",code:"UNREACHABLE_STEP",message:"Step is not reachable from a trigger",nodeId:e.id}),eN(e.config)&&i.push({severity:"ERROR",code:"SECRET_LITERAL",message:"Store secrets as credential references, not workflow literals",nodeId:e.id}),eO(e.config)&&i.push({severity:"ERROR",code:"UNRESOLVED_REFERENCE",message:"Resolve imported references before publishing",nodeId:e.id}),new Set((0,s.invalidWorkflowValueBindings)(e.config))))i.push({severity:"ERROR",code:"SESSION_BINDING_INVALID",message:t,nodeId:e.id});if("CONTROL_SUBWORKFLOW"===e.kind&&"string"!=typeof e.config.versionId&&i.push({severity:"ERROR",code:"SUBWORKFLOW_VERSION_REQUIRED",message:"Sub-workflows must pin a published version",nodeId:e.id}),"SAVED_COMMAND"===e.kind||"CUSTOM_COMMAND"===e.kind){let t=F(e.config);if(r.edges.some(t=>t.source===e.id&&"match"===t.sourceHandle)&&!t&&i.push({severity:"ERROR",code:"COMMAND_MATCH_PATTERN_REQUIRED",message:"The match connector requires an output pattern",nodeId:e.id}),t){void 0!==e.config.outputMatchMode&&"ONCE"!==e.config.outputMatchMode&&"EACH_MATCH"!==e.config.outputMatchMode&&i.push({severity:"ERROR",code:"COMMAND_MATCH_MODE_INVALID",message:"Output match behavior must be Once or Each match",nodeId:e.id}),"FIRE_AND_FORGET"===e.config.completionMode&&i.push({severity:"ERROR",code:"COMMAND_MATCH_REQUIRES_WAIT",message:"Output matching requires Wait for exit completion",nodeId:e.id});try{z(t)}catch(t){i.push({severity:"ERROR",code:"COMMAND_MATCH_PATTERN_INVALID",message:t instanceof Error?t.message:String(t),nodeId:e.id})}let a=t=>r.edges.filter(r=>r.source===e.id&&r.sourceHandle===t).map(({target:e})=>e),n=e=>{let t=new Set,i=[...e];for(;i.length;){let e=i.shift();t.has(e)||(t.add(e),i.push(...r.edges.filter(t=>t.source===e).map(({target:e})=>e)))}return t},s=n(a("match")),o=n([...a("success"),...a("failure")]);[...s].some(e=>o.has(e))&&i.push({severity:"ERROR",code:"COMMAND_MATCH_BRANCH_RECONVERGES",message:"A command match branch cannot reconverge with its success or failure branch",nodeId:e.id})}}}for(let e of r.triggers){for(let t of((u.get(e.id)??[]).length||i.push({severity:"ERROR",code:"TRIGGER_DISCONNECTED",message:"Trigger is not connected to a step",triggerId:e.id}),eN(e.config)&&i.push({severity:"ERROR",code:"SECRET_LITERAL",message:"Store secrets as credential references, not trigger literals",triggerId:e.id}),eO(e.config)&&i.push({severity:"ERROR",code:"UNRESOLVED_REFERENCE",message:"Resolve imported references before publishing",triggerId:e.id}),new Set((0,s.invalidWorkflowValueBindings)(e.config))))i.push({severity:"ERROR",code:"SESSION_BINDING_INVALID",message:t,triggerId:e.id});if((0,n.isResourceTriggerKind)(e.kind)&&!W(e.config)&&i.push({severity:"ERROR",code:"RESOURCE_KIND_REQUIRED",message:"Resource triggers must target a single resource kind; add one trigger per kind",triggerId:e.id}),(0,n.isChoiceTriggerKind)(e.kind)){let t=V(e.config),a=Array.isArray(e.config.choices)?e.config.choices.length:0;t.length&&t.length===a||i.push({severity:"ERROR",code:"TRIGGER_CHOICES_REQUIRED",message:"Choice triggers need at least one option, each with a unique key",triggerId:e.id});let n=new Set(t.map(({key:e})=>e));for(let t of r.edges)t.source===e.id&&(n.has(t.sourceHandle)||i.push({severity:"ERROR",code:"TRIGGER_CHOICE_HANDLE_UNKNOWN",message:`Connection ${t.id} leaves an option that no longer exists`,triggerId:e.id}))}if("GITHUB_ISSUE_COMMAND"===e.kind||"JIRA_ISSUE_COMMAND"===e.kind||"GITLAB_NOTE_COMMAND"===e.kind){let t="JIRA_ISSUE_COMMAND"===e.kind,r="GITLAB_NOTE_COMMAND"===e.kind,a=t?e.config.allowedAccountIds:r?e.config.allowedUsernames:e.config.allowedLogins,n=e.config.commandPattern;(!Array.isArray(a)||!a.length||a.some(e=>"string"!=typeof e||!e.trim()))&&i.push({severity:"ERROR",code:"ISSUE_COMMAND_ALLOWLIST_REQUIRED",message:t?"Issue command triggers require an explicit Jira account ID allow-list":r?"Note command triggers require an explicit GitLab username allow-list":"Issue command triggers require an explicit GitHub login allow-list",triggerId:e.id}),"string"==typeof n&&n.startsWith("^")&&n.endsWith("$")||i.push({severity:"ERROR",code:"ISSUE_COMMAND_PATTERN_ANCHORED",message:"Issue command patterns must be anchored with ^ and $",triggerId:e.id})}}for(let e of eR(r).requirementViolations)i.push({severity:"ERROR",code:"REQUIREMENT_UNSATISFIED",message:`${e.path} is not guaranteed on the path from ${e.triggerName}`,nodeId:e.nodeId,triggerId:e.triggerId,path:e.path});for(let e=0;e<r.nodes.length;e+=1){let t=r.nodes[e],a=[...eA(t,er.get(t.kind).providedPaths),...t.providedPaths].filter(e=>!e.startsWith(`steps.${t.id}.`));for(let n=e+1;n<r.nodes.length;n+=1){let e=r.nodes[n];if(m.get(t.id)?.has(e.id)||m.get(e.id)?.has(t.id))continue;let s=[...eA(e,er.get(e.kind).providedPaths),...e.providedPaths].filter(t=>!t.startsWith(`steps.${e.id}.`));a.some(e=>s.some(t=>ek(e,t)||ek(t,e)))&&i.push({severity:"ERROR",code:"PARALLEL_WRITE_CONFLICT",message:`Parallel steps ${t.name??t.id} and ${e.name??e.id} can write the same session-data path`,nodeId:e.id})}}return{definition:r,diagnostics:i}},"workflowResourceKind",0,W,"workflowTriggerChoices",0,V],497800)},337951,e=>{"use strict";var t=e.i(497800),r=e.i(835544);function i(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 a(e,t){return e.nodes.find(e=>e.id===t)??e.triggers.find(e=>e.id===t)}function n(e){return(0,r.isChoiceTriggerKind)(e.kind)?(0,t.workflowTriggerChoices)(e.config).map(({key:e})=>e):(0,r.workflowStaticSourceHandles)(e.kind)}function s(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 o(e,t){let r=a(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=n(r),s=t.sourceHandle??i[0];if(!s)throw Error(`${t.source} offers no connectors yet — a choice trigger needs its options set first`);if(!i.includes(s))throw Error(`${t.source} has no ${s} connector; it offers ${i.join(", ")}`);let o=t.targetHandle??"input",l=e.edges.find(e=>e.source===t.source&&e.target===t.target&&e.sourceHandle===s);if(l)return{definition:e,edgeId:l.id};let u=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:u,source:t.source,target:t.target,sourceHandle:s,targetHandle:o}]},edgeId:u}}e.s(["addWorkflowStep",0,function(e,t){let r=i(e,"node"),n={id:r,kind:t.kind,name:t.name??void 0,position:t.position??function(e,t){let r=t?a(e,t):void 0,i=r?r.position.x+320:320,n=r?r.position.y:120,s=[...e.nodes,...e.triggers].filter(e=>160>Math.abs(e.position.x-i)).map(e=>e.position.y),o=n;for(;s.some(e=>80>Math.abs(e-o));)o+=160;return{x:i,y:o}}(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"},s={...e,nodes:[...e.nodes,n]};if(!t.connectFrom)return{definition:s,nodeId:r,edgeId:null};let l=o(s,{source:t.connectFrom.from,target:r,sourceHandle:t.connectFrom.sourceHandle??null});return{definition:l.definition,nodeId:r,edgeId:l.edgeId}},"addWorkflowTrigger",0,function(e,t){let r=i(e,"trigger"),a={id:r,kind:t.kind,name:t.name??void 0,config:t.config??{},position:t.position??{x:0,y:100+140*e.triggers.length}};return{definition:{...e,triggers:[...e.triggers,a]},triggerId:r}},"availableSourceHandles",0,n,"connectWorkflowNodes",0,o,"disconnectWorkflowNodes",0,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]}},"layoutWorkflowDefinition",0,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),u=e.nodes.map(o);return{...e,triggers:l,nodes:u}},"removeWorkflowGraphNode",0,function(e,t,r={}){if(!a(e,t))throw Error(`${t} is not in this workflow`);let i=e.edges.filter(e=>e.target===t),n=e.edges.filter(e=>e.source===t),s=e.edges.filter(e=>e.source!==t&&e.target!==t),l={...e,nodes:e.nodes.filter(e=>e.id!==t),triggers:e.triggers.filter(e=>e.id!==t),edges:s};if(!r.reconnect)return l;for(let e of i)for(let t of n)l=o(l,{source:e.source,sourceHandle:e.sourceHandle,target:t.target,targetHandle:t.targetHandle}).definition;return l},"updateWorkflowStep",0,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:s(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)}},"updateWorkflowTrigger",0,function(e,t){let i=e.triggers.find(({id:e})=>e===t.triggerId);if(!i)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 a={...i,name:t.name??i.name,config:s(i.config,t),position:t.position??i.position},o=new Set(n(a)),l=(0,r.isChoiceTriggerKind)(a.kind)?e.edges.filter(e=>e.source!==a.id||o.has(e.sourceHandle)):e.edges;return{...e,triggers:e.triggers.map(e=>e.id===a.id?a:e),edges:l}}])},887802,e=>{"use strict";let t={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"}],tailscale:[{name:"operationId",description:"Tailscale Serve operation id"},{name:"status",description:"Fleet operation status"},{name:"templateId",description:"Tailscale Serve template id"},{name:"operation",description:"Durable operation and per-agent progress"},{name:"overview",description:"Fleet templates and agent Tailscale identity"}],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"}]},r=new Map(Object.entries(t).flatMap(([e,t])=>t.map(t=>[`${e}.${t.name}`,t.description])));function i(e){return e.split(".")[0]??e}e.s(["expandSessionPaths",0,function(e){let a=new Map,n=e=>{a.has(e.path)||a.set(e.path,e)};for(let a of e){let e=a.trim();if(e&&"*"!==e){if(e.endsWith(".*")){let r=e.slice(0,-2),a=t[i(r)];if(a)for(let e of a)n({path:`${r}.${e.name}`,description:e.description});else n({path:e});continue}n({path:e,description:function(e){let t=e.split(".");if(t.length<2)return;let a=t[t.length-1];return r.get(`${i(e)}.${a}`)}(e)})}}return[...a.values()].sort((e,t)=>e.path.localeCompare(t.path))}])},835544,e=>{"use strict";let t=new Set(["MANUAL_CHOICE","RESOURCE_MANUAL_CHOICE"]),r=new Set(["RESOURCE_MANUAL","RESOURCE_MANUAL_CHOICE"]);function i(e){return t.has(e)}let a=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;e.s(["WORKFLOW_CHOICE_KEY_PATTERN",0,a,"WORKFLOW_QUICK_ACTION_KINDS",0,["STANDARD","MERGE_CONFLICT","GITHUB_ACTIONS","GITLAB_PIPELINES","NONE"],"WORKFLOW_RESOURCE_KINDS",0,["BUILD","CODEBASE","JIRA_TICKET","AGENT_RUN","GITHUB_PIPELINE","GITHUB_JOB","GITLAB_MERGE_REQUEST","GITLAB_PIPELINE","GITLAB_JOB","PULL_REQUEST","WORKTREE","COMMAND_RUN","SKILL","SKILL_SYNC","IOS_DEVICE","SIGNING_PROFILE","PUSH_NOTIFICATION_BATCH","BUILD_DATA_COLLECTION"],"WORKFLOW_STEP_KINDS",0,["JIRA_LOAD_TICKET","JIRA_TRANSITION","JIRA_COMMENT","JIRA_ASSIGN","JIRA_UPDATE_FIELDS","JIRA_RESOLVE_BRANCH","GITHUB_LOAD_PR","GITHUB_MERGE_PR","GITHUB_COLLECT_REVIEW_THREADS","GITHUB_REPLY_REVIEW_THREAD","GITHUB_SET_REVIEW_THREAD_RESOLVED","GITHUB_CREATE_PR","GITHUB_SET_PR_LABELS","GITHUB_RETRY_PIPELINE","GITHUB_RETRY_JOB","GITHUB_CANCEL_WORKFLOW_RUN","GITHUB_SAVE_AUTO_RETRY","GITHUB_WAIT_CHECKS","WORKTREE_CREATE","WORKTREE_CHANGE_BRANCH","WORKTREE_COMMIT","WORKTREE_REFRESH_PULL_REQUEST","WORKTREE_OPERATION","WORKTREE_PREPARATION","WORKTREE_SET_AUTO_SYNC","WORKTREE_SET_AUTO_MERGE","WORKTREE_DELETE","WORKTREE_MOVE","WORKTREE_INSPECT","WORKTREE_INSPECT_GIT","WORKTREE_GIT_OPERATION","WORKTREE_WAIT_PUSH_READY","WORKTREE_SNAPSHOT","CODEBASE_FETCH_REFRESH","CODEBASE_INSPECT_GIT","CODEBASE_GIT_OPERATION","BUILD_START","BUILD_READ_TEST_RESULTS","BUILD_READ_COVERAGE","BUILD_IMPORT_COVERAGE","BUILD_EXPORT","BUILD_DEPLOY","BUILD_CANCEL","DISK_SPACE_LOAD","DISK_SPACE_REFRESH","DISK_SPACE_UPDATE_THRESHOLDS","DISK_SPACE_SET_MONITORING","DISK_SPACE_SET_PRESSURE_MODE","SKILL_APPLY","RUN_CREATE_PLAN","RUN_CREATE_SESSION","RUN_PLAY_PLAN","RUN_FOLLOW_UP","RUN_STEER","RUN_ANSWER","RUN_PAUSE","RUN_CONTINUE","RUN_CANCEL","RUN_REVISE_ANSWER","RUN_READ_RESULT","RUN_CAPTURE_CHECKPOINT","RUN_ARCHIVE_DELETE","NOTIFICATION_SEND","IOS_PUSH_SEND","HUMAN_CONFIRM","HUMAN_CHOICE","CONTROL_IF","CONTROL_JOIN","CONTROL_DELAY","CONTROL_WAIT_UNTIL","CONTROL_FOR_EACH","CONTROL_TRY","CONTROL_SET_VARIABLE","CONTROL_SUBWORKFLOW","SAVED_COMMAND","CUSTOM_COMMAND","COMMAND_RERUN","COMMAND_TERMINATE","COMMAND_READ_OUTPUT","WORKTREE_INSPECT_DIFF","WORKTREE_UPDATE_METADATA","WORKTREE_MOVE_CONTROL","BUILD_REBUILD","BUILD_GENERATE_REPORT","BUILD_DELETE","SKILL_PREPARE_SYNC","SKILL_RESOLVE_SYNC","SKILL_SKIP_SYNC","BUILD_DATA_REFRESH","BUILD_DATA_DELETE","BUILD_DATA_SET_LOCK","TAILSCALE_SERVE_INSPECT","TAILSCALE_SERVE_UPSERT_TEMPLATE","TAILSCALE_SERVE_SET_AGENT_ENABLED","TAILSCALE_SERVE_DELETE_TEMPLATE","SIGNING_REFRESH","SIGNING_SYNC_PROFILE","SIGNING_DELETE_EXPIRED","IOS_DEVICE_REGISTER","IOS_DEVICE_REJECT","AGENT_RECONCILE","AGENT_UPDATE_CADENCE","CCUSAGE_COLLECT","MODEL_COST_REFRESH","GITHUB_UPDATE_PR","GITHUB_SUBMIT_REVIEW","GITHUB_REQUEST_REVIEWERS","GITHUB_DISPATCH_WORKFLOW","GITLAB_LOAD_MR","GITLAB_CREATE_MR","GITLAB_UPDATE_MR","GITLAB_SUBMIT_REVIEW","GITLAB_REPLY_DISCUSSION","GITLAB_SET_DISCUSSION_RESOLVED","GITLAB_MERGE_MR","GITLAB_SET_MR_LABELS","GITLAB_REQUEST_REVIEWERS","GITLAB_CREATE_PIPELINE","GITLAB_RETRY_PIPELINE","GITLAB_RETRY_JOB","GITLAB_CANCEL_PIPELINE","GITLAB_SAVE_AUTO_RETRY","GITLAB_WAIT_PIPELINE","JIRA_CREATE_TICKET","JIRA_ADD_WORKLOG","JIRA_LINK_TICKETS","TERMINAL_RUN","MCP_CALL","SSE_ENDPOINT_ACTION","SSE_MOCK_ACTION","SSE_STORAGE_ACTION","SSE_BREAKPOINT_RESOLVE","SSE_HISTORY_CLEAR","SSE_SCRIPT_TEST"],"WORKFLOW_TRIGGER_KINDS",0,["MANUAL","MANUAL_CHOICE","RESOURCE_MANUAL","RESOURCE_MANUAL_CHOICE","SCHEDULE","WORKFLOW_FINISHED","GITHUB_PR_STATE","GITHUB_REVIEW_CHANGES_REQUESTED","GITHUB_REVIEW_COMMENT","GITHUB_PR_CLOSED","GITHUB_CHECK_FAILED","GITHUB_PUSH_DEFAULT","GITHUB_WORKFLOW_SUCCEEDED","GITHUB_ISSUE_COMMAND","GITHUB_ACTIONS_RESULT","GITHUB_PR_LABEL","BUILD_RESULT","BUILD_TEST_THRESHOLD","BUILD_COVERAGE_THRESHOLD","BUILD_HOOK_FAILED","AGENT_CONNECTION","AGENT_JOB_FAILED","AGENT_DISK_REPORT","AGENT_DISK_THRESHOLD","AGENT_DISK_STATE_CHANGED","AGENT_DISK_CLEANUP_RESULT","CCUSAGE_THRESHOLD","WORKTREE_CREATED","WORKTREE_BEHIND","WORKTREE_CONFLICT","WORKTREE_MISSING","WORKTREE_DIVERGED","WORKTREE_DIRTY_DURATION","WORKTREE_NEW_COMMIT","CODEBASE_REMOTE_BRANCH","JIRA_STATUS","JIRA_LABEL","JIRA_ASSIGNED_SELF","JIRA_SOURCE_NEW_TICKET","JIRA_MENTION","JIRA_SPRINT_STARTED","JIRA_ISSUE_CREATED","JIRA_ISSUE_DELETED","JIRA_ISSUE_COMMAND","JIRA_ATTACHMENT_ADDED","JIRA_ISSUE_LINKED","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","COMMAND_RUN_RESULT","COMMAND_OUTPUT_MATCH","SKILL_SYNC_RESULT","SKILL_SYNC_CONFLICT","GITHUB_PIPELINE_STATUS_CHANGED","GITHUB_PR_SYNCHRONIZED","GITHUB_REVIEW_APPROVED","GITLAB_MR_STATE","GITLAB_REVIEW_CHANGES_REQUESTED","GITLAB_REVIEW_COMMENT","GITLAB_MR_CLOSED","GITLAB_PIPELINE_FAILED","GITLAB_PUSH_DEFAULT","GITLAB_PIPELINE_SUCCEEDED","GITLAB_NOTE_COMMAND","GITLAB_PIPELINE_RESULT","GITLAB_MR_LABEL","GITLAB_PIPELINE_STATUS_CHANGED","GITLAB_MR_SYNCHRONIZED","GITLAB_REVIEW_APPROVED","GITLAB_JOB_STATUS_CHANGED","JIRA_TICKET_UPDATED","JIRA_COMMENT_ADDED","JIRA_WORKLOG_ADDED","JIRA_SPRINT_ENDED","CODEBASE_SYNC_STATE_CHANGED","CODEBASE_OPERATION_FAILED","WORKTREE_SYNC_STATE_CHANGED","WORKTREE_AUTOMATION_RESULT","WORKTREE_CLEAN","PUSH_NOTIFICATION_RESULT","IOS_DEVICE_ENROLLED","IOS_DEVICE_REGISTRATION_RESULT","SIGNING_OPERATION_RESULT","SIGNING_ASSET_EXPIRING","BUILD_DATA_THRESHOLD","BUILD_DATA_CLEANUP_RESULT","POLLING_OPERATION_STATE","MODEL_COST_CATALOG_CHANGED","CREDENTIAL_STORE_DEGRADED","AGENT_RESOURCE_THRESHOLD","AGENT_VERSION_CHANGED","TOOL_CALL_RESULT","SSE_REQUEST_OPENED","SSE_EVENT_EMITTED","SSE_BREAKPOINT_WAITING","SSE_BREAKPOINT_RESOLVED","SSE_STREAM_COMPLETED","SSE_STREAM_FAILED"],"isChoiceTriggerKind",0,i,"isResourceTriggerKind",0,function(e){return r.has(e)},"isWorkflowChoiceKey",0,function(e){return"string"==typeof e&&a.test(e)},"workflowStaticSourceHandles",0,function(e){return i(e)?[]:"CONTROL_IF"===e?["true","false"]:"CONTROL_FOR_EACH"===e?["body","empty"]:"CONTROL_TRY"===e?["success","catch"]:"SAVED_COMMAND"===e||"CUSTOM_COMMAND"===e?["success","failure","match"]:["success","failure"]}])},296581,330223,142118,e=>{"use strict";e.i(497800);var t=e.i(835544);function r(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 i(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}function a(e,t,r){return i(e[t])[r]}function n(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 s=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"]),o=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"]),l=new Set(["BUILD_RESULT","BUILD_TEST_THRESHOLD","BUILD_COVERAGE_THRESHOLD","BUILD_HOOK_FAILED"]),u=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"]),c=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"]),d=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"]);e.s(["pullRequestResourceId",0,r,"workflowTriggerResourceLink",0,function(e,h){let p=e.trim().toUpperCase(),m=i(h.sessionData);if((0,t.isResourceTriggerKind)(p)){let e=h.resourceKind,t="string"==typeof e?e.toUpperCase():null,r="GITHUB_JOB"===t?a(m,"job","url"):"GITLAB_JOB"===t?a(m,"job","webUrl"):"GITHUB_PIPELINE"===t?a(m,"pipeline","url"):"GITLAB_PIPELINE"===t?a(m,"pipeline","webUrl"):"GITLAB_MERGE_REQUEST"===t?a(m,"pr","webUrl"):null;return"string"==typeof e?n(e.toUpperCase(),h.resourceId,{url:"string"==typeof r?r:null,metadata:"AGENT_RUN"===e.toUpperCase()?{runKind:a(m,"run","kind")}:null}):null}if(s.has(p))return n("JIRA_TICKET",a(m,"ticket","key"));if(o.has(p))return n("AGENT_RUN",a(m,"run","id"),{metadata:{runKind:a(m,"run","kind")}});if(l.has(p))return n("BUILD",a(m,"build","id"));if(u.has(p))return n("WORKTREE",a(m,"worktree","id"));if("CODEBASE_REMOTE_BRANCH"===p||"CODEBASE_SYNC_STATE_CHANGED"===p||"CODEBASE_OPERATION_FAILED"===p)return n("CODEBASE",a(m,"codebase","id"));if("COMMAND_RUN_RESULT"===p||"COMMAND_OUTPUT_MATCH"===p)return n("COMMAND_RUN",a(m,"command","id"));if("SKILL_SYNC_RESULT"===p||"SKILL_SYNC_CONFLICT"===p)return n("SKILL_SYNC",a(m,"skillSync","id"));if("IOS_DEVICE_ENROLLED"===p||"IOS_DEVICE_REGISTRATION_RESULT"===p)return n("IOS_DEVICE",a(m,"device","id"));if("SIGNING_OPERATION_RESULT"===p||"SIGNING_ASSET_EXPIRING"===p)return n("SIGNING_PROFILE",a(m,"signingProfile","id"));if("PUSH_NOTIFICATION_RESULT"===p)return n("PUSH_NOTIFICATION_BATCH",a(m,"pushBatch","id"));if("BUILD_DATA_THRESHOLD"===p||"BUILD_DATA_CLEANUP_RESULT"===p)return n("BUILD_DATA_COLLECTION",a(m,"buildData","id"));if(p.startsWith("SSE_")){let e=i(m.sse),t=a(e,"request","id");return n("SSE_EVENT_EMITTED"===p?"SSE_EVENT":"SSE_REQUEST","SSE_EVENT_EMITTED"===p?a(e,"event","id"):t,{url:`/sse/history?requestId=${encodeURIComponent(String(t??""))}`})}if("AGENT_JOB_FAILED"===p)return n("AGENT_JOB",a(i(m.steps),"trigger","id"));if("AGENT_CONNECTION"===p||"AGENT_DISK_REPORT"===p||"AGENT_DISK_THRESHOLD"===p||"AGENT_DISK_STATE_CHANGED"===p||"AGENT_DISK_CLEANUP_RESULT"===p||"CCUSAGE_THRESHOLD"===p)return n("AGENT",a(m,"agent","id")??a(m,"codebase","agentId"));if("WORKFLOW_FINISHED"===p)return n("WORKFLOW_RUN",a(h,"run","id"));if(c.has(p)){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}(a(m,"repo","displayOrigin")),t=Number(a(m,"pr","number"));return e&&Number.isInteger(t)&&t>0?n("PULL_REQUEST",r(e.owner,e.repository,t)):null}if(d.has(p)){let e=a(m,"pipeline","url");return n("GITHUB_WORKFLOW_RUN",a(m,"pipeline","runId"),{url:"string"==typeof e?e:null})}return"GITHUB_PUSH_DEFAULT"===p?n("CODEBASE_REPOSITORY",a(m,"repo","id")):null}],296581);var h=e.i(483291),p=e.i(361617);let m=["","aa"," ","a a","a\na"," a","a "];function f(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 g(e,t){return f(e.cadenceSeconds,1)??Math.max(1,t)}e.s(["compileCommandOutputPattern",0,function(e,t=!1){(0,p.validateCommandOutputPattern)(e);try{let r=(0,h.compileRe2)(e,{flags:t?"g":"",label:"Output pattern"});for(let t of m){let r=(0,h.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)}`)}}],330223),e.s(["waitCadenceSeconds",0,g,"waitElapsedText",0,function(e){let t=Math.max(0,Math.round(e/1e3)),r=Math.floor(t/3600),i=Math.floor(t%3600/60);return r?`${r}h ${i}m`:i?`${i}m ${t%60}s`:`${t}s`},"waitKindText",0,function(e){return e.toLowerCase().replaceAll("_"," ")},"waitResumeAfter",0,function(e,t=1){return new Date(Date.now()+1e3*g(e,t))},"waitTimeoutAt",0,function(e,t=null){let r=f(e.timeoutSeconds,10)??(null===t?null:f(t,10));return null===r?null:new Date(Date.now()+1e3*r)}],142118)},366367,e=>{"use strict";var t=e.i(807055),r=e.i(184015),i=e.i(119909),a=e.i(243783),n=e.i(296581),s=e.i(499162),o=e.i(361617),l=e.i(330223),u=e.i(142118);let c=(e,t)=>{if(!e||"object"!=typeof e||Array.isArray(e))throw Error(`${t} must be an object`);return e},d=(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()},h=(e,t=2e4)=>null==e||""===e?null:d(e,"Value",t),p=(e,t,r,i)=>d(e.node.config[t]??(0,s.getSessionValue)(e.sessionData,r),i,500),m=(e,t="operation")=>`${e.run.id}:${e.attempt.id}:${t}`,f=(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:(0,u.waitResumeAfter)(e.node.config),timeoutAt:(0,u.waitTimeoutAt)(e.node.config)}:void 0}),g=(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:(0,u.waitResumeAfter)(e.node.config),timeoutAt:(0,u.waitTimeoutAt)(e.node.config,t.timeoutSeconds??3600)}}),y=(e,t,r,i,a)=>({kind:e,resourceId:t,label:r,url:i,metadata:a}),w=(e,t)=>y("JIRA_TICKET",e,t??e);function b(e,t,r){let i=A(e);return y("PULL_REQUEST",(0,n.pullRequestResourceId)(i.owner,i.name,R(e)),t??"Pull request",r)}function E(e){let t=I(e),r=C(e);return t&&r?y("PULL_REQUEST",(0,n.pullRequestResourceId)(t.owner,t.name,r),"Pull request"):null}function S(e){let t=e.node.config.workflowRunId??(0,s.getSessionValue)(e.sessionData,"pipeline.runId"),r=(0,s.getSessionValue)(e.sessionData,"pipeline.url");return("string"==typeof t||"number"==typeof t)&&"string"==typeof r&&r?y("GITHUB_WORKFLOW_RUN",String(t),"Workflow run",r):null}function v(e){let t=(0,s.getSessionValue)(e.sessionData,"run.kind");if("PLAN"!==t&&"SESSION"!==t)return null;let r=function(e){try{return L(e)}catch{return null}}(e);return r?y("AGENT_RUN",r,t,`/${"PLAN"===t?"plans":"sessions"}/${r}`,{runKind:t}):null}function I(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 A(e){let t=I(e);if(!t)throw Error("GitHub owner and repository are required");return t}function k(e){let t=c(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 _(e){let t=c(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 T(e){return d(e.node.config.issueKey??(0,s.getSessionValue)(e.sessionData,"ticket.key"),"Jira issue key",100)}function C(e){let t=e.node.config.number??(0,s.getSessionValue)(e.sessionData,"pr.number"),r="string"==typeof t?Number(t):t;return"number"==typeof r&&Number.isInteger(r)&&r>=1?r:null}function R(e){let t=C(e);if(!t)throw Error("Pull request number is required");return t}function N(e){return p(e,"worktreeId","worktree.id","Worktree ID")}function O(e){return p(e,"codebaseId","codebase.id","Codebase ID")}function D(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:h(e.node.config.branchName??(0,s.getSessionValue)(e.sessionData,"worktree.branch"),500),ticketKey:"TICKET"===t?h(e.node.config.ticketKey??(0,s.getSessionValue)(e.sessionData,"ticket.key"),100):null,baseBranch:d(e.node.config.baseBranch??(0,s.getSessionValue)(e.sessionData,"worktree.baseBranch")??(0,s.getSessionValue)(e.sessionData,"repo.defaultBranch"),"Base branch",500)}}function P(e){return p(e,"buildId","build.id","Build ID")}function x(e){return d(e.node.config.agentId??(0,s.getSessionValue)(e.sessionData,"agent.id")??(0,s.getSessionValue)(e.sessionData,"codebase.agentId"),"Agent ID",500)}function L(e){let t=e.node.config.runId;if("string"==typeof t&&t)return t;let r=e.node.config.sourceStepId;return"string"==typeof r?d((0,s.getSessionValue)(e.sessionData,`run.${r}.id`),"Agent run ID",500):d((0,s.getSessionValue)(e.sessionData,"run.id"),"Agent run ID",500)}function U(e,t){let r,i,a=e.node.config.worktreeConcurrencyLimit;return{kind:t,worktreeId:(r=e.node.config.worktreeId,i=(0,s.getSessionValue)(e.sessionData,"worktree.id"),"string"==typeof r&&r===e.run.workflowId&&"string"==typeof i&&i!==r?d(i,"Worktree ID",500):N(e)),jiraIssueKey:h(e.node.config.jiraIssueKey??(0,s.getSessionValue)(e.sessionData,"ticket.key"),100),provider:d(e.node.config.provider??"CODEX","Provider",50),model:d(e.node.config.model,"Model",200),effort:h(e.node.config.effort,50),webSearchEnabled:!0===e.node.config.webSearchEnabled,prompt:d(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}}e.s(["registerWorkflowAdapters",0,function(e,I,C){var B,M,q,j,$,G,F,z,H,V,K,W,J,Y,Q,Z;let X,ee;B=e,M=C,B.registerWaitPoller("AGENT_JOB",async e=>{let t=await M.agentControl.getJob(e);return t?new Set(["QUEUED","RUNNING"]).has(t.status)?{pending:!0,pollAfterSeconds:2}:{pending:!1,result:t.resultJson?{...c(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"}}),B.registerWaitPoller("AGENT_JOBS",async e=>{let t=c(JSON.parse(e),"Agent jobs wait"),r=Array.isArray(t.ids)?t.ids.map(e=>d(e,"Agent job ID",500)):[];if(!r.length)return{pending:!1,result:{jobs:[]}};let i=await Promise.all(r.map(e=>M.agentControl.getJob(e)));if(i.some(e=>!e))return{pending:!1,error:"Agent job disappeared"};let a=i.filter(e=>!!e);if(a.some(e=>new Set(["QUEUED","RUNNING"]).has(e.status)))return{pending:!0,pollAfterSeconds:2};let n=a.map(e=>({id:e.id,status:e.status,error:e.error})),s=n.filter(({status:e})=>"SUCCEEDED"!==e);return{pending:!1,result:{jobs:n,sessionPatch:{signing:{jobs:n}}},error:s.length?s.map(({id:e,status:t,error:r})=>r?`${e}: ${r}`:`${e}: ${t.toLowerCase()}`).join("; "):null}}),B.registerWaitPoller("AGENT_RUN",async e=>{let t=await M.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"}}),B.registerWaitPoller("COMMAND_RUN",async e=>{let t=await M.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"}}),B.registerWaitPoller("BUILD",async e=>{let t=await M.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"}}),B.registerWaitPoller("BUILD_DATA_COLLECTION",async e=>{let t=await M.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"}}),B.registerWaitPoller("TAILSCALE_SERVE_OPERATION",async e=>{let t=await M.tailscale.operation(e);return t?["SUCCEEDED","FAILED","PARTIAL_FAILED"].includes(t.status)?{pending:!1,result:{...t,sessionPatch:{tailscale:{operation:t,operationId:t.id,status:t.status,templateId:t.templateId}}},error:"SUCCEEDED"===t.status?null:`Tailscale Serve operation ${t.status.toLowerCase().replaceAll("_"," ")}`}:{pending:!0,pollAfterSeconds:2}:{pending:!1,error:"Tailscale Serve operation disappeared"}}),B.registerWaitPoller("SIGNING_OPERATIONS",async e=>{let t=c(JSON.parse(e),"Signing operations wait"),r=Array.isArray(t.ids)?t.ids.map(e=>d(e,"Signing operation ID",500)):[];if(!r.length)return{pending:!1,result:{operations:[]}};let i=(await M.signingAssets.operations(200)).filter(({id:e})=>r.includes(e));if(i.length!==r.length)return{pending:!1,error:"Signing operation disappeared"};let a=new Set(["SUCCEEDED","FAILED","CANCELLED","TIMED_OUT"]);if(i.some(({status:e})=>!a.has(e)))return{pending:!0,pollAfterSeconds:2};let n=i.filter(({status:e})=>"SUCCEEDED"!==e);return{pending:!1,result:{operations:i,sessionPatch:{signing:{operations:i}}},error:n.length?n.map(({id:e,error:t,status:r})=>t?`${e}: ${t}`:`${e}: ${r.toLowerCase()}`).join("; "):null}}),B.registerWaitPoller("SKILL_RUN",async e=>{let t=await M.skills.getRun(e);return t?("READY"===t.status&&(t=await M.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"}}),B.registerWaitPoller("WORKTREE_MOVE",async e=>{let t=await M.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 r=t.targetWorktreeId?await M.worktrees.workflowSessionDataForWorktree(t.targetWorktreeId,{includeMissing:!0}):{};return{pending:!1,result:{id:t.id,status:t.status,targetWorktreeId:t.targetWorktreeId,sessionPatch:r},error:"SUCCEEDED"===t.status?null:t.error||`Worktree move ${t.status.toLowerCase()}`}}),B.registerWaitPoller("WORKTREE_PUSH_READY",async e=>{let t=await (0,a.getPrismaClient)(),r=await t.worktree.findUnique({where:{id:e}});if(!r)return{pending:!1,error:"Worktree disappeared"};if("READY"!==r.pushStatus)return{pending:!0,pollAfterSeconds:5};let i=await M.worktrees.workflowSessionDataForWorktree(r.id,{includeMissing:!0});return{pending:!1,result:{id:r.id,pushStatus:r.pushStatus,sessionPatch:i}}}),B.registerWaitPoller("WORKFLOW_RUN",async e=>{let t=await B.run(e);return t?new Set(["SUCCEEDED","FAILED","CANCELLED"]).has(t.status)?{pending:!1,result:{id:t.id,status:t.status,sessionData:JSON.parse(t.sessionDataJson)},error:"SUCCEEDED"===t.status?null:t.error||`Sub-workflow ${t.status.toLowerCase()}`}:{pending:!0,pollAfterSeconds:3}:{pending:!1,error:"Sub-workflow disappeared"}}),B.registerWaitPoller("RUN_ANSWER_REVISION",async e=>{let t=c(JSON.parse(e),"Answer revision wait"),r=d(t.batchId,"Question batch ID",500),i=await M.runs.questionBatch(r);if(!i)return{pending:!1,error:"Question batch disappeared"};if(!i.revisionPreparedAt)return{pending:!0,pollAfterSeconds:2};let a=await M.runs.reviseAnswer(r,t.answers??{},!0===t.stash,!1!==t.rollback);return a?{pending:!1,result:{id:a.id,kind:a.kind,status:a.status,phase:a.phase,parentRunId:a.parentRunId,followUpMode:a.followUpMode}}:{pending:!1,error:"Answer revision failed"}}),B.registerWaitPoller("GITHUB_CHECKS",async e=>{let t=c(JSON.parse(e),"GitHub checks wait"),r=await M.github.autoRetryRun(d(t.repositoryId,"Repository ID"),d(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(r.status)?{pending:!1,result:{runId:r.id,status:r.status,jobs:r.jobs,sessionPatch:{pipeline:{runId:r.id,status:r.status,conclusion:r.status,jobs:r.jobs}}},error:"SUCCESS"===r.status?null:`GitHub checks concluded ${r.status.toLowerCase()}`}:{pending:!0,pollAfterSeconds:10}}),B.registerWaitPoller("GITLAB_PIPELINE",async e=>{let t=c(JSON.parse(e),"GitLab pipeline wait"),r=await M.gitlab.pipeline(d(t.projectId,"GitLab project ID",500),d(t.pipelineId,"GitLab pipeline ID",500));return new Set(["SUCCESS","FAILED","CANCELED","SKIPPED","MANUAL"]).has(r.status)?{pending:!1,result:{id:r.id,projectId:r.projectId,status:r.status,webUrl:r.webUrl,sessionPatch:{pipeline:{id:r.id,projectId:r.projectId,status:r.status,webUrl:r.webUrl}}},error:"SUCCESS"===r.status?null:`GitLab pipeline concluded ${r.status.toLowerCase()}`}:{pending:!0,pollAfterSeconds:10}}),B.registerWaitPoller("DISK_SPACE_REPORT",async e=>{let t=c(JSON.parse(e),"Disk-space report wait"),r=d(t.agentId,"Agent ID",500),i=await M.diskSpace.snapshot(r);if(!i.disk.enabled)return{pending:!1,error:"Disk-space monitoring was disabled while awaiting a report"};let a=i.disk.lastReportedAt,n="string"==typeof t.previousReportedAt?t.previousReportedAt:null;return(d(t.requestedAt,"Requested timestamp",100),a&&(!n||Date.parse(a)>Date.parse(n)))?{pending:!1,result:{...i,sessionPatch:i}}:{pending:!0,pollAfterSeconds:2}}),q=I,j=C,q.register("JIRA_LOAD_TICKET",async e=>{let t=k(await j.jira.ticket(T(e),!0===e.node.config.force));return{output:t,sessionPatch:{ticket:t},links:[w(String(t.key),String(t.title??t.key))]}}),q.register("JIRA_TRANSITION",async e=>{let t=k(await j.jira.transitionTicket(T(e),d(e.node.config.transitionId,"Jira transition ID",200)));return{output:t,sessionPatch:{ticket:t},links:[w(String(t.key),String(t.title??t.key))]}}),q.register("JIRA_COMMENT",async e=>{let t=k(await j.jira.addComment(T(e),{value:d(e.node.config.content,"Jira comment",1e5),format:"JIRA_WIKI"===e.node.config.format?"JIRA_WIKI":"MARKDOWN"}));return{output:t,sessionPatch:{ticket:t},links:[w(String(t.key),String(t.title??t.key))]}}),q.register("JIRA_ASSIGN",async e=>{let t=null===e.node.config.accountId?null:d(e.node.config.accountId,"Jira account ID",500),r=k(await j.jira.assignTicket(T(e),t));return{output:r,sessionPatch:{ticket:r},links:[w(String(r.key),String(r.title??r.key))]}}),q.register("JIRA_UPDATE_FIELDS",async e=>{let t=c(e.node.config.fields??{},"Jira fields"),r=k(await j.jira.updateTicket({issueKey:T(e),...t}));return{output:r,sessionPatch:{ticket:r},links:[w(String(r.key),String(r.title??r.key))]}}),q.register("JIRA_RESOLVE_BRANCH",async e=>{let t=await j.worktrees.previewTicketBranch({codebaseId:d(e.node.config.codebaseId??(0,s.getSessionValue)(e.sessionData,"codebase.id"),"Codebase ID",200),worktreeId:"string"==typeof(0,s.getSessionValue)(e.sessionData,"worktree.id")?String((0,s.getSessionValue)(e.sessionData,"worktree.id")):null,ticketKey:T(e)});return{output:t,sessionPatch:{worktree:{branch:t.branchName},ticket:{key:t.ticketKey,title:t.ticketTitle,type:t.ticketType}},links:[w(t.ticketKey,t.ticketTitle)]}}),$=I,G=C,$.register("GITHUB_LOAD_PR",async e=>{let t=A(e),r=await G.github.pullRequest(t.owner,t.name,R(e),"WORKFLOW_AUTOMATION");if(!r)throw Error("Pull request was not found");let i=_(r);return{output:i,sessionPatch:{pr:i},links:[y("PULL_REQUEST",(0,n.pullRequestResourceId)(t.owner,t.name,r.number),r.title,r.url)]}}),$.register("GITHUB_MERGE_PR",async e=>{let t=A(e),r=R(e),i=await G.github.pullRequestMergeOptions(t.owner,t.name,r,"WORKFLOW_AUTOMATION");if(!i.canMerge)throw Error(i.blockedReason||"Pull request cannot be merged");let a=await G.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:[b(e)]}}),$.register("GITHUB_COLLECT_REVIEW_THREADS",async e=>{let t=A(e),r=await G.github.pullRequest(t.owner,t.name,R(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:[b(e,r.title,r.url)]}}),$.register("GITHUB_REPLY_REVIEW_THREAD",async e=>{let t=await G.github.replyToReviewThread(d(e.node.config.threadId,"Review thread ID",500),d(e.node.config.body,"Review reply",1e5),"WORKFLOW_AUTOMATION"),r=E(e);return{output:t,links:r?[r]:void 0}}),$.register("GITHUB_SET_REVIEW_THREAD_RESOLVED",async e=>{let t=await G.github.setReviewThreadResolved(d(e.node.config.threadId,"Review thread ID",500),!1!==e.node.config.resolved,"WORKFLOW_AUTOMATION"),r=E(e);return{output:t,links:r?[r]:void 0}}),$.register("GITHUB_CREATE_PR",async e=>{let t=A(e),r=await G.github.createPullRequest({...t,baseRefName:d(e.node.config.baseRefName??(0,s.getSessionValue)(e.sessionData,"worktree.baseBranch"),"Base branch",500),headRefName:d(e.node.config.headRefName??(0,s.getSessionValue)(e.sessionData,"worktree.branch"),"Head branch",500),title:d(e.node.config.title??(0,s.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 G.worktrees.attachPullRequestForBranch(`github.com/${t.owner}/${t.name}`,r.headRefName,r);let i=_(r);return{output:i,sessionPatch:{pr:i},links:[y("PULL_REQUEST",(0,n.pullRequestResourceId)(t.owner,t.name,r.number),r.title,r.url)]}}),$.register("GITHUB_SET_PR_LABELS",async e=>{let t=A(e),r=Array.isArray(e.node.config.labels)?e.node.config.labels.map(String):[],i=await G.github.setPullRequestLabels({...t,number:R(e),labels:r});return{output:i.labels,sessionPatch:{pr:{labels:i.labels}},links:[b(e)]}}),$.register("GITHUB_RETRY_PIPELINE",async e=>{let t=await G.github.retryPipeline(d(e.node.config.repositoryId??(0,s.getSessionValue)(e.sessionData,"pr.repositoryGithubId"),"GitHub repository ID",500),d(e.node.config.checkSuiteId??(0,s.getSessionValue)(e.sessionData,"pipeline.checkSuiteId"),"Check suite ID",500),"WORKFLOW_AUTOMATION",{actor:"workflow",ipAddress:null}),r=S(e);return{output:t,sessionPatch:{pipeline:{status:t.status}},links:r?[r]:void 0}}),$.register("GITHUB_RETRY_JOB",async e=>{let t=await G.github.retryWorkflowJob(d(e.node.config.repositoryId,"GitHub repository ID",500),d(e.node.config.checkSuiteId,"Check suite ID",500),d(e.node.config.jobId,"Workflow job ID",500),"WORKFLOW_AUTOMATION",{actor:"workflow",ipAddress:null}),r=S(e);return{output:t,links:r?[r]:void 0}}),$.register("GITHUB_CANCEL_WORKFLOW_RUN",async e=>{let t=await G.github.cancelActionsWorkflowRun(d(e.node.config.codebaseRepositoryId??(0,s.getSessionValue)(e.sessionData,"repo.id"),"Codebase repository ID",500),d(e.node.config.workflowRunId??(0,s.getSessionValue)(e.sessionData,"pipeline.runId"),"Workflow run ID",500),!0===e.node.config.force,"WORKFLOW_AUTOMATION",{actor:"workflow",ipAddress:null}),r=S(e);return{output:t,sessionPatch:{pipeline:{status:"CANCELLED"}},links:r?[r]:void 0}}),$.register("GITHUB_SAVE_AUTO_RETRY",async e=>({output:await G.github.saveAutoRetryRule(c(e.node.config.input,"Auto-retry rule"))})),$.register("GITHUB_WAIT_CHECKS",async e=>{let t=d(e.node.config.repositoryId??(0,s.getSessionValue)(e.sessionData,"repo.id"),"Repository ID",500),r=d(e.node.config.workflowRunId??(0,s.getSessionValue)(e.sessionData,"pipeline.runId"),"Workflow run ID",500),i=S(e);return{links:i?[i]:void 0,wait:{kind:"GITHUB_CHECKS",externalKey:JSON.stringify({repositoryId:t,workflowRunId:r}),resumeAfter:(0,u.waitResumeAfter)(e.node.config),timeoutAt:(0,u.waitTimeoutAt)(e.node.config)}}}),F=I,z=C,F.register("WORKTREE_CREATE",async e=>{let t=D(e),r=await z.worktrees.createWorktree({codebaseId:O(e),selection:t,requestId:m(e,"create")});return g(e,r,{worktree:{branch:t.branchName,baseBranch:t.baseBranch}})}),F.register("WORKTREE_CHANGE_BRANCH",async e=>{let t=N(e),r=D(e),i=await z.worktrees.changeWorktreeBranch({worktreeId:t,selection:r,requestId:m(e,"change-branch"),stashOnFailure:!0===e.node.config.stashOnFailure});return g(e,i,{worktree:{branch:r.branchName,baseBranch:r.baseBranch}},[y("WORKTREE",t,"Worktree")])}),F.register("WORKTREE_COMMIT",async e=>{let t=N(e),r=!1!==e.node.config.stageAll,i=e.node.config.paths,a=Array.isArray(i)?i.map(e=>d(e,"Selected path",2e3)):[],n=await z.worktrees.commitWorktree({worktreeId:t,message:d(e.node.config.message,"Commit message",5e4),signed:"boolean"==typeof e.node.config.signed?e.node.config.signed:null,stageAll:r,paths:a,requestId:m(e,"commit")});return g(e,n,void 0,[y("WORKTREE",t,"Worktree")])}),F.register("WORKTREE_REFRESH_PULL_REQUEST",async e=>{let t=N(e),r=(await z.worktrees.refreshPullRequest(t)).pullRequest,i=r?_(r):null,a=[y("WORKTREE",t,"Worktree")];if(r){let[e,t]=r.repositoryNameWithOwner.split("/");e&&t&&a.push(y("PULL_REQUEST",(0,n.pullRequestResourceId)(e,t,r.number),r.title,r.url))}return{output:{found:!!r,pullRequest:r},sessionPatch:{pr:i},links:a}}),F.register("WORKTREE_OPERATION",async e=>{let t=String(e.node.config.operation??"SYNC").toUpperCase();if("OPEN_EDITOR"===t||!i.WORKTREE_OPERATIONS.includes(t))throw Error("Worktree operation is invalid for workflow execution");let r=N(e),a=await z.worktrees.runOperation(r,t,m(e,t.toLowerCase()),!0===e.node.config.forcePreparations);return g(e,a,void 0,[y("WORKTREE",r,"Worktree")])}),F.register("WORKTREE_PREPARATION",async e=>{let t=N(e),r=String(e.node.config.action??"INSPECT").toUpperCase();if(!i.WORKTREE_PREPARATION_ACTIONS.includes(r))throw Error("Worktree preparation action is invalid");let a=await z.worktrees.runPreparations([t],r,m(e,`preparation-${r.toLowerCase()}`)),n=a.jobs[0];if(!n)throw Error(a.skipped[0]?.reason??"Worktree preparation was not dispatched");return g(e,n,void 0,[y("WORKTREE",t,"Worktree")])}),F.register("WORKTREE_SET_AUTO_SYNC",async e=>{let t=N(e),r=String(e.node.config.action??"ENABLE").toUpperCase();if("FORCE"===r){let r=await z.worktreeAutomations.forceAutoSync(t,m(e,"force-auto-sync"));return g(e,r,void 0,[y("WORKTREE",t,"Worktree")])}let i="CANCEL"===r?{cancelled:await z.worktreeAutomations.cancelAutoSync(t)}:"RETRY"===r?await z.worktreeAutomations.retryAutoSync(t):"ENABLE"===r?await z.worktreeAutomations.configureAutoSync({worktreeId:t,conflictWorkflowId:h(e.node.config.conflictWorkflowId,500),conflictWorkflowChoice:h(e.node.config.conflictWorkflowChoice,500)}):null;if(!i)throw Error("Unknown Auto Sync action");return{output:i,sessionPatch:{worktree:{autoSync:i}},links:[y("WORKTREE",t,"Worktree")]}}),F.register("WORKTREE_SET_AUTO_MERGE",async e=>{let t,r=N(e),i=String(e.node.config.action??"ENABLE").toUpperCase();if("CANCEL"===i)t={cancelled:await z.worktreeAutomations.cancelAutoMerge(r)};else if("RETRY"===i)t=await z.worktreeAutomations.retryAutoMerge(r);else if("ENABLE"===i){let i=Number(e.node.config.pullRequestNumber??(0,s.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 z.worktreeAutomations.configureAutoMerge({worktreeId:r,repositoryNameWithOwner:d(e.node.config.repositoryNameWithOwner??(0,s.getSessionValue)(e.sessionData,"repo.nameWithOwner"),"Repository",500),pullRequestNumber:i,method:a,commitHeadline:d(e.node.config.commitHeadline??(0,s.getSessionValue)(e.sessionData,"pr.title"),"Commit headline",1e3),commitBody:String(e.node.config.commitBody??""),authorEmail:h(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:[y("WORKTREE",r,"Worktree")]}}),F.register("WORKTREE_DELETE",async e=>{let t=await z.worktrees.deleteWorktree({worktreeId:N(e),deleteRemoteBranch:!0===e.node.config.deleteRemoteBranch,requestId:m(e,"delete")});return g(e,t)}),F.register("WORKTREE_MOVE",async e=>{let t=await z.worktrees.moveWorktree({sourceWorktreeId:N(e),targetCodebaseId:d(e.node.config.targetCodebaseId,"Target codebase ID",500),targetWorktreeId:h(e.node.config.targetWorktreeId,500),deleteSource:!0===e.node.config.deleteSource,requestId:m(e,"move")}),r=t.targetWorktreeId??(!0===e.node.config.deleteSource?null:N(e));return{output:t,links:[...r?[y("WORKTREE",r,"Worktree")]:[],{kind:"WORKTREE_MOVE",resourceId:t.id,label:"Worktree move"}],wait:{kind:"WORKTREE_MOVE",externalKey:t.id,resumeAfter:(0,u.waitResumeAfter)(e.node.config),timeoutAt:(0,u.waitTimeoutAt)(e.node.config)}}}),F.register("WORKTREE_INSPECT",async e=>{let t=N(e),r=await z.worktrees.inspect(t,m(e,"inspect"));return{output:r,sessionPatch:{worktree:{commits:r.commits,changes:r.changes,branchChanges:r.branchChanges}},links:[y("WORKTREE",t,"Worktree")]}}),F.register("WORKTREE_INSPECT_GIT",async e=>{let t=N(e),r=await z.worktrees.inspectGitState(t,m(e,"inspect-git"));return{output:r,sessionPatch:{worktree:{...r}},links:[y("WORKTREE",t,"Worktree")]}}),F.register("WORKTREE_GIT_OPERATION",async e=>{let t=String(e.node.config.operation??"PULL_BRANCH").toUpperCase();if(!i.WORKTREE_GIT_OPERATIONS.includes(t))throw Error("Worktree Git operation is invalid");let r=N(e),a=await z.worktrees.runGitOperation({worktreeId:r,operation:t,branch:h(e.node.config.branch,500),stashOid:h(e.node.config.stashOid,200),stashChanges:!0===e.node.config.stashChanges,requestId:m(e,t.toLowerCase())});return g(e,a,void 0,[y("WORKTREE",r,"Worktree")])}),F.register("WORKTREE_WAIT_PUSH_READY",async e=>{let t=N(e);return{links:[y("WORKTREE",t,"Worktree")],wait:{kind:"WORKTREE_PUSH_READY",externalKey:t,resumeAfter:(0,u.waitResumeAfter)(e.node.config),timeoutAt:(0,u.waitTimeoutAt)(e.node.config)}}}),H=I,V=C,H.register("CODEBASE_FETCH_REFRESH",async e=>{let t=O(e),i="REFRESH"===e.node.config.operation?r.CODEBASE_REFRESH_JOB_KIND:r.CODEBASE_FETCH_JOB_KIND,a=await V.codebases.runOperation(i,[t],m(e,i)),n=a.jobs[0];if(!n)throw Error(a.skipped[0]?.reason??"Codebase operation was skipped");return g(e,n,void 0,[y("CODEBASE",t,"Codebase")])}),H.register("CODEBASE_INSPECT_GIT",async e=>{let t=O(e),r=await V.codebases.inspectGitState(t,m(e,"inspect-git"));return{output:r,sessionPatch:{codebase:{...r}},links:[y("CODEBASE",t,"Codebase")]}}),H.register("CODEBASE_GIT_OPERATION",async e=>{let t=String(e.node.config.operation??"PULL_BRANCH").toUpperCase();if(!r.CODEBASE_GIT_OPERATIONS.includes(t))throw Error("Codebase Git operation is invalid");let i=O(e),a=await V.codebases.runGitOperation({codebaseId:i,operation:t,branch:h(e.node.config.branch,500),stashOid:h(e.node.config.stashOid,200),stashChanges:!0===e.node.config.stashChanges,requestId:m(e,t.toLowerCase())});return g(e,a,void 0,[y("CODEBASE",i,"Codebase")])}),K=I,W=C,K.register("BUILD_START",async e=>{let r=String(e.node.config.action??"BUILD").toUpperCase();if(!t.BUILD_ACTIONS.includes(r))throw Error("Build action is invalid");let i=await W.builds.startBuild({worktreeId:N(e),configurationId:d(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:r,advancedSettings:e.node.config.advancedSettings,exportWhenComplete:!0===e.node.config.exportWhenComplete,exportSettings:e.node.config.exportSettings,worktreeCoverage:!0===e.node.config.worktreeCoverage,requestId:m(e,"build"),telemetryRequestOrigin:"workflow"});return{output:i,sessionPatch:{build:{id:i.id,status:i.status,action:i.action}},links:[{kind:"BUILD",resourceId:i.id,label:`${i.action} build`,url:`/builds/${i.id}`}],wait:{kind:"BUILD",externalKey:i.id,resumeAfter:(0,u.waitResumeAfter)(e.node.config),timeoutAt:(0,u.waitTimeoutAt)(e.node.config)}}}),K.register("BUILD_READ_TEST_RESULTS",async e=>{let t=P(e),r=(await W.builds.reportsForBuild(t)).filter(({kind:e,status:t})=>"TEST_RESULTS"===e&&"READY"===t).at(-1);if(!r)throw Error("Test results are not ready");let i=c(JSON.parse(r.summaryJson),"Test summary"),a=c(JSON.parse(r.dataJson),"Test results");return{output:{summary:i,tests:a.tests??[]},sessionPatch:{build:{testSummary:i,tests:a.tests??[]}},links:[y("BUILD",t,"Build",void 0)]}}),K.register("BUILD_READ_COVERAGE",async e=>{let t=P(e),r=(await W.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=c(JSON.parse(r.summaryJson),"Coverage summary"),a=c(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:[y("BUILD",t,"Build",`/builds/${t}/coverage`)]}}),K.register("BUILD_IMPORT_COVERAGE",async e=>{let t=N(e),r=await W.builds.importCoverageReport({worktreeId:t,buildName:h(e.node.config.buildName,200)??h((0,s.getSessionValue)(e.sessionData,"workflow.name"),200)??"Coverage report",reportPath:d(e.node.config.reportPath??"coverage/lcov.info","Coverage file",4e3),format:h(e.node.config.format)??"AUTO",requestId:m(e,"coverage-import")}),i=[y("WORKTREE",t,"Worktree"),y("BUILD",r.id,"Build",`/builds/${r.id}`)];return"jobId"in r&&"string"==typeof r.jobId?g(e,{id:r.jobId,timeoutSeconds:300},{build:{id:r.id}},i):{output:r,sessionPatch:{build:{id:r.id}},links:i}}),K.register("BUILD_EXPORT",async e=>{let t=P(e),r=await W.builds.exportArchive({buildId:t,requestId:m(e,"export"),settings:c(e.node.config.settings,"Export settings")});return r.jobId?g(e,{id:r.jobId,timeoutSeconds:3600},{build:{exportId:r.id}},[y("BUILD",t,"Build",void 0)]):{output:r,links:[y("BUILD",t,"Build",void 0)]}}),K.register("BUILD_DEPLOY",async e=>{let t=P(e),r=await W.builds.runBuild({buildId:t,destinations:Array.isArray(e.node.config.destinations)?e.node.config.destinations:[],requestId:m(e,"deploy")}),i=r.find(({jobId:e})=>!!e)?.jobId;return i?g(e,{id:i,timeoutSeconds:3600},void 0,[y("BUILD",t,"Build",void 0)]):{output:r,links:[y("BUILD",t,"Build",void 0)]}}),K.register("BUILD_CANCEL",async e=>{let t=P(e),r=await W.builds.cancelBuild(t);return{output:r,sessionPatch:{build:{id:r?.id,status:r?.status}},links:[y("BUILD",t,"Build",void 0)]}}),J=I,Y=C,X=async e=>{let t=await Y.diskSpace.snapshot(e);return{output:t,sessionPatch:t,links:[y("AGENT",e,t.agent.name,`/agents/${encodeURIComponent(e)}`)]}},J.register("DISK_SPACE_LOAD",async e=>X(x(e))),J.register("DISK_SPACE_REFRESH",async e=>{let t=x(e),r=await Y.diskSpace.requestRefresh(t);return{output:r,links:[y("AGENT",t,"Agent",`/agents/${encodeURIComponent(t)}`)],wait:{kind:"DISK_SPACE_REPORT",externalKey:JSON.stringify(r),resumeAfter:(0,u.waitResumeAfter)(e.node.config,2),timeoutAt:(0,u.waitTimeoutAt)(e.node.config,180)}}}),J.register("DISK_SPACE_UPDATE_THRESHOLDS",async e=>{let t=await Y.diskSpace.updateSettings({normalThresholdGiB:Number(e.node.config.normalThresholdGiB),pressureThresholdGiB:Number(e.node.config.pressureThresholdGiB)});return{output:t,sessionPatch:{disk:t}}}),J.register("DISK_SPACE_SET_MONITORING",async e=>{let t=x(e);return await Y.diskSpace.setMonitoring(t,!0===e.node.config.enabled),X(t)}),J.register("DISK_SPACE_SET_PRESSURE_MODE",async e=>{let t=x(e);return await Y.diskSpace.setManualPressureMode(t,!0===e.node.config.enabled),X(t)}),function(e,t){for(let[r,i]of(e.register("RUN_CREATE_PLAN",async e=>{let r=await t.runs.create(U(e,"PLAN"));if(!r)throw Error("Plan could not be created");return f(e,r,!0)}),e.register("RUN_CREATE_SESSION",async e=>{let r=await t.runs.create(U(e,"SESSION"));if(!r)throw Error("Session could not be created");return f(e,r,!0)}),e.register("RUN_PLAY_PLAN",async e=>{let r=e.node.config.worktreeConcurrencyLimit,i=await t.runs.playPlan(L(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 f(e,i,!0)}),e.register("RUN_FOLLOW_UP",async e=>{let r=U(e,"SESSION"),i=await t.runs.followUp(L(e),{...r,followUpMode:d(e.node.config.followUpMode??"RESUME","Follow-up mode",50),contextMode:h(e.node.config.contextMode,50)});if(!i)throw Error("Follow-up could not be created");return f(e,i,!0)}),e.register("RUN_STEER",async e=>{let r=await t.runs.steer(L(e),d(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 f(e,r)}),e.register("RUN_ANSWER",async e=>{let r=await t.runs.answerQuestion(d(e.node.config.batchId,"Question batch ID",500),e.node.config.answers??{});if(!r)throw Error("Question could not be answered");return f(e,r)}),[["RUN_PAUSE","PAUSE"],["RUN_CONTINUE","CONTINUE"],["RUN_CANCEL","CANCEL"]]))e.register(r,async e=>{let r=await t.runs.lifecycle(L(e),i);if(!r)throw Error("Run lifecycle operation failed");return f(e,r)});e.register("RUN_REVISE_ANSWER",async e=>{let r=d(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 f(e,i)}await t.runs.prepareAnswerRevision(r);let a=v(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:(0,u.waitResumeAfter)(e.node.config),timeoutAt:(0,u.waitTimeoutAt)(e.node.config)}}}),e.register("RUN_READ_RESULT",async e=>{let r=await t.runs.get(L(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 f(e,{...r,events:i,questions:a,usage:n,links:s})}),e.register("RUN_CAPTURE_CHECKPOINT",async e=>{let t=await (0,a.getPrismaClient)(),r=await t.runCheckpoint.findFirst({where:{runId:L(e)},orderBy:{createdAt:"desc"}});if(!r)throw Error("Run has no captured checkpoint");let i=v(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=L(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:v(e);return{output:{id:r,affected:a},links:n?[n]:void 0}})}(I,C),Q=I,Z=C,Q.register("SAVED_COMMAND",async e=>{let t=d(e.node.config.commandId,"Saved command",500),r=await Z.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",n=(0,o.commandOutputPattern)(e.node.config),c=(0,o.commandOutputMatchMode)(e.node.config),h=Array.isArray((0,s.getSessionValue)(e.sessionData,`steps.${e.node.id}.matches`))?(0,s.getSessionValue)(e.sessionData,`steps.${e.node.id}.matches`):[];if(n&&((0,l.compileCommandOutputPattern)(n),"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 p=String(e.node.config.targetMode??"CONTEXT"),m=null,f=null,g=new Set(["ANY_AGENT_HOME","SPECIFIC_AGENT_HOME"]).has(r.targetKind);if("FIXED_AGENT"===p)m=d(e.node.config.agentId,"Fixed agent",500);else if("FIXED_WORKTREE"===p)f=d(e.node.config.worktreeId,"Fixed worktree",500);else if(g){let t=(0,s.getSessionValue)(e.sessionData,"agent.id")??(0,s.getSessionValue)(e.sessionData,"codebase.agentId");if("string"==typeof t&&(m=t),!m){let t=(0,s.getSessionValue)(e.sessionData,"worktree.id");if("string"==typeof t){let e=await (0,a.getPrismaClient)(),r=await e.worktree.findUnique({where:{id:t},select:{codebase:{select:{agentId:!0}}}});m=r?.codebase.agentId??null}}}else{let t=(0,s.getSessionValue)(e.sessionData,"worktree.id");"string"==typeof t&&(f=t)}let y=await Z.commands.startRun({commandId:t,agentId:m,worktreeId:f,origin:"WORKFLOW",idempotencyKey:e.attempt.idempotencyKey,blocksGitOperations:e.run.blocksGitOperations});if(!y)throw Error("Command run could not be created");return{output:{id:y.id,displayNumber:y.displayNumber,status:y.status},sessionPatch:{steps:{[e.node.id]:{commandRunId:y.id,displayNumber:y.displayNumber,matches:h,latestMatch:h.at(-1)??null}}},links:[{kind:"COMMAND_RUN",resourceId:y.id,label:`Command #${y.displayNumber}`,url:`/commands/runs/${y.id}`}],wait:"WAIT_FOR_EXIT"===i?{kind:"COMMAND_RUN",externalKey:y.id,predicate:n?{outputMatch:{pattern:n,mode:c,matchCount:h.length,matched:"ONCE"===c&&h.length>0,scanAttempt:1,scanCharacterOffset:0,observedAttempt:0,observedSequence:-1}}:void 0,resumeAfter:(0,u.waitResumeAfter)(e.node.config),timeoutAt:(0,u.waitTimeoutAt)(e.node.config)}:void 0}}),Q.register("CUSTOM_COMMAND",async e=>{let t=d(e.node.config.script,"Custom command",1e6),r="FIRE_AND_FORGET"===e.node.config.completionMode?"FIRE_AND_FORGET":"WAIT_FOR_EXIT",i=(0,o.commandOutputPattern)(e.node.config),a=(0,o.commandOutputMatchMode)(e.node.config),n=Array.isArray((0,s.getSessionValue)(e.sessionData,`steps.${e.node.id}.matches`))?(0,s.getSessionValue)(e.sessionData,`steps.${e.node.id}.matches`):[];if(i&&((0,l.compileCommandOutputPattern)(i),"WAIT_FOR_EXIT"!==r))throw Error("Output matching requires Wait for exit completion");let c=String(e.node.config.targetMode??"CONTEXT"),h=null,p=null;if("FIXED_AGENT"===c)h=d(e.node.config.agentId,"Fixed agent",500);else if("FIXED_WORKTREE"===c)p=d(e.node.config.worktreeId,"Fixed worktree",500);else{let t=(0,s.getSessionValue)(e.sessionData,"worktree.id");if("string"==typeof t)p=t;else{let t=(0,s.getSessionValue)(e.sessionData,"agent.id")??(0,s.getSessionValue)(e.sessionData,"codebase.agentId");"string"==typeof t&&(h=t)}}if(!h&&!p)throw Error("Custom command context has no agent or worktree target");let m=await Z.commands.startCustomRun({script:t,agentId:h,worktreeId:p,origin:"WORKFLOW",idempotencyKey:e.attempt.idempotencyKey,blocksGitOperations:e.run.blocksGitOperations});if(!m)throw Error("Custom command run could not be created");return{output:{id:m.id,displayNumber:m.displayNumber,status:m.status},sessionPatch:{steps:{[e.node.id]:{commandRunId:m.id,displayNumber:m.displayNumber,matches:n,latestMatch:n.at(-1)??null}}},links:[{kind:"COMMAND_RUN",resourceId:m.id,label:`Command #${m.displayNumber}`,url:`/commands/runs/${m.id}`}],wait:"WAIT_FOR_EXIT"===r?{kind:"COMMAND_RUN",externalKey:m.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:(0,u.waitResumeAfter)(e.node.config),timeoutAt:(0,u.waitTimeoutAt)(e.node.config)}:void 0}}),Q.register("SKILL_APPLY",async e=>{let t=await Z.skills.prepareSync(e.node.config.groupId?"GROUP":"ALL",h(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:(0,u.waitResumeAfter)(e.node.config),timeoutAt:(0,u.waitTimeoutAt)(e.node.config)}}}),Q.register("NOTIFICATION_SEND",async e=>{let t=await (0,a.getPrismaClient)(),r=await t.$transaction(t=>Z.notifications.recordInTransaction(t,{dedupeKey:`${e.run.id}:${e.node.id}:${e.attempt.generation}`,typeKey:"WORKFLOW_MESSAGE",title:d(e.node.config.title,"Notification title",240),body:d(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,s.getSessionValue)(e.sessionData,"worktree.id")?String((0,s.getSessionValue)(e.sessionData,"worktree.id")):null}));return Z.notifications.created(r),{output:r}}),Q.register("IOS_PUSH_SEND",async e=>({output:await Z.pushNotifications.send({requestId:m(e,"ios-push"),editor:e.node.config.editor,targetMode:d(e.node.config.targetMode??"ALL","Push target mode",50),registrationIds:Array.isArray(e.node.config.registrationIds)?e.node.config.registrationIds.map(String):[],channelId:h(e.node.config.channelId,500),directToken:h(e.node.config.directToken,2e4),directTokenEncoding:"BASE64"===e.node.config.directTokenEncoding?"BASE64":"HEX",directEnvironment:"PRODUCTION"===e.node.config.directEnvironment?"PRODUCTION":"SANDBOX"})})),ee=async(e,t,r)=>{let i=await Z.tools.callTool({groupId:"builtin:sse",name:t,arguments:r},{caller:`workflow:${e.run.id}`,correlationId:e.attempt.id,source:"WORKFLOW"});return{output:i,sessionPatch:{sse:{action:i},steps:{[e.node.id]:{output:i}}}}},Q.register("SSE_ENDPOINT_ACTION",async e=>{let t=d(e.node.config.operation,"SSE endpoint operation",50),r=h(e.node.config.endpointId,500),i=c(e.node.config.input??{},"SSE endpoint input"),a={CREATE:{name:"sse_endpoint_create",arguments:i},UPDATE:{name:"sse_endpoint_update",arguments:{id:r,endpoint:i}},SET_MODE:{name:"sse_endpoint_set_mode",arguments:{id:r,mode:i.mode}},ROTATE_TOKEN:{name:"sse_endpoint_rotate_token",arguments:{id:r}},DELETE:{name:"sse_endpoint_delete",arguments:{id:r}}}[t];if(!a)throw Error("Unsupported SSE endpoint workflow operation");if("CREATE"!==t&&!r)throw Error("SSE endpoint ID is required");return ee(e,a.name,a.arguments)}),Q.register("SSE_MOCK_ACTION",async e=>{let t=d(e.node.config.operation,"SSE mock operation",50),r=h(e.node.config.endpointId,500),i=h(e.node.config.resourceId,500),a=c(e.node.config.input??{},"SSE mock input"),n={SAVE_TEMPLATE:{name:"sse_mock_template_save",arguments:{endpointId:r,id:i,...a}},DELETE_TEMPLATE:{name:"sse_mock_template_delete",arguments:{id:i}},SAVE_COMPOSITION:{name:"sse_mock_composition_save",arguments:{endpointId:r,id:i,composition:a}},ACTIVATE_COMPOSITION:{name:"sse_mock_composition_activate",arguments:{endpointId:r,compositionId:i}},DELETE_COMPOSITION:{name:"sse_mock_composition_delete",arguments:{id:i}}}[t];if(!n)throw Error("Unsupported SSE mock workflow operation");return ee(e,n.name,n.arguments)}),Q.register("SSE_STORAGE_ACTION",async e=>{let t=d(e.node.config.operation,"SSE storage operation",50),r=d(e.node.config.key,"SSE storage key",256),i={SET:{name:"sse_storage_set",arguments:{key:r,value:e.node.config.value}},COMPARE_AND_SET:{name:"sse_storage_compare_and_set",arguments:{key:r,expectedVersion:e.node.config.expectedVersion??null,value:e.node.config.value}},INCREMENT:{name:"sse_storage_increment",arguments:{key:r,delta:e.node.config.delta??1}},DELETE:{name:"sse_storage_delete",arguments:{key:r}}}[t];if(!i)throw Error("Unsupported SSE storage workflow operation");return ee(e,i.name,i.arguments)}),Q.register("SSE_BREAKPOINT_RESOLVE",async e=>ee(e,"sse_breakpoint_resolve",{id:d(e.node.config.breakpointId,"SSE breakpoint ID",500),version:e.node.config.version,resolution:e.node.config.resolution,mockCompositionId:e.node.config.mockCompositionId??null,adHocComposition:e.node.config.adHocComposition??null})),Q.register("SSE_HISTORY_CLEAR",async e=>ee(e,"sse_history_clear",{endpointId:e.node.config.endpointId??null,ids:e.node.config.ids??null})),Q.register("SSE_SCRIPT_TEST",async e=>ee(e,"sse_script_test",{source:d(e.node.config.source,"SSE script",1e5),context:e.node.config.context??{},timeoutMs:e.node.config.timeoutMs,memoryLimitMb:e.node.config.memoryLimitMb,fetchTimeoutMs:e.node.config.fetchTimeoutMs})),Q.register("MCP_CALL",async e=>{let t=await Z.tools.callTool({groupId:d(e.node.config.groupId,"MCP tool group",500),name:d(e.node.config.name,"MCP tool name",500),arguments:c(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=c(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=c(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:(0,u.waitResumeAfter)(e.node.config),timeoutAt:(0,u.waitTimeoutAt)(e.node.config,i)}),a=(e,t,r,i)=>p(e,t,r,i),n=e=>({projectId:a(e,"projectId","pr.projectId","GitLab project ID"),iid:Number(e.node.config.iid??(0,s.getSessionValue)(e.sessionData,"pr.iid")??(0,s.getSessionValue)(e.sessionData,"pr.number"))}),o=e=>({pr:c(e.mergeRequest,"GitLab merge request output")});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:c(e.run,"Command run output")}),wait:t=>i(e,"COMMAND_RUN",d(c(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:c(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:d(e.node.config.scope,"Diff scope",100),path:e.node.config.path,previousPath:e.node.config.previousPath,commitSha:e.node.config.commitSha,requestId:m(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,s.mergeSessionData)(await t.worktrees.workflowSessionDataForWorktree(i,{includeMissing:!0}),{worktree:c(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:d(e.node.config.moveId,"Move ID",500)},{sessionPatch:async e=>{let r=c(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,s.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:m(e,"rebuild")},{sessionPatch:e=>({build:c(e.build,"Build output")}),wait:t=>i(e,"BUILD",d(c(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:m(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:c(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:d(e.node.config.itemId,"Conflict item ID",500),resolution:String(e.node.config.resolution??"SKIP")}},{sessionPatch:e=>({skillSync:c(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:c(e.run,"Skill sync output")})})),e.register("BUILD_DATA_REFRESH",e=>r(e,"builtin:build-data","refresh_build_data",{requestId:m(e,"build-data")},{sessionPatch:e=>({buildData:c(e.collection,"Build-data collection output")}),wait:t=>{let r=c(t.collection,"Build-data collection output");return"COMPLETED"===r.status?void 0:i(e,"BUILD_DATA_COLLECTION",d(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:m(e,"build-data-delete"),overrideProtection:!0===e.node.config.overrideProtection},{sessionPatch:e=>({buildData:c(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:d(e.node.config.entryId,"Entry ID",500),locked:!0===e.node.config.locked},{sessionPatch:e=>({buildData:{id:t,entry:e.entry}})})});let l=async(e,t,a)=>{let n=await r(e,"builtin:tailscale",t,a,{sessionPatch:e=>{let t=c(e.operation,"Tailscale operation output");return{tailscale:{operation:t,operationId:t.id,status:t.status,templateId:t.templateId}}},wait:t=>{let r=c(t.operation,"Tailscale operation output");return["SUCCEEDED","FAILED","PARTIAL_FAILED"].includes(String(r.status))?void 0:i(e,"TAILSCALE_SERVE_OPERATION",d(r.id,"Tailscale operation ID",500),604800)}}),s=c(c(n.output,"Tailscale tool output").operation,"Tailscale operation output");return{...n,links:[{kind:"TAILSCALE_SERVE_OPERATION",resourceId:d(s.id,"Tailscale operation ID",500),label:"Tailscale Serve",url:"/tailscale"}]}};for(let[u,p]of(e.register("TAILSCALE_SERVE_INSPECT",e=>l(e,"inspect_tailscale_serve",{agentIds:Array.isArray(e.node.config.agentIds)?e.node.config.agentIds.map(String):[],requestId:m(e,"tailscale-inspect")})),e.register("TAILSCALE_SERVE_UPSERT_TEMPLATE",e=>{let t=h(e.node.config.templateId,500),r=Number(e.node.config.expectedRevision),i=Array.isArray(e.node.config.agentIds)?e.node.config.agentIds.map(e=>d(e,"Agent ID",500)):[];return l(e,"upsert_tailscale_serve_template",{input:{...t?{id:t,expectedRevision:r}:{},name:d(e.node.config.name,"Template name",200),protocol:d(e.node.config.protocol??"HTTPS","Listener protocol",50),listenPort:Number(e.node.config.listenPort),mountPath:String(e.node.config.mountPath??"/"),destinationProtocol:d(e.node.config.destinationProtocol??"HTTP","Destination protocol",50),destinationPort:Number(e.node.config.destinationPort),destinationPath:String(e.node.config.destinationPath??""),funnel:!0===e.node.config.funnel,appCapabilities:Array.isArray(e.node.config.appCapabilities)?e.node.config.appCapabilities.map(e=>d(e,"App capability",500)):[],proxyProtocol:d(e.node.config.proxyProtocol??"NONE","PROXY protocol",20),assignments:i.map(e=>({agentId:e,enabled:!0}))},requestId:m(e,"tailscale-upsert")})}),e.register("TAILSCALE_SERVE_SET_AGENT_ENABLED",e=>l(e,"set_tailscale_serve_agent_enabled",{templateId:a(e,"templateId","tailscale.templateId","Tailscale template ID"),agentId:d(e.node.config.agentId,"Agent ID",500),enabled:!0===e.node.config.enabled,expectedRevision:Number(e.node.config.expectedRevision),requestId:m(e,"tailscale-assignment")})),e.register("TAILSCALE_SERVE_DELETE_TEMPLATE",e=>l(e,"delete_tailscale_serve_template",{id:a(e,"templateId","tailscale.templateId","Tailscale template ID"),expectedRevision:Number(e.node.config.expectedRevision),requestId:m(e,"tailscale-delete")})),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:d(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:[d(c(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:c(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:c(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"),c(e.node.config.settings,"Cadence settings"));return{output:r,sessionPatch:{agent:c(r,"Agent output")}}}),e.register("CCUSAGE_COLLECT",async e=>{let r=await t.ccusage.collect(m(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:o})),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:d(e.node.config.title??(0,s.getSessionValue)(e.sessionData,"ticket.title"),"Merge request title",500),description:h(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:o})),e.register("GITLAB_UPDATE_MR",e=>r(e,"builtin:gitlab","gitlab_update_merge_request",{...n(e),title:h(e.node.config.title),description:h(e.node.config.description),stateEvent:h(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:o})),e.register("GITLAB_SUBMIT_REVIEW",e=>r(e,"builtin:gitlab","gitlab_submit_review",{...n(e),outcome:String(e.node.config.outcome??"COMMENT"),body:h(e.node.config.body)})),e.register("GITLAB_REPLY_DISCUSSION",e=>r(e,"builtin:gitlab","gitlab_reply_discussion",{...n(e),discussionId:d(e.node.config.discussionId,"Discussion ID",500),body:d(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:d(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:h(e.node.config.sha)},{sessionPatch:o})),[["GITLAB_SET_MR_LABELS","labels"],["GITLAB_REQUEST_REVIEWERS","reviewerIds"]]))e.register(u,e=>r(e,"builtin:gitlab","gitlab_update_merge_request",{...n(e),[p]:Array.isArray(e.node.config[p])?e.node.config[p].map(String):[]},{sessionPatch:o}));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",c(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:(0,u.waitResumeAfter)(e.node.config),timeoutAt:(0,u.waitTimeoutAt)(e.node.config)}}));let f=async(e,t,i)=>{let a=await r(e,"builtin:github",t,i),n=c(a.output,"GitHub tool output"),s=_(c(n.pullRequest,"Pull request output"));return{...a,sessionPatch:{...a.sessionPatch,pr:s}}},g=e=>({owner:d(e.node.config.owner??(0,s.getSessionValue)(e.sessionData,"repo.owner"),"Repository owner",200),name:d(e.node.config.name??(0,s.getSessionValue)(e.sessionData,"repo.name"),"Repository name",200),number:Number(e.node.config.number??(0,s.getSessionValue)(e.sessionData,"pr.number"))});e.register("GITHUB_UPDATE_PR",e=>f(e,"update_pull_request",{...g(e),title:h(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=>f(e,"submit_pull_request_review",{...g(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=>f(e,"request_pull_request_reviewers",{...g(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:d(e.node.config.workflowId,"Workflow ID",500),ref:d(e.node.config.ref,"Git ref",500),inputs:e.node.config.inputs?c(e.node.config.inputs,"Workflow inputs"):void 0},{sessionPatch:e=>({pipeline:e})}));let y=async(e,t,i)=>{let a=await r(e,"builtin:jira",t,i),n=c(a.output,"Jira tool output"),s=k(c(n.ticket,"Jira ticket output"));return{...a,sessionPatch:{...a.sessionPatch,ticket:s}}};e.register("JIRA_CREATE_TICKET",e=>y(e,"create_jira_ticket",{projectKey:d(e.node.config.projectKey,"Project key",100),issueTypeId:d(e.node.config.issueTypeId,"Issue type ID",100),summary:d(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?c(e.node.config.fields,"Additional Jira fields"):void 0})),e.register("JIRA_ADD_WORKLOG",e=>y(e,"add_jira_worklog",{issueKey:a(e,"issueKey","ticket.key","Issue key"),timeSpentSeconds:Number(e.node.config.timeSpentSeconds),startedAt:h(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=>y(e,"link_jira_tickets",{inwardIssueKey:a(e,"inwardIssueKey","ticket.key","Inward issue key"),outwardIssueKey:d(e.node.config.outwardIssueKey,"Outward issue key",100),linkType:d(e.node.config.linkType,"Link type",100)}))}(I,C)}])},381494,e=>{"use strict";var t=e.i(666680),r=e.i(243783);e.s(["WorkflowEventsService",0,class{nextMaintenanceAt=0;async record(e){let t=await (0,r.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,r){let i=await e.workflowTriggerEvent.findUnique({where:{dedupeKey:r.dedupeKey}});return i||e.workflowTriggerEvent.create({data:{id:(0,t.randomUUID)(),kind:r.kind,subjectKey:r.subjectKey,dedupeKey:r.dedupeKey,payloadJson:JSON.stringify(r.payload)}})}async maintain(){let e=Date.now();if(e<this.nextMaintenanceAt)return;let t=await (0,r.getPrismaClient)(),i=await t.workflowTriggerEvent.findMany({where:{status:"FAILED",receivedAt:{lt:new Date(e-6048e5)}},select:{id:!0},orderBy:{receivedAt:"asc"},take:1e3});if(i.length){await t.workflowTriggerEvent.deleteMany({where:{id:{in:i.map(({id:e})=>e)}}}),this.nextMaintenanceAt=0;return}this.nextMaintenanceAt=e+36e5}}])},420533,e=>{"use strict";var t=e.i(666680),r=e.i(586589),i=e.i(119909);e.i(805422);var a=e.i(661983),n=e.i(243783),s=e.i(499162);e.i(714327);var o=e.i(508813);function l(e){try{let t=JSON.parse(e);return t&&"object"==typeof t&&!Array.isArray(t)?t:{}}catch{return{}}}function u(e,t){return{id:e.id,name:e.name,url:e.displayOrigin,canonicalOrigin:e.canonicalOrigin,displayOrigin:e.displayOrigin,defaultBranch:t??null}}function c(e){return{id:e.id,name:e.name,hostname:e.hostname,connected:null===e.disconnectedAt,diskFreeBytes:e.diskFreeBytes,memoryFreeBytes:e.memoryFreeBytes}}e.s(["WorkflowEventBridge",0,class{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===i.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,s.mergeSessionData)(t,{worktree:{id:e.worktreeId},automation:{jobId:e.id,status:e.status,error:e.error,result:l(e.resultJson??"{}")}}),{cursorValue:`${e.id}:${e.status}`})}if("ccusage.report"===e.kind&&"SUCCEEDED"===e.status&&e.resultJson){let t=l(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,s.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=a.agentEventBus.iterate(a.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=a.agentEventBus.iterate(a.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=a.agentEventBus.iterate(a.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,s.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=a.agentEventBus.iterate(a.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=a.agentEventBus.iterate(a.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=a.agentEventBus.iterate(a.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=a.agentEventBus.iterate(a.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=a.agentEventBus.iterate(a.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=a.agentEventBus.iterate(a.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=a.agentEventBus.iterate(a.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=a.agentEventBus.iterate(a.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=a.agentEventBus.iterate(a.TOOL_CALL_AUDIT_CHANGED_TOPIC);try{for await(let t of e){if(!this.running)break;let e=await (0,n.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,s=a?null:await e.workflowStepAttempt.findUnique({where:{id:r.correlationId},select:{run:{select:{id:!0,workflowId:!0}}}}),o=a??s?.run??null,l=r.finishedAt?.toISOString()??"unfinished";await this.record("TOOL_CALL_RESULT",r.id,`tool-call:${r.id}:${r.resultStatus}:${l}`,{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}:${l}`,...o?{workflowCorrelation:{workflowId:o.workflowId,runId:o.id}}:{}})}}finally{await e.return?.()}}async observeRun(e){let t=await (0,n.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),o=(0,s.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:u(r.worktree.codebase.repository,r.worktree.codebase.defaultBranch)}:{},...r.agent?{agent:c(r.agent)}:{},...r.jiraIssueKey?{ticket:{key:r.jiraIssueKey}}:{}}),l=i?{workflowId:i.run.workflowId,runId:i.runId,attemptId:i.attemptId}:null,d={cursorValue:`${r.status}:${r.phase}`,workflowCorrelation:l};r.startedAt&&await this.record("RUN_STARTED",r.id,`run-started:${r.id}:${r.startedAt.toISOString()}`,o,d);let h="COMPLETED"===r.status?"RUN_COMPLETED":"FAILED"===r.status?"RUN_FAILED":"CANCELLED"===r.status?"RUN_CANCELLED":"PAUSED"===r.status?"RUN_PAUSED":null;h&&await this.record(h,r.id,`run-status:${r.id}:${r.status}:${r.finishedAt?.toISOString()??r.updatedAt.toISOString()}`,o,d),"RUNNING"===r.phase&&r.startedAt&&r.updatedAt>r.startedAt&&await this.record("RUN_CONTINUED",r.id,`run-continued:${r.id}:${r.updatedAt.toISOString()}`,o,d),r.sourcePlanId&&await this.record("RUN_PLAN_PLAYED",r.id,`run-plan-played:${r.id}:${r.sourcePlanId}`,o,d),r.parentRunId&&"PLAN_PLAY"!==r.followUpMode&&await this.record("RUN_FOLLOW_UP",r.id,`run-follow-up:${r.id}:${r.parentRunId}`,o,d),"IMPORTED"===r.origin&&await this.record("RUN_IMPORTED",r.id,`run-imported:${r.id}:${r.updatedAt.toISOString()}`,o,d),await this.record("RUN_USAGE_THRESHOLD",r.id,`run-usage:${r.id}:${r.updatedAt.toISOString()}`,o,{...d,cursorValue:r.updatedAt.toISOString()});let p=r.questionBatches[0];if(p){let e={...o,run:{...o.run,questions:p.questions}};"PENDING"===p.status?await this.record("RUN_QUESTION_NEEDED",r.id,`run-question:${p.id}:pending`,e,d):"ANSWERED"===p.status&&await this.record("RUN_QUESTION_ANSWERED",r.id,`run-question:${p.id}:answered`,e,d)}let m=r.events[0];m&&await this.record("RUN_EVENT_MATCH",r.id,`run-event:${m.id}`,o,{...d,event:m});let f=r.toolCalls[0];f&&await this.record("RUN_EVENT_MATCH",r.id,`run-tool:${f.id}:${f.status}`,o,{...d,toolCall:f})}async consumeBuilds(){let e=a.agentEventBus.iterate(a.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,n.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,s.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:u(r.codebase.repository,r.codebase.defaultBranch),agent:c(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=l(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=a.agentEventBus.iterate(a.WORKTREE_CHANGED_TOPIC);try{for await(let t of e){if(!this.running)break;let e=t.worktreeOverviewChanged,r=await (0,n.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,s.mergeSessionData)(i,{repo:u(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=a.agentEventBus.iterate(a.CODEBASE_CHANGED_TOPIC);try{for await(let t of e){if(!this.running)break;let e=await (0,n.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:u(t.repository,t.defaultBranch),agent:c(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=(0,o.diskSpaceStateCursor)(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((0,o.diskSpaceSessionData)(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 r=await this.diskSpace.overview();for(let i of r.agents){let a=(0,o.diskSpaceSessionData)(r.settings,i,e?"STARTUP_RECONCILE":"STATE_AUDIT"),n=JSON.stringify((0,o.diskSpaceStateCursor)(a));(e||this.diskStateFingerprints.get(i.agent.id)!==n)&&await this.emitDiskSnapshot(a,{changeId:(0,t.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*r.DISK_SPACE_POLL_INTERVAL_SECONDS),this.diskAuditTimer.unref?.())}}async consumeAgents(){let e=a.agentEventBus.iterate(a.AGENT_CHANGED_TOPIC);try{for await(let t of e){if(!this.running)break;let e=await (0,n.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?.()}}}])},499162,e=>{"use strict";let t=/^([A-Za-z0-9_-]+)(?:\[(\d+)\])?$/,r=/^[A-Za-z0-9_-]+(?:\[\d+\])?(?:\.[A-Za-z0-9_-]+(?:\[\d+\])?)*$/,i=/\{\{\s*([A-Za-z0-9_-]+(?:\[\d+\])?(?:\.[A-Za-z0-9_-]+(?:\[\d+\])?)*)\s*\}\}/g,a=/\{\{([^{}]*)\}\}/g;function n(e){return e.split(".").flatMap(r=>{let i=t.exec(r);if(!i)throw Error(`Invalid session path: ${e}`);return void 0===i[2]?[i[1]]:[i[1],Number(i[2])]})}function s(e,t){let r=e;for(let e of n(t)){if(null==r)return;if("number"==typeof e){if(!Array.isArray(r))return;r=r[e]}else{if("object"!=typeof r||Array.isArray(r))return;r=r[e]}}return r}e.s(["getSessionValue",0,s,"hasSessionValue",0,function(e,t){return void 0!==s(e,t)},"invalidWorkflowValueBindings",0,function e(t,i=[]){if(Array.isArray(t))for(let r of t)e(r,i);else if(t&&"object"==typeof t)for(let a of("SESSION"!==t.source||"string"==typeof t.path&&r.test(t.path)||i.push("Session bindings require a valid dotted path"),Object.values(t)))e(a,i);else if("string"==typeof t&&/\{\{|\}\}/.test(t)){let e=t.replace(a,"");for(let n of(/\{\{|\}\}/.test(e)&&i.push("Text interpolation contains unmatched braces"),t.matchAll(a)))r.test(n[1].trim())||i.push("Text interpolation requires a valid dotted path")}return i},"mergeSessionData",0,function(e,t){let r=(e,t)=>{if(e&&t&&"object"==typeof e&&"object"==typeof t&&!Array.isArray(e)&&!Array.isArray(t)){let i={...e};for(let[e,a]of Object.entries(t))i[e]=r(i[e],a);return i}return structuredClone(t)};return r(e,t)},"resolveWorkflowValue",0,function e(t,r){var a,n;return t&&"object"==typeof t&&!Array.isArray(t)&&"SESSION"===t.source&&"string"==typeof t.path?s(r,t.path):t&&"object"==typeof t&&!Array.isArray(t)&&"LITERAL"===t.source?t.value:Array.isArray(t)?t.map(t=>e(t,r)):t&&"object"==typeof t?Object.fromEntries(Object.entries(t).map(([t,i])=>[t,e(i,r)])):"string"==typeof t?(a=t,n=r,a.replace(i,(e,t)=>{let r=s(n,t);return null==r?"":"string"==typeof r?r:JSON.stringify(r)})):t},"setSessionValue",0,function(e,t,r){let i=structuredClone(e),a=n(t),s=i;return a.forEach((e,i)=>{if(i===a.length-1){if("number"==typeof e){if(!Array.isArray(s))throw Error(`Expected an array at ${t}`);s[e]=r}else{if(Array.isArray(s))throw Error(`Expected an object at ${t}`);s[e]=r}return}let n="number"==typeof a[i+1];if("number"==typeof e){if(!Array.isArray(s))throw Error(`Expected an array at ${t}`);let r=s[e];r&&"object"==typeof r||(s[e]=n?[]:{}),s=s[e]}else{if(Array.isArray(s))throw Error(`Expected an object at ${t}`);let r=s[e];r&&"object"==typeof r||(s[e]=n?[]:{}),s=s[e]}}),i},"workflowSessionData",0,function(e){let t=JSON.parse(e);if(!t||"object"!=typeof t||Array.isArray(t))throw Error("Workflow session data must be a JSON object");return t},"workflowValueSessionPaths",0,function e(t,a=new Set){if(Array.isArray(t))for(let r of t)e(r,a);else if(t&&"object"==typeof t)for(let i of("SESSION"===t.source&&"string"==typeof t.path&&r.test(t.path)&&a.add(t.path),Object.values(t)))e(i,a);else if("string"==typeof t)for(let e of t.matchAll(i))a.add(e[1]);return a}])},493015,49172,e=>{"use strict";var t=e.i(397554),r=e.i(827957);e.i(582482);var i=e.i(783396),a=e.i(318905),n=e.i(91022);class s extends Error{status;errors;constructor(e,t,r){super(e),this.status=t,this.errors=r,this.name="AppleDeveloperRequestError"}}async function o(e=new n.CredentialService){let t=await e.getJson(a.CREDENTIALS.appStoreConnectSettings);if(!t)throw Error("App Store Connect API credentials are not configured");let r=(0,i.appStoreConnectConnectionSettings)(t),s=await e.getText(a.CREDENTIALS.appStoreConnectPrivateKey);if(!s)throw Error("App Store Connect API credentials are not configured");return{issuerId:r.issuerId,keyId:r.keyId,privateKey:s}}e.s(["AppleDeveloperClient",0,class{credentials;fetcher;constructor(e,t=fetch){this.credentials=e,this.fetcher=t}async token(){let e;try{e=await (0,t.importPKCS8)(this.credentials.privateKey,"ES256")}catch{throw Error("The App Store Connect key must be an ES256 PKCS#8 private key")}return new r.SignJWT({}).setProtectedHeader({alg:"ES256",kid:this.credentials.keyId,typ:"JWT"}).setIssuer(this.credentials.issuerId).setAudience("appstoreconnect-v1").setIssuedAt().setExpirationTime("15m").sign(e)}async request(e,t={}){let r,i=await this.token(),a=e.startsWith("http")?e:`https://api.appstoreconnect.apple.com${e}`;try{r=await this.fetcher(a,{...t,signal:t.signal??AbortSignal.timeout(2e4),headers:{accept:"application/json",authorization:`Bearer ${i}`,...t.body?{"content-type":"application/json"}:{},...t.headers}})}catch(e){if(e instanceof Error&&("TimeoutError"===e.name||"AbortError"===e.name))throw Error("Apple Developer API timed out; retry the operation");throw Error("Could not connect to the Apple Developer API")}if(204===r.status)return;let n=await r.json().catch(()=>({}));if(!r.ok){let e=n.errors?.map(e=>e.detail||e.title||e.code).filter(Boolean).join("; ");throw new s(401===r.status||403===r.status?"Apple rejected the API key or it lacks Certificates, Identifiers & Profiles permission":e||`Apple Developer API returned HTTP ${r.status}`,r.status,n.errors??[])}return n}async list(e){let t=[],r=e;for(;r;){let e=await this.request(r);t.push(...e.data),r=e.links?.next??null}return t}listProfiles(){return this.list("/v1/profiles?limit=200&include=bundleId,certificates,devices")}listCertificates(){return this.list("/v1/certificates?limit=200")}listBundleIds(){return this.list("/v1/bundleIds?limit=200")}listDevices(){return this.list("/v1/devices?limit=200")}async createProfile(e){let t={bundleId:{data:{type:"bundleIds",id:e.bundleIdId}},certificates:{data:e.certificateIds.map(e=>({type:"certificates",id:e}))}};return e.deviceIds?.length&&(t.devices={data:e.deviceIds.map(e=>({type:"devices",id:e}))}),this.request("/v1/profiles",{method:"POST",body:JSON.stringify({data:{type:"profiles",attributes:{name:e.name,profileType:e.profileType},relationships:t}})})}deleteProfile(e){return this.request(`/v1/profiles/${encodeURIComponent(e)}`,{method:"DELETE"})}revokeCertificate(e){return this.request(`/v1/certificates/${encodeURIComponent(e)}`,{method:"DELETE"})}},"AppleDeveloperRequestError",0,s,"storedAppleDeveloperCredentials",0,o],49172),e.s([],493015)},925991,e=>{"use strict";var t=e.i(666680),r=e.i(885418),i=e.i(243783);e.i(805422);var a=e.i(694355),n=e.i(661983),s=e.i(504173),o=e.i(518733);let l=new Set(["SUCCEEDED","FAILED","CANCELLED","TIMED_OUT","INVALID"]),u={agents:{include:{agent:!0}},jobs:{orderBy:{createdAt:"asc"}}};function c(e){return null!==e.lastSeenAt&&Date.now()-e.lastSeenAt.getTime()<=(0,a.agentOnlineWindowMs)(e)&&null===e.disconnectedAt}function d(e){try{let t=JSON.parse(e.capabilitiesJson);return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}catch{return[]}}function h(e){return null===e?null:JSON.parse(e)}function p(e){let t=h(e.payloadJson);return(e.kind===r.BUILD_DATA_DELETE_JOB_KIND?(0,r.buildDataDeletePayload)(t).targets:(0,r.buildDataTargetsPayload)(t).targets).map(e=>e.path)}function m(e,t){let i=e===r.BUILD_DATA_DELETE_JOB_KIND?"delete":"size";return`Invalid Build Data ${i} result: ${t instanceof Error?t.message:String(t)}`}function f(e,t,r){try{for(let i of p(t)){let a=e.get(g(t.agentId,i));a&&(a.error=r)}}catch{}}function g(e,r){return(0,t.createHash)("sha256").update(e).update("\0").update(r).digest("base64url")}e.s(["BuildDataService",0,class{agentControlService;initialized;constructor(e){this.agentControlService=e,this.initialized=!1,this.agentControlService.registerCompletionHandler(r.BUILD_DATA_DELETE_JOB_KIND,e=>this.projectDeletion(e))}async initialize(){this.initialized||(await this.pruneHistory(),this.initialized=!0)}async refresh(e){await this.initialize();let r=e?.trim()||(0,t.randomUUID)();return await this.ensureCollection(r),await this.getCollection(r)}async getCollection(e){await this.initialize();let t=await this.loadCollection(e);if(!t)return null;!t.finishedAt&&t.deadlineAt.getTime()<=Date.now()&&(await this.expireCollection(t),t=await this.loadCollection(e)??t);let r=await this.snapshot(t);if("COMPLETED"===r.status&&!t.finishedAt){let t=new Date,a=await (0,i.getPrismaClient)();await a.buildDataCollection.updateMany({where:{id:e,finishedAt:null},data:{finishedAt:t}}),r.finishedAt=t.toISOString()}return r}async *subscribe(e){await this.initialize();let t=n.agentEventBus.iterate((0,n.buildDataCollectionChangedTopic)(e));try{let r=await this.getCollection(e);for(r&&(yield r);;){if((await t.next()).done)return;let r=await this.getCollection(e);r&&(yield r)}}finally{await t.return?.()}}async calculateSizes(e,t,i){let a=await this.requireCollection(e);return await this.createTargetJobs(a,t,i,r.BUILD_DATA_SIZE_JOB_KIND),await this.getCollection(e)}async deleteEntries(e,t,i,a=!1){let n=await this.requireCollection(e);return await this.createTargetJobs(n,t,i,r.BUILD_DATA_DELETE_JOB_KIND,a),await this.getCollection(e)}async history(e=100,t){await this.initialize(),await this.pruneHistory();let r=Math.max(1,Math.min(e,200)),a=await (0,i.getPrismaClient)(),n=t?await a.buildDataDeletionHistory.findUnique({where:{id:t},select:{id:!0,deletedAt:!0}}):null,s=await a.buildDataDeletionHistory.findMany({where:n?{OR:[{deletedAt:{lt:n.deletedAt}},{deletedAt:n.deletedAt,id:{lt:n.id}}]}:void 0,orderBy:[{deletedAt:"desc"},{id:"desc"}],take:r+1}),o=s.length>r,l=s.slice(0,r);return{items:l,nextCursor:o?l.at(-1)?.id??null:null}}async clearHistory(){await this.initialize();let e=await (0,i.getPrismaClient)();return(await e.buildDataDeletionHistory.deleteMany()).count}async ensureCollection(e){let t=await (0,i.getPrismaClient)(),a=await t.buildDataCollection.findUnique({where:{id:e},select:{id:!0}});if(!a){let i=await this.agentControlService.listAgents();try{a=await t.buildDataCollection.create({data:{id:e,deadlineAt:new Date(Date.now()+6e4),agents:{create:i.map(e=>({agentId:e.id,initialStatus:c(e)?d(e).includes(r.BUILD_DATA_SCAN_JOB_KIND)?"QUEUING":"UNSUPPORTED":"OFFLINE"}))}},select:{id:!0}}),this.publish(e)}catch(r){if(!(a=await t.buildDataCollection.findUnique({where:{id:e},select:{id:!0}})))throw r}}await this.ensureScanJobs(e)}async ensureScanJobs(e){let t=await (0,i.getPrismaClient)(),a=await t.buildDataCollection.findUnique({where:{id:e},select:{deadlineAt:!0,finishedAt:!0}});if(!a||a.finishedAt||a.deadlineAt<=new Date)return;let n=await t.buildDataCollectionAgent.findMany({where:{collectionId:e,initialStatus:"QUEUING"},include:{agent:!0}}),s=new Set((await t.agentJob.findMany({where:{buildDataCollectionId:e,kind:r.BUILD_DATA_SCAN_JOB_KIND},select:{agentId:!0}})).map(e=>e.agentId));for(let i of n)if(!s.has(i.agentId))try{let a=await t.worktree.findMany({where:{missingAt:null,codebase:{agentId:i.agentId}},select:{id:!0,folder:!0}});await this.agentControlService.createJob({agentId:i.agentId,kind:r.BUILD_DATA_SCAN_JOB_KIND,payload:{mode:i.agent.derivedDataLocationMode,path:i.agent.derivedDataPath,worktrees:a},idempotencyKey:`build-data:scan:${e}`,timeoutSeconds:45,buildDataCollectionId:e,visibility:"SYSTEM"})}catch(r){await t.buildDataCollectionAgent.update({where:{collectionId_agentId:{collectionId:e,agentId:i.agentId}},data:{initialStatus:"FAILED",error:r instanceof Error?r.message:String(r)}}),this.publish(e)}}async createTargetJobs(e,t,a,n,s=!1){let o=[...new Set(t)];if(!o.length)throw Error("Select at least one Derived Data entry");let l=new Map(e.entries.map(e=>[e.id,e])),u=o.map(e=>{let t=l.get(e);if(!t)throw Error("A selected Derived Data entry is no longer available");return t});if(n===r.BUILD_DATA_DELETE_JOB_KIND&&!s){let e=u.filter(e=>e.locked||e.activeResources.length>0);if(e.length)throw Error(`Explicit override confirmation is required to delete protected Derived Data: ${e.map(e=>e.name).join(", ")}`)}let h=new Map;for(let e of u){let t=h.get(e.agent.id)??[];t.push(e),h.set(e.agent.id,t)}let p=await (0,i.getPrismaClient)(),m=[];for(let[e,t]of h){let r=t[0].agent,i=await p.agent.findUnique({where:{id:e}});if(!i||!c(i))throw Error(`${r.name} is offline; reconnect it before running this operation`);if(!d(i).includes(n))throw Error(`${r.name} must be updated before this operation can run`);m.push({agentId:e,entries:t})}for(let{agentId:t,entries:i}of m){let s=n===r.BUILD_DATA_DELETE_JOB_KIND?[...new Map(i.filter(e=>!!e.worktreeId).map(e=>[e.worktreeId,e])).values()]:[],o=[];try{for(let e of s)await p.derivedDataCleanupLease.create({data:{worktreeId:e.worktreeId,agentId:t,path:e.path,source:"USER",expiresAt:new Date(Date.now()+6048e5)}}),o.push(e.worktreeId);let r=await this.agentControlService.createJob({agentId:t,kind:n,payload:{targets:i.map(({path:e,rootPath:t})=>({path:e,rootPath:t}))},idempotencyKey:`${n}:${e.id}:${a}:${t}`,timeoutSeconds:604800,buildDataCollectionId:e.id,visibility:"SYSTEM"});s.length&&await p.derivedDataCleanupLease.updateMany({where:{worktreeId:{in:s.map(e=>e.worktreeId)},jobId:null},data:{jobId:r.id}})}catch(e){throw o.length&&await p.derivedDataCleanupLease.deleteMany({where:{worktreeId:{in:o},source:"USER",jobId:null}}),e}}}async requireCollection(e){let t=await this.getCollection(e);if(!t)throw Error("Derived Data collection not found");if("COMPLETED"!==t.status)throw Error("Wait for the Derived Data scan to finish");return t}async loadCollection(e){return(await (0,i.getPrismaClient)()).buildDataCollection.findUnique({where:{id:e},include:u})}progress(e){let t=new Map(e.jobs.filter(e=>e.kind===r.BUILD_DATA_SCAN_JOB_KIND).map(e=>[e.agentId,e])),i=e.agents.map(e=>{let i=t.get(e.agentId),a=e.initialStatus,n=e.error,s=[];if("QUEUING"===e.initialStatus&&i&&(a=i.status,n=i.error,"SUCCEEDED"===i.status))try{s=(0,r.parseBuildDataScanResult)(h(i.resultJson)).warnings}catch(e){a="INVALID",n=e instanceof Error?e.message:String(e)}return{agent:e.agent,status:a,jobId:i?.id??null,error:n,warnings:s}}),a=i.filter(({status:e})=>"OFFLINE"!==e&&"UNSUPPORTED"!==e),n=a.filter(({status:e})=>l.has(e));return{agents:i,eligibleCount:a.length,finishedCount:n.length,successfulCount:a.filter(({status:e})=>"SUCCEEDED"===e).length}}async snapshot(e){let t=this.progress(e),r=await this.entries(e,!1);return{id:e.id,status:t.finishedCount===t.eligibleCount?"COMPLETED":"COLLECTING",createdAt:e.createdAt.toISOString(),deadlineAt:e.deadlineAt.toISOString(),finishedAt:e.finishedAt?.toISOString()??null,progress:t,entries:r}}async entries(e,t){let a=await (0,i.getPrismaClient)(),n=new Map(e.agents.map(e=>[e.agentId,e.agent])),u=await a.worktree.findMany({where:{missingAt:null,codebase:{agentId:{in:[...n.keys()]}}},include:{codebase:{select:{agentId:!0}}}}),c=new Map;for(let e of u){let t=c.get(e.codebase.agentId)??[];t.push(e),c.set(e.codebase.agentId,t)}let d=new Map;for(let t of e.jobs){let e;if(t.kind!==r.BUILD_DATA_SCAN_JOB_KIND||"SUCCEEDED"!==t.status)continue;let i=n.get(t.agentId);if(i){try{e=(0,r.parseBuildDataScanResult)(h(t.resultJson))}catch{continue}for(let r of e.entries){let e=(r.workspacePath?(c.get(t.agentId)??[]).filter(e=>(function(e,t){let r="/"===e?e:e.replace(/\/+$/,"");return t===r||t.startsWith(`${r}/`)})(e.folder,r.workspacePath)).sort((e,t)=>t.folder.length-e.folder.length):[])[0]??null,a=g(t.agentId,r.path);d.set(a,{id:a,name:r.name,kind:r.kind,status:"DEVICE_SUPPORT"===r.kind?"READY":"PENDING"===r.kind?"PENDING":"SHARED_CACHE"===r.kind?"SHARED_CACHE":e?"READY":"UNLINKED",workspacePath:r.workspacePath,worktreeId:e?.id??null,worktreePath:e?(0,s.worktreeDisplayPath)(e.folder,i.baseRepoDirectory):null,sizeBytes:null,operation:"IDLE",error:null,agent:i,path:r.path,rootPath:r.rootPath,modifiedAt:r.modifiedAt,volumeId:r.volumeId,locked:!1,activeResources:[]})}}}for(let i of e.jobs){if(i.kind===r.BUILD_DATA_SIZE_JOB_KIND&&"SUCCEEDED"===i.status)try{for(let e of(0,r.parseBuildDataSizeResult)(h(i.resultJson)).sizes){let t=d.get(g(i.agentId,e.path));t&&(t.sizeBytes=e.sizeBytes,t.error=e.error)}}catch(e){f(d,i,m(r.BUILD_DATA_SIZE_JOB_KIND,e))}if(i.kind===r.BUILD_DATA_DELETE_JOB_KIND&&"SUCCEEDED"===i.status)try{for(let e of(0,r.parseBuildDataDeleteResult)(h(i.resultJson)).deleted){let r=g(i.agentId,e.path),a=d.get(r);a&&(e.deleted&&!t?d.delete(r):a.error=e.error)}}catch(e){f(d,i,m(r.BUILD_DATA_DELETE_JOB_KIND,e))}if("QUEUED"===i.status||"RUNNING"===i.status){if(i.kind!==r.BUILD_DATA_SIZE_JOB_KIND&&i.kind!==r.BUILD_DATA_DELETE_JOB_KIND)continue;try{for(let e of p(i)){let t=d.get(g(i.agentId,e));t&&(t.operation=i.kind===r.BUILD_DATA_DELETE_JOB_KIND?"DELETING":"SIZING")}}catch{}}if("SUCCEEDED"!==i.status&&l.has(i.status)&&(i.kind===r.BUILD_DATA_SIZE_JOB_KIND||i.kind===r.BUILD_DATA_DELETE_JOB_KIND))try{for(let e of p(i)){let t=d.get(g(i.agentId,e));t&&(t.error=i.error||"Build Data operation failed")}}catch{}}let y=[...d.values()],w=y.map(e=>e.worktreeId).filter(e=>!!e),[b,E]=await Promise.all([a.derivedDataLock.findMany({where:{OR:y.map(e=>({agentId:e.agent.id,path:e.path}))},select:{agentId:!0,path:!0}}),(0,o.executingResourcesByWorktree)(w)]),S=new Set(b.map(e=>`${e.agentId}\0${e.path}`));for(let e of y)e.locked=S.has(`${e.agent.id}\0${e.path}`),e.activeResources=e.worktreeId?E.get(e.worktreeId)??[]:[];return y.sort((e,t)=>e.agent.name.localeCompare(t.agent.name)||(null===e.modifiedAt?1:null===t.modifiedAt?-1:new Date(e.modifiedAt).getTime()-new Date(t.modifiedAt).getTime())||e.name.localeCompare(t.name))}async setEntryLocked(e,r,a){let n=(await this.requireCollection(e)).entries.find(e=>e.id===r);if(!n)throw Error("Derived Data entry not found");let s=await (0,i.getPrismaClient)();return a?await s.derivedDataLock.upsert({where:{agentId_path:{agentId:n.agent.id,path:n.path}},create:{id:(0,t.randomUUID)(),agentId:n.agent.id,path:n.path},update:{}}):await s.derivedDataLock.deleteMany({where:{agentId:n.agent.id,path:n.path}}),this.publish(e),await this.getCollection(e)}async expireCollection(e){let t=await (0,i.getPrismaClient)(),a=new Set(e.jobs.filter(e=>e.kind===r.BUILD_DATA_SCAN_JOB_KIND).map(e=>e.agentId));await t.buildDataCollectionAgent.updateMany({where:{collectionId:e.id,initialStatus:"QUEUING",agentId:{notIn:[...a]}},data:{initialStatus:"TIMED_OUT"}}),await this.agentControlService.timeoutBuildDataCollectionJobs(e.id),this.publish(e.id)}async projectDeletion(e){let a;if("SUCCEEDED"!==e.status||!e.resultJson)return;await this.pruneHistory();let n=await (0,i.getPrismaClient)();if(await n.buildDataDeleteProjection.findUnique({where:{jobId:e.id}}))return;try{a=(0,r.parseBuildDataDeleteResult)(h(e.resultJson)).deleted.filter(e=>e.deleted)}catch(i){let t=m(r.BUILD_DATA_DELETE_JOB_KIND,i);try{await n.buildDataDeleteProjection.create({data:{jobId:e.id,error:t}})}catch(t){if(!await n.buildDataDeleteProjection.findUnique({where:{jobId:e.id}}))throw t}return}if(!a.length)return void await n.buildDataDeleteProjection.create({data:{jobId:e.id}});let s=(0,r.buildDataDeletePayload)(h(e.payloadJson)),o=e.buildDataCollectionId?await this.loadCollection(e.buildDataCollectionId):null,l=new Map((o?await this.entries(o,!0):[]).filter(t=>t.agent.id===e.agentId).map(e=>[e.path,e])),u=new Map(s.targets.map(e=>[e.path,e])),c=await n.agent.findUnique({where:{id:e.agentId}});if(c)try{await n.$transaction(async r=>{if(!await r.buildDataDeleteProjection.findUnique({where:{jobId:e.id}}))for(let i of(await r.buildDataDeleteProjection.create({data:{jobId:e.id}}),a)){let a=l.get(i.path),n=u.get(i.path),o=n?.worktreeId??a?.worktreeId??null,d=o?(await r.worktree.findUnique({where:{id:o},select:{id:!0}}))?.id??null:null;await r.buildDataDeletionHistory.create({data:{id:(0,t.randomUUID)(),agentId:e.agentId,agentName:c.name,folderName:n?.name??a?.name??i.path,worktreeId:d,worktreePath:n?.worktreePath??a?.worktreePath??null,source:s.source,entryKind:n?.kind??a?.kind??"PROJECT",jobId:e.id,targetKey:a?.id??g(e.agentId,i.path)}})}})}catch(t){if(!await n.buildDataDeleteProjection.findUnique({where:{jobId:e.id}}))throw t}}async pruneHistory(){let e=await (0,i.getPrismaClient)();await e.buildDataDeletionHistory.deleteMany({where:{deletedAt:{lt:new Date(Date.now()-7776e6)}}})}publish(e){n.agentEventBus.publish(n.BUILD_DATA_CHANGED_TOPIC,{buildDataCollectionChanged:{id:e}}),n.agentEventBus.publish((0,n.buildDataCollectionChangedTopic)(e),{buildDataCollectionChanged:{id:e}})}}])},396763,e=>{"use strict";e.i(925991),e.s([])},163853,e=>e.a(async(t,r)=>{try{e.s(["cacheTransferredArtifact",()=>g,"cachedArtifact",()=>f,"materializeArtifact",()=>b]);var i=e.i(666680),a=e.i(912714),n=e.i(660526),s=e.i(750227),o=e.i(243783),l=e.i(503675),u=e.i(887394),c=t([u]);[u]=c.then?(await c)():c;let E=process.env.ARTIFACT_CACHE_DIRECTORY?.trim()||(0,s.join)((0,n.tmpdir)(),"ade-build-artifact-cache"),S=Number(process.env.ARTIFACT_CACHE_MAX_BYTES)||0x140000000,v=globalThis,I=v.buildArtifactMaterializations??(v.buildArtifactMaterializations=new Map);async function d(e,t){try{await (0,a.rename)(e,t);return}catch(e){if("EXDEV"!==e.code)throw e}let r=`${t}.${(0,i.randomUUID)()}.incoming`;try{await (0,a.copyFile)(e,r),await (0,a.rename)(r,t),await (0,a.rm)(e,{force:!0})}finally{await (0,a.rm)(r,{force:!0}).catch(()=>{})}}async function h(e){try{let t=JSON.parse(await (0,a.readFile)(e,"utf8"));if(!t||"object"!=typeof t)return null;let{filename:r,contentType:i,size:n}=t;if("string"!=typeof r||"string"!=typeof i||"number"!=typeof n)return null;return{filename:r,contentType:i,size:n}}catch{return null}}async function p(e){let t=(0,s.join)(E,e),r=await h(`${t}.json`);if(!r)return null;try{let i=await (0,a.stat)(t);if(!i.isFile()||i.size!==r.size)return null;let n=new Date;return await (0,a.utimes)(t,n,n).catch(()=>{}),{path:t,etag:`"${e}"`,...r}}catch{return null}}async function m(e,t){var r;let a=(0,u.getServerServices)(),n=await a.buildsService.artifactForInstall(e,t);if(!n)throw Error("Build artifact not found");return{artifact:n,key:(r=n.checksum??n.createdAt,(0,i.createHash)("sha1").update(`${t}:${r}`).digest("hex"))}}async function f(e,t){let{key:r}=await m(e,t);return p(r)}async function g(e){let{key:t}=await m(e.buildId,e.artifactId);await (0,a.mkdir)(E,{recursive:!0,mode:448});let r=(0,s.join)(E,t);await d(e.path,r);let i=(await (0,a.stat)(r)).size,n={filename:e.filename,contentType:e.contentType,size:i};return await (0,a.writeFile)(`${r}.json`,JSON.stringify(n),{mode:384}),await y(t).catch(()=>{}),{path:r,etag:`"${t}"`,...n}}async function y(e){let t,r=new Set;try{let e=await (0,o.getPrismaClient)();for(let t of(await e.buildArtifactTransfer.findMany({where:{status:{in:["READY","DOWNLOADING"]},expiresAt:{gt:new Date},stagingPath:{not:null}},select:{stagingPath:!0}})))t.stagingPath&&r.add(t.stagingPath)}catch{}try{t=await (0,a.readdir)(E)}catch{return}let i=[],n=Date.now()-216e5;for(let o of t){if(o.endsWith(".json"))continue;let t=(0,s.join)(E,o);try{let s=await (0,a.stat)(t);if(!s.isFile())continue;if(o.endsWith(".incoming")){s.mtimeMs<n&&await (0,a.rm)(t,{force:!0}).catch(()=>{});continue}i.push({path:t,size:s.size,mtimeMs:s.mtimeMs,keep:o===e||r.has(t)})}catch{continue}}i.sort((e,t)=>e.mtimeMs-t.mtimeMs);let l=i.reduce((e,t)=>e+t.size,0);for(let e of i)!e.keep&&(l<=S&&e.mtimeMs>=n||(await (0,a.rm)(e.path,{force:!0}).catch(()=>{}),await (0,a.rm)(`${e.path}.json`,{force:!0}).catch(()=>{}),l-=e.size))}async function w(e,t,r,n){let o=(0,i.randomUUID)(),c=(0,u.getServerServices)(),h=await c.buildsService.getBuild(e);if(!h?.agentId)throw Error("Build agent is unavailable");let p=Math.min(18e5,12e4+(n??0)/1e3),m=null;try{let[i]=await Promise.all([(0,l.expectArtifactTransfer)(o,h.agentId,p),c.buildsService.prepareArtifactDownload(e,t,o,p)]);m=i.path,await (0,a.mkdir)(E,{recursive:!0,mode:448});let n=(0,s.join)(E,r);await d(i.path,n),m=null;let u=(await (0,a.stat)(n)).size,f={filename:i.filename,contentType:i.contentType,size:u};return await (0,a.writeFile)(`${n}.json`,JSON.stringify(f),{mode:384}),await y(r).catch(()=>{}),{path:n,etag:`"${r}"`,...f}}catch(e){throw(0,l.cancelArtifactTransfer)(o,e),m&&await (0,a.rm)(m,{force:!0}).catch(()=>{}),e}}async function b(e,t){let{artifact:r,key:i}=await m(e,t),a=await p(i);if(a)return a;let n=I.get(i);if(n)return n;let s=w(e,t,i,r.sizeBytes).finally(()=>{I.delete(i)});return I.set(i,s),s}r()}catch(e){r(e)}},!1),933416,e=>e.a(async(t,r)=>{try{e.s(["ARTIFACT_TRANSFER_CHUNK_BYTES",()=>I,"appendBuildArtifactTransferChunk",()=>w,"buildArtifactFileChecksum",()=>b,"buildArtifactTransferStatus",()=>g,"completeBuildArtifactTransferUpload",()=>E,"failBuildArtifactTransferForJob",()=>v,"initializeBuildArtifactTransfer",()=>y,"readBuildArtifactTransferRange",()=>S]);var i=e.i(666680),a=e.i(902157),n=e.i(912714),s=e.i(660526),o=e.i(750227),l=e.i(243783);e.i(805422);var u=e.i(661983),c=e.i(163853),d=t([c]);[c]=d.then?(await d)():d;let I=0x1000000,A=Number(process.env.ARTIFACT_TRANSFER_MAX_BYTES)||0x500000000,k=process.env.ARTIFACT_TRANSFER_DIRECTORY?.trim()||(0,o.join)((0,s.tmpdir)(),"ade-build-artifact-transfers"),_=globalThis,T=_.buildArtifactTransferLocks??(_.buildArtifactTransferLocks=new Map);async function h(e,t,r){let i=0;for(;i<t.byteLength;){let a=t.byteLength-i,{bytesWritten:n}=await e.write(t,i,a,r+i);if(!Number.isSafeInteger(n)||n<=0||n>a)throw Error("Artifact transfer file write made no progress");i+=n}}async function p(e,t){let r;for(;T.has(e);)await T.get(e);let i=new Promise(e=>{r=e});T.set(e,i);try{return await t()}finally{T.get(e)===i&&T.delete(e),r()}}function m(e){u.agentEventBus.publish((0,u.buildTopic)(e),{buildChanged:{id:e}}),u.agentEventBus.publish(u.BUILDS_CHANGED_TOPIC,{buildsChanged:{id:e}})}async function f(e,t,r){let i=await (0,l.getPrismaClient)(),a=await i.buildArtifactTransfer.findUnique({where:{id:e},include:{artifact:{include:{build:!0}}}});if(!a)throw Error("Artifact transfer not found");if(!("source"===r?a.sourceAgentId===t:"target"===r?a.targetAgentId===t:a.sourceAgentId===t||a.targetAgentId===t))throw Error("Artifact transfer belongs to another agent");return a.expiresAt.getTime()<=Date.now()&&!["SUCCEEDED","FAILED","CANCELLED","EXPIRED"].includes(a.status)&&(a=await i.buildArtifactTransfer.update({where:{id:a.id},data:{status:"EXPIRED",error:"Artifact transfer expired",finishedAt:new Date},include:{artifact:{include:{build:!0}}}}),m(a.artifact.buildId)),a}async function g(e,t){return f(e,t,"either")}async function y(e,t,r){return p(e,async()=>{let i=await f(e,t,"source");if(!["QUEUED","UPLOADING"].includes(i.status))throw Error("Artifact transfer is not accepting uploads");if(!Number.isSafeInteger(r.uploadLength)||r.uploadLength<=0||r.uploadLength>A)throw Error("Artifact upload length is invalid");let a=r.checksum.trim().toLowerCase();if(!/^[a-f0-9]{64}$/.test(a))throw Error("Artifact checksum must be SHA-256");let s=function(e){let t=e.trim();if(!t||t.length>255||(0,o.basename)(t)!==t||t.includes("\0"))throw Error("Artifact filename is invalid");return t}(r.filename),u=r.contentType.trim()||"application/octet-stream";if(null!==i.uploadLength&&(i.uploadLength!==r.uploadLength||i.checksum!==a||i.filename!==s))throw Error("Artifact upload metadata does not match the transfer");await (0,n.mkdir)(k,{recursive:!0,mode:448});let c=(0,o.join)(k,`${i.id}.upload`),d=0;try{d=(await (0,n.stat)(c)).size}catch{}d>r.uploadLength&&(await (0,n.rm)(c,{force:!0}),d=0);let h=await (0,n.statfs)(k);if(Number(h.bavail)*Number(h.bsize)<r.uploadLength-d+0x4000000)throw Error("The artifact relay does not have enough free disk space");let p=await (0,l.getPrismaClient)(),g=await p.buildArtifactTransfer.update({where:{id:i.id},data:{status:"UPLOADING",uploadLength:r.uploadLength,uploadOffset:d,checksum:a,filename:s,contentType:u,stagingPath:c,error:null},include:{artifact:{include:{build:!0}}}});return m(g.artifact.buildId),g})}async function w(e,t,r,i){return p(e,async()=>{let a=await f(e,t,"source");if("UPLOADING"!==a.status||null===a.uploadLength||!a.stagingPath)throw Error("Artifact transfer upload has not been initialized");if(!Number.isSafeInteger(r)||r!==a.uploadOffset)throw Error(`Upload offset mismatch; expected ${a.uploadOffset}`);if(!i.byteLength||i.byteLength>I)throw Error("Artifact upload chunks must be 1 to 16 MiB");if(r+i.byteLength>a.uploadLength)throw Error("Artifact upload exceeds its declared length");let s=await (0,n.open)(a.stagingPath,0===r?"w":"r+");try{await h(s,i,r),await s.sync()}finally{await s.close()}let o=await (0,l.getPrismaClient)(),u=await o.buildArtifactTransfer.update({where:{id:a.id},data:{uploadOffset:r+i.byteLength},include:{artifact:{include:{build:!0}}}});return m(u.artifact.buildId),u})}async function b(e){let t=(0,i.createHash)("sha256");for await(let r of(0,a.createReadStream)(e))t.update(r);return t.digest("hex")}async function E(e,t){return p(e,async()=>{let r=await f(e,t,"source");if("UPLOADING"!==r.status||null===r.uploadLength||r.uploadOffset!==r.uploadLength||!r.stagingPath||!r.checksum||!r.filename||!r.contentType)throw Error("Artifact upload is incomplete");let i=await b(r.stagingPath),a=await (0,l.getPrismaClient)();if(i!==r.checksum){await (0,n.rm)(r.stagingPath,{force:!0});let e=await a.buildArtifactTransfer.update({where:{id:r.id},data:{status:"FAILED",error:"Artifact checksum did not match",stagingPath:null,finishedAt:new Date},include:{artifact:{include:{build:!0}}}});throw m(e.artifact.buildId),Error("Artifact checksum did not match")}let s=await (0,c.cacheTransferredArtifact)({buildId:r.artifact.buildId,artifactId:r.artifactId,path:r.stagingPath,filename:r.filename,contentType:r.contentType}),o=await a.buildArtifactTransfer.update({where:{id:r.id},data:{status:"READY",stagingPath:s.path,uploadOffset:s.size,uploadLength:s.size,error:null},include:{artifact:{include:{build:!0}}}});return m(o.artifact.buildId),o})}async function S(e,t,r,i){let a=await f(e,t,"target");if(!["READY","DOWNLOADING","SUCCEEDED"].includes(a.status)||!a.stagingPath||null===a.uploadLength)throw Error("Artifact transfer is not ready to download");if(!Number.isSafeInteger(r)||!Number.isSafeInteger(i)||r<0||i<r||i>=a.uploadLength||i-r+1>I)throw Error("Artifact download range is invalid");let s=Buffer.allocUnsafe(i-r+1),o=await (0,n.open)(a.stagingPath,"r");try{if((await o.read(s,0,s.length,r)).bytesRead!==s.length)throw Error("Artifact download ended unexpectedly")}finally{await o.close()}let u=await (0,l.getPrismaClient)();return await u.buildArtifactTransfer.update({where:{id:a.id},data:{status:"SUCCEEDED"===a.status?"SUCCEEDED":"DOWNLOADING",downloadOffset:Math.max(a.downloadOffset,i+1)}}),m(a.artifact.buildId),{bytes:s,start:r,end:i,size:a.uploadLength,checksum:a.checksum,filename:a.filename??"artifact.tar.gz",contentType:a.contentType??"application/octet-stream"}}async function v(e,t){let r=await (0,l.getPrismaClient)(),i=await r.buildArtifactTransfer.findFirst({where:{OR:[{sourceJobId:e},{targetJobId:e}]},include:{artifact:!0}});!i||["SUCCEEDED","FAILED"].includes(i.status)||(await r.$transaction([r.buildArtifactTransfer.update({where:{id:i.id},data:{status:"FAILED",error:t,finishedAt:new Date}}),r.buildDeployment.updateMany({where:{transferId:i.id,status:{in:["QUEUED","TRANSFERRING"]}},data:{status:"FAILED",error:t,finishedAt:new Date}})]),m(i.artifact.buildId))}r()}catch(e){r(e)}},!1),503675,e=>{"use strict";var t=e.i(902157),r=e.i(912714),i=e.i(660526),a=e.i(750227),n=e.i(81111),s=e.i(188646);let o=globalThis,l=o.buildArtifactTransfers??(o.buildArtifactTransfers=new Map);function u(e,t){let r=l.get(e);r&&(l.delete(e),clearTimeout(r.timeout),r.reject(t instanceof Error?t:Error(String(t))))}async function c(e,o,c){let d=l.get(e);if(!d||d.agentId!==o)throw Error("Artifact upload is not expected");if(!c.body)throw Error("Artifact upload body is required");let h=(0,a.join)((0,i.tmpdir)(),`ade-build-artifact-upload-${e}`);try{await (0,s.pipeline)(n.Readable.fromWeb(c.body),(0,t.createWriteStream)(h,{mode:384}));let r=c.headers.get("x-artifact-filename")??"artifact",i="artifact";try{i=decodeURIComponent(r)}catch{}l.delete(e),clearTimeout(d.timeout);let a=c.headers.get("content-length");d.resolve({path:h,filename:i,contentType:c.headers.get("content-type")??"application/octet-stream",size:null!==a&&Number.isFinite(Number(a))?Number(a):null})}catch(t){throw await (0,r.rm)(h,{force:!0}),u(e,t),t}}e.s(["cancelArtifactTransfer",0,u,"expectArtifactTransfer",0,function(e,t,r=17e4){return new Promise((i,a)=>{let n=setTimeout(()=>{l.delete(e),a(Error("The agent did not upload the artifact in time"))},r);n.unref(),l.set(e,{agentId:t,resolve:i,reject:a,timeout:n})})},"receiveArtifactTransfer",0,c])},971619,e=>{"use strict";var t=e.i(750227);e.s(["effectiveBuildsDirectory",0,function(e){var r;return e.buildsDirectory??((r=e.baseRepoDirectory)?/^[a-z]:[\\/]/i.test(r)||r.startsWith("\\\\")?t.win32.join(r,"Builds"):t.posix.join(r,"Builds"):null)}])},984179,e=>{"use strict";let t=new Set(["QUEUED","PREPARING","RUNNING"]);e.s(["buildOutOfDate",0,function(e){let r;if(t.has(e.status)||!e.worktree||(e.worktree._count?.builds??0)>0||e.finishedAt&&(!e.worktree.lastCheckedAt||e.worktree.lastCheckedAt<e.finishedAt))return!1;try{r=JSON.parse(e.snapshotJson)}catch{return!1}if(!r||"object"!=typeof r||Array.isArray(r))return!1;let i=r.worktree;if(!i||"object"!=typeof i||Array.isArray(i))return!1;if("string"==typeof i.codeStateHash&&e.worktree.codeStateHash)return i.codeStateHash!==e.worktree.codeStateHash;if("string"==typeof i.headSha&&e.worktree.headSha!==i.headSha)return!0;if("boolean"==typeof i.hasStagedChanges){if(i.hasStagedChanges!==e.worktree.hasStagedChanges)return!0}else if(e.worktree.hasStagedChanges)return!0;return"boolean"==typeof i.hasUnstagedChanges?i.hasUnstagedChanges!==e.worktree.hasUnstagedChanges:e.worktree.hasUnstagedChanges}])},190714,e=>{"use strict";var t=e.i(907855);let r=t.object({status:t.string().optional(),codebaseId:t.string().optional(),worktreeId:t.string().optional(),first:t.number().int().min(1).max(200).default(50),after:t.string().optional()}),i=t.object({builds:t.array(t.unknown()),nextCursor:t.string().nullable()}),a=t.object({buildId:t.string().min(1),afterLogId:t.string().min(1).nullable().default(null),logLimit:t.number().int().min(1).max(5e3).default(1e3)}),n=t.object({build:t.unknown(),logs:t.array(t.unknown())}),s=t.object({worktreeId:t.string().min(1)}),o=t.object({project:t.unknown().nullable()}),l=t.union([t.object({buildId:t.string().min(1),requestId:t.string().min(1)}),t.object({worktreeId:t.string().min(1),configurationId:t.string().min(1),action:t.string().optional(),requestId:t.string().min(1)})]),u=t.object({destinations:t.array(t.unknown())}),c=t.object({worktreeId:t.string().min(1),configurationId:t.string().min(1),destination:t.record(t.string(),t.unknown()),scriptIds:t.array(t.string()).default([]),action:t.string().optional(),advancedSettings:t.record(t.string(),t.unknown()).optional(),requestId:t.string().min(1)}),d=t.object({build:t.unknown()}),h=t.object({worktreeId:t.string().min(1),reportPath:t.string().min(1).max(4e3),format:t.enum(["AUTO","LCOV","ISTANBUL"]).default("AUTO"),requestId:t.string().min(1)}),p=t.object({build:t.unknown()}),m=t.object({buildId:t.string().min(1),requestId:t.string().min(1)}),f=t.object({build:t.unknown()}),g=t.object({buildId:t.string().min(1),destinations:t.array(t.record(t.string(),t.unknown())).min(1),requestId:t.string().min(1)}),y=t.object({deployments:t.array(t.unknown())}),w=t.object({buildId:t.string().min(1),settings:t.record(t.string(),t.unknown()),requestId:t.string().min(1)}),b=t.object({export:t.unknown()});e.s(["CancelBuildToolInputSchema",0,m,"CancelBuildToolOutputSchema",0,f,"ExportBuildToolInputSchema",0,w,"ExportBuildToolOutputSchema",0,b,"GetBuildConfigurationsInputSchema",0,s,"GetBuildConfigurationsOutputSchema",0,o,"GetBuildDestinationsInputSchema",0,l,"GetBuildDestinationsOutputSchema",0,u,"GetBuildInputSchema",0,a,"GetBuildOutputSchema",0,n,"GetBuildsInputSchema",0,r,"GetBuildsOutputSchema",0,i,"ImportCoverageReportToolInputSchema",0,h,"ImportCoverageReportToolOutputSchema",0,p,"RunBuildToolInputSchema",0,g,"RunBuildToolOutputSchema",0,y,"StartBuildToolInputSchema",0,c,"StartBuildToolOutputSchema",0,d])},669602,e=>e.a(async(t,r)=>{try{e.s(["BuildsService",()=>C]);var i=e.i(666680),a=e.i(750227),n=e.i(807055),s=e.i(503083),o=e.i(243783);e.i(805422);var l=e.i(694355),u=e.i(661983),c=e.i(971619),d=e.i(163853),h=e.i(933416),p=t([d,h]);[d,h]=p.then?(await p)():p;let A=new Set(n.BUILD_CONFIGURATION_ICON_KEYS),k=new Set(["SUCCEEDED","FAILED","CANCELLED","TIMED_OUT"]),_=["QUEUED","PREPARING","RUNNING"];function m(e,t=null){if(null===e)return t;try{return JSON.parse(e)}catch{return t}}function f(e,t){if(!e||"object"!=typeof e||Array.isArray(e))throw Error(`${t} must be an object`);return e}function g(e){return Array.isArray(e)?e.filter(e=>"string"==typeof e):[]}function y(e){return null!==e.lastSeenAt&&Date.now()-e.lastSeenAt.getTime()<=(0,l.agentOnlineWindowMs)(e)&&null===e.disconnectedAt}function w(e){return g(m(e.capabilitiesJson,[]))}function b(e,t,r=80){let i=e.trim();if(!i)throw Error(`${t} is required`);if(i.length>r)throw Error(`${t} is too long`);return i}function E(e){return e.split(".").map(e=>Number.parseInt(e,10)||0)}function S(e,t){let r="string"==typeof t.minimumOSVersion?t.minimumOSVersion:null;if("SIMULATOR"!==e.type||!r||!e.osVersion)return e;let i=E(e.osVersion),a=E(r),n=Math.max(i.length,a.length);for(let t=0;t<n&&!((i[t]??0)>(a[t]??0));t+=1)if((i[t]??0)<(a[t]??0))return{...e,available:!1};return e}function v(e){if(e.codebaseId)return e.codebaseId;let t=m(e.snapshotJson,{});if(t&&"object"==typeof t&&!Array.isArray(t)){let e=t.codebase;if(e&&"object"==typeof e&&!Array.isArray(e)){let t=e.id;if("string"==typeof t&&t.trim())return t}}throw Error("Build coordination metadata is unavailable")}function I(e){return"SUCCEEDED"===e?"SUCCEEDED":"CANCELLED"===e?"CANCELLED":"FAILED"}let T={agent:!0,codebase:{include:{repository:!0}},worktree:{include:{_count:{select:{builds:{where:{status:{in:_}}}}}}},configuration:{include:{source:!0,project:!0}},artifacts:{orderBy:{createdAt:"asc"}},scriptExecutions:{orderBy:[{phase:"asc"},{position:"asc"}]},deployments:{orderBy:{createdAt:"desc"},include:{targetAgent:!0,transfer:{include:{sourceAgent:!0,targetAgent:!0}}}},exports:{orderBy:{createdAt:"desc"}}};class C{agentControl;telemetry;notifications;diskSpace;constructor(e,t,r,i){this.agentControl=e,this.telemetry=t,this.notifications=r,this.diskSpace=i,this.agentControl.registerCompletionHandler(n.IOS_BUILD_JOB_KIND,e=>this.projectBuildCompletion(e)),this.agentControl.registerCompletionHandler(n.IOS_DEPLOY_JOB_KIND,e=>this.projectDeploymentCompletion(e)),this.agentControl.registerCompletionHandler(n.IOS_REMOTE_DEPLOY_JOB_KIND,e=>this.projectDeploymentCompletion(e)),this.agentControl.registerCompletionHandler(n.IOS_ARTIFACT_TRANSFER_UPLOAD_JOB_KIND,async e=>{"SUCCEEDED"!==e.status&&await (0,h.failBuildArtifactTransferForJob)(e.id,e.error||"The build agent could not upload the runnable app")}),this.agentControl.registerCompletionHandler(n.IOS_EXPORT_JOB_KIND,e=>this.projectExportCompletion(e)),this.agentControl.registerCompletionHandler(n.IOS_TEST_RESULTS_JOB_KIND,e=>this.projectGeneratedReportCompletion(e)),this.agentControl.registerCompletionHandler(n.IOS_COVERAGE_REPORT_JOB_KIND,e=>this.projectGeneratedReportCompletion(e)),this.agentControl.registerCompletionHandler(s.COVERAGE_IMPORT_JOB_KIND,e=>this.importedCoverageCompletion(e))}publish(e){u.agentEventBus.publish((0,u.buildTopic)(e),{buildChanged:{id:e}}),u.agentEventBus.publish(u.BUILDS_CHANGED_TOPIC,{buildsChanged:{id:e}}),u.agentEventBus.publish(u.SIDEBAR_STATUS_CHANGED_TOPIC,{sidebarStatusChanged:!0})}async requireWorktree(e,t,r="Agent must be updated to use iOS builds"){let i=await (0,o.getPrismaClient)(),a=await i.worktree.findUnique({where:{id:e},include:{codebase:{include:{agent:!0,repository:!0}}}});if(!a||a.missingAt||"AVAILABLE"!==a.availability)throw Error("Worktree is unavailable");if(!y(a.codebase.agent))throw Error("Agent is offline");if(!w(a.codebase.agent).includes(t))throw Error(r);return a}identity(e){return{codebaseId:e.codebaseId,worktreeId:e.id,branch:e.branch,folder:e.folder,gitDirectory:e.gitDirectory,expectedOrigin:e.codebase.repository.canonicalOrigin,headSha:e.headSha,baseBranch:e.baseBranchOverride??e.codebase.defaultBranch??null}}async ensureProject(e){let t=await (0,o.getPrismaClient)(),r=await t.codebase.findUnique({where:{id:e},select:{repositoryId:!0}});if(!r)throw Error("Codebase not found");return t.codebaseProject.upsert({where:{repositoryId_type:{repositoryId:r.repositoryId,type:"IOS_APP"}},create:{id:(0,i.randomUUID)(),repositoryId:r.repositoryId,type:"IOS_APP"},update:{}})}async project(e){let t=await (0,o.getPrismaClient)(),r=await t.codebase.findUnique({where:{id:e},include:{repository:!0}});if(!r)return null;let i=await t.codebaseProject.findUnique({where:{repositoryId_type:{repositoryId:r.repositoryId,type:"IOS_APP"}},include:{configurations:{orderBy:{name:"asc"},include:{source:{include:{observations:{where:{codebaseId:e},orderBy:{lastParseAttemptAt:"desc"},take:1}}}}}}}),a=await t.codebaseRepositoryBuildScript.findMany({where:{repositoryId:r.repositoryId,script:{deletedAt:null}},orderBy:[{position:"asc"},{script:{name:"asc"}}],include:{script:!0}});return i?{...i,repository:r.repository,allowedScripts:a}:null}async createProject(e){return await this.ensureProject(e),this.project(e)}async projectForWorktree(e){let t=await (0,o.getPrismaClient)(),r=await t.worktree.findUnique({where:{id:e},select:{codebaseId:!0}});return r?this.project(r.codebaseId):null}async saveConfiguration(e){let t=await this.ensureProject(e.codebaseId),r=(0,n.parseBuildSource)({kind:e.sourceKind,relativePath:e.sourcePath}),a=b(e.name,"Configuration name"),s=b(e.scheme,"Scheme",256),l=b(e.buildConfiguration,"Xcode configuration",256);if(!n.BUILD_ACTIONS.includes(e.defaultAction))throw Error("Build action is invalid");let u=e.iconKey?.trim()||null;if(u&&!A.has(u))throw Error("Icon is invalid");let c=(0,n.parseBuildAdvancedSettings)(e.advancedSettings??n.DEFAULT_BUILD_ADVANCED_SETTINGS),d=!0===e.autoExport;if(d&&"ARCHIVE"!==e.defaultAction)throw Error("Auto Export is available only for Archive configurations");let h=e.exportSettings?(0,n.parseBuildExportSettings)(e.exportSettings):null;if(d&&!h)throw Error("Auto Export settings are required");let p=await (0,o.getPrismaClient)(),m=e.id?await p.buildConfiguration.findUnique({where:{id:e.id}}):null;if(e.id&&(!m||m.projectId!==t.id))throw Error("Build configuration not found");let f=await p.buildSource.upsert({where:{projectId_relativePath:{projectId:t.id,relativePath:r.relativePath}},create:{id:(0,i.randomUUID)(),projectId:t.id,kind:r.kind,relativePath:r.relativePath},update:{kind:r.kind}}),g=m?.id??(0,i.randomUUID)();return p.buildConfiguration.upsert({where:{id:g},create:{id:g,projectId:t.id,sourceId:f.id,name:a,iconKey:u,scheme:s,buildConfiguration:l,defaultAction:e.defaultAction,advancedSettingsJson:JSON.stringify(c),autoExport:d,exportSettingsJson:h?JSON.stringify(h):null},update:{sourceId:f.id,name:a,iconKey:u,scheme:s,buildConfiguration:l,defaultAction:e.defaultAction,advancedSettingsJson:JSON.stringify(c),autoExport:d,exportSettingsJson:h?JSON.stringify(h):null},include:{source:!0}})}async deleteConfiguration(e){let t=await (0,o.getPrismaClient)();if(await t.build.findFirst({where:{configurationId:e,status:{in:_}}}))throw Error("Configuration has an active build");let r=await t.buildConfiguration.deleteMany({where:{id:e}});return 1===r.count}async scripts(){return(await (0,o.getPrismaClient)()).buildScript.findMany({where:{deletedAt:null},orderBy:{name:"asc"}})}async saveScript(e){let t=b(e.name,"Script name"),r=e.preBuildScript?.trim()||null,a=e.postBuildScript?.trim()||null;if(!r&&!a)throw Error("A pre-build or post-build script is required");let s=e.timeoutSeconds??300;if(!Number.isInteger(s)||s<1||s>3600)throw Error("Script timeout must be between 1 and 3600 seconds");if(!n.BUILD_SCRIPT_FAILURE_BEHAVIORS.includes(e.failureBehavior))throw Error("Script failure behavior is invalid");let l=await (0,o.getPrismaClient)(),u=e.id??(0,i.randomUUID)();return l.buildScript.upsert({where:{id:u},create:{id:u,name:t,preBuildScript:r,postBuildScript:a,enabledByDefault:e.enabledByDefault,timeoutSeconds:s,failureBehavior:e.failureBehavior},update:{name:t,preBuildScript:r,postBuildScript:a,enabledByDefault:e.enabledByDefault,timeoutSeconds:s,failureBehavior:e.failureBehavior,deletedAt:null}})}async deleteScript(e){let t=await (0,o.getPrismaClient)(),r=await t.buildScript.updateMany({where:{id:e,deletedAt:null},data:{deletedAt:new Date}});return await t.codebaseRepositoryBuildScript.deleteMany({where:{scriptId:e}}),1===r.count}async setAllowedScripts(e,t){let r=await (0,o.getPrismaClient)(),i=await r.codebase.findUnique({where:{id:e}});if(!i)throw Error("Codebase not found");let a=[...new Set(t)];if((await r.buildScript.findMany({where:{id:{in:a},deletedAt:null}})).length!==a.length)throw Error("Build script not found");return await r.$transaction(async e=>{await e.codebaseRepositoryBuildScript.deleteMany({where:{repositoryId:i.repositoryId}}),a.length&&await e.codebaseRepositoryBuildScript.createMany({data:a.map((e,t)=>({repositoryId:i.repositoryId,scriptId:e,position:t}))})}),this.project(e)}async waitForJob(e,t=12e4){let r=u.agentEventBus.iterate((0,u.agentJobChangedTopic)(e)),i=Date.now()+t;try{for(;Date.now()<i;){let t=await this.agentControl.getJob(e);if(!t)throw Error("Agent job disappeared");if(k.has(t.status))return t;await Promise.race([r.next(),new Promise(e=>setTimeout(e,Math.max(1,i-Date.now())))])}throw await this.agentControl.cancelJob(e),Error("Agent did not respond in time")}finally{await r.return?.()}}result(e){if("SUCCEEDED"!==e.status)throw Error(e.error||"Agent operation failed");return f(m(e.resultJson,{}),"agent result")}async discoverSources(e,t){let r=await this.requireWorktree(e,n.IOS_SOURCE_DISCOVER_JOB_KIND),i=await this.agentControl.createJob({agentId:r.codebase.agentId,codebaseId:r.codebaseId,worktreeId:r.id,kind:n.IOS_SOURCE_DISCOVER_JOB_KIND,payload:this.identity(r),idempotencyKey:`ios:source:discover:${t}:${r.id}`,timeoutSeconds:60,visibility:"SYSTEM"});try{let e=this.result(await this.waitForJob(i.id));return Array.isArray(e.sources)?e.sources:[]}finally{let e=await (0,o.getPrismaClient)();await e.agentJob.deleteMany({where:{id:i.id,visibility:"SYSTEM"}})}}async reparse(e,t,r){let a=await this.requireWorktree(t,n.IOS_SOURCE_PARSE_JOB_KIND),s=await (0,o.getPrismaClient)(),l=await s.buildConfiguration.findUnique({where:{id:e},include:{source:{include:{project:!0}}}});if(!l||l.source.project.repositoryId!==a.codebase.repositoryId)throw Error("Build configuration is not available for this worktree");let u=`worktree:${a.id}`,c=await s.buildSourceObservation.findUnique({where:{sourceId_scopeKey:{sourceId:l.sourceId,scopeKey:u}}}),d=new Date;await s.buildSourceObservation.upsert({where:{sourceId_scopeKey:{sourceId:l.sourceId,scopeKey:u}},create:{id:(0,i.randomUUID)(),sourceId:l.sourceId,scopeKey:u,codebaseId:a.codebaseId,worktreeId:a.id,status:"PARSING",lastParseAttemptAt:d},update:{status:"PARSING",error:null,lastParseAttemptAt:d}});let h=await this.agentControl.createJob({agentId:a.codebase.agentId,codebaseId:a.codebaseId,worktreeId:a.id,kind:n.IOS_SOURCE_PARSE_JOB_KIND,payload:{...this.identity(a),source:{kind:l.source.kind,relativePath:l.source.relativePath},scheme:l.scheme},idempotencyKey:`ios:source:parse:${r}:${l.id}:${a.id}`,timeoutSeconds:120,visibility:"SYSTEM"});try{let e=this.result(await this.waitForJob(h.id)),t=g(e.schemes),r=g(e.configurations),i=t.includes(l.scheme)&&r.includes(l.buildConfiguration);return s.buildSourceObservation.update({where:{sourceId_scopeKey:{sourceId:l.sourceId,scopeKey:u}},data:{status:i?"VALID":"INVALID",schemesJson:JSON.stringify(t),configurationsJson:JSON.stringify(r),testPlansJson:JSON.stringify(g(e.testPlans)),error:i?null:"The saved scheme or configuration is no longer available",stale:!1,headSha:"string"==typeof e.headSha?e.headSha:a.headSha,xcodeVersion:"string"==typeof e.xcodeVersion?e.xcodeVersion:null,lastParsedAt:new Date}})}catch(t){let e=t instanceof Error?t.message:String(t);return s.buildSourceObservation.update({where:{sourceId_scopeKey:{sourceId:l.sourceId,scopeKey:u}},data:{status:"ERROR",error:e,stale:!!c?.lastParsedAt}})}finally{await s.agentJob.deleteMany({where:{id:h.id,visibility:"SYSTEM"}})}}async inspectSource(e){let t=await this.requireWorktree(e.worktreeId,n.IOS_SOURCE_PARSE_JOB_KIND),r=(0,n.parseBuildSource)({kind:e.sourceKind,relativePath:e.sourcePath}),i=await this.agentControl.createJob({agentId:t.codebase.agentId,codebaseId:t.codebaseId,worktreeId:t.id,kind:n.IOS_SOURCE_PARSE_JOB_KIND,payload:{...this.identity(t),source:r,scheme:e.scheme?.trim()||null,configuration:e.configuration?.trim()||null},idempotencyKey:`ios:source:inspect:${e.requestId}:${t.id}:${r.relativePath}:${e.scheme??""}:${e.configuration??""}`,timeoutSeconds:120,visibility:"SYSTEM"});try{var a;let e=this.result(await this.waitForJob(i.id));return{source:r,schemes:g(e.schemes),configurations:g(e.configurations),testPlans:g(e.testPlans),signingRequirements:(a=e.signingRequirements,Array.isArray(a)?a.flatMap(e=>!e||"object"!=typeof e||Array.isArray(e)||"string"!=typeof e.bundleId||"string"!=typeof e.name||"string"!=typeof e.target?[]:[{bundleId:e.bundleId,name:e.name,target:e.target,platform:"string"==typeof e.platform?e.platform:null,teamId:"string"==typeof e.teamId?e.teamId:null,provisioningProfileSpecifier:"string"==typeof e.provisioningProfileSpecifier?e.provisioningProfileSpecifier:null}]):[]),headSha:"string"==typeof e.headSha?e.headSha:t.headSha,xcodeVersion:"string"==typeof e.xcodeVersion?e.xcodeVersion:null}}finally{let e=await (0,o.getPrismaClient)();await e.agentJob.deleteMany({where:{id:i.id,visibility:"SYSTEM"}})}}async destinations(e){let t=await this.requireWorktree(e.worktreeId,n.IOS_DESTINATIONS_JOB_KIND),r=await (0,o.getPrismaClient)(),i=await r.buildConfiguration.findUnique({where:{id:e.configurationId},include:{source:{include:{project:!0}}}});if(!i||i.source.project.repositoryId!==t.codebase.repositoryId)throw Error("Build configuration is not available for this worktree");let a=e.action??i.defaultAction;if(!n.BUILD_ACTIONS.includes(a))throw Error("Build action is invalid");let s=(0,n.genericBuildDestinations)(a);if("ARCHIVE"===a)return s;let l=await this.agentControl.createJob({agentId:t.codebase.agentId,codebaseId:t.codebaseId,worktreeId:t.id,kind:n.IOS_DESTINATIONS_JOB_KIND,payload:{...this.identity(t),source:{kind:i.source.kind,relativePath:i.source.relativePath},scheme:i.scheme,configuration:i.buildConfiguration,action:a},idempotencyKey:`ios:destinations:${e.requestId}:${i.id}:${t.id}:${a}`,timeoutSeconds:120,visibility:"SYSTEM"});try{let e=this.result(await this.waitForJob(l.id));return(Array.isArray(e.destinations)?e.destinations:[]).map(e=>(0,n.parseBuildDestination)(e)).filter(e=>!1!==e.available)}finally{await r.agentJob.deleteMany({where:{id:l.id,visibility:"SYSTEM"}})}}async signingOptionsForBuild(e){let t=await (0,o.getPrismaClient)(),r=await t.build.findUnique({where:{id:e},include:{artifacts:!0}}),i=r?.artifacts.find(e=>"ARCHIVE"===e.kind);if(!r||"SUCCEEDED"!==r.status||!r.worktreeId)throw Error("A successful archive build is required");if(!i)throw Error("Build does not contain an archive");let a=await this.requireWorktree(r.worktreeId,n.IOS_SIGNING_INSPECT_JOB_KIND),s=await this.agentControl.createJob({agentId:a.codebase.agentId,codebaseId:a.codebaseId,worktreeId:a.id,kind:n.IOS_SIGNING_INSPECT_JOB_KIND,payload:{buildId:r.id,codebaseId:a.codebaseId,artifactDirectory:r.artifactDirectory,archiveRelativePath:i.relativePath},idempotencyKey:`ios:signing:${r.id}:${i.id}`,timeoutSeconds:120,visibility:"SYSTEM"});try{let e=this.result(await this.waitForJob(s.id));return{teams:Array.isArray(e.teams)?e.teams:[],identities:Array.isArray(e.identities)?e.identities:[],profiles:Array.isArray(e.profiles)?e.profiles:[],bundles:Array.isArray(e.bundles)?e.bundles:[]}}finally{await t.agentJob.deleteMany({where:{id:s.id,visibility:"SYSTEM"}})}}async runAgentsForBuild(e){let t=await (0,o.getPrismaClient)(),r=await t.build.findUnique({where:{id:e},include:{artifacts:!0,agent:!0,worktree:!0}}),i=r?.artifacts.find(e=>"RUNNABLE_APP"===e.kind);if(!r||"SUCCEEDED"!==r.status||!i||!r.agentId)throw Error("A successful runnable build is required");let a=f(m(i.metadataJson,{}),"runnable metadata"),s=new Set(g(a.architectures).map(e=>"x64"===e?"x86_64":e)),l=await (0,d.cachedArtifact)(r.id,i.id),u=r.agent?w(r.agent):[];return(await t.agent.findMany({orderBy:{name:"asc"}})).map(e=>{let t=e.id===r.agentId,i=null;return e.osVersion.toLocaleLowerCase().startsWith("macos")?y(e)?t?w(e).includes(n.IOS_RUN_DESTINATIONS_JOB_KIND)&&w(e).includes(n.IOS_DEPLOY_JOB_KIND)||(i="AGENT_UPDATE_REQUIRED"):w(e).includes(n.IOS_AGENT_RUN_DESTINATIONS_JOB_KIND)&&w(e).includes(n.IOS_REMOTE_DEPLOY_JOB_KIND)?l||r.agent&&y(r.agent)&&u.includes(n.IOS_ARTIFACT_TRANSFER_UPLOAD_JOB_KIND)?"SIMULATOR"===r.destinationType&&s.size>0&&!s.has("x64"===e.architecture?"x86_64":e.architecture)&&(i="INCOMPATIBLE_ARCHITECTURE"):i="BUILD_AGENT_UNAVAILABLE":i="AGENT_UPDATE_REQUIRED":i="OFFLINE":i="NOT_MACOS",{agent:e,isBuildAgent:t,available:null===i,unavailableReason:i}}).sort((e,t)=>Number(t.isBuildAgent)-Number(e.isBuildAgent)||e.agent.name.localeCompare(t.agent.name))}async destinationsForBuild(e,t,r){let i=await (0,o.getPrismaClient)(),a=await i.build.findUnique({where:{id:e},include:{artifacts:!0}});if(!a||"SUCCEEDED"!==a.status||!a.artifacts.some(e=>"RUNNABLE_APP"===e.kind))throw Error("A successful runnable build is required");let s=a.artifacts.find(e=>"RUNNABLE_APP"===e.kind),l=f(m(s.metadataJson,{}),"runnable metadata"),u=r??a.agentId;if(!u)throw Error("Build agent is unavailable");if(u!==a.agentId){let e=(await this.runAgentsForBuild(a.id)).find(e=>e.agent.id===u);if(!e?.available)throw Error("The selected run agent is unavailable");let r=await this.agentControl.createJob({agentId:u,kind:n.IOS_AGENT_RUN_DESTINATIONS_JOB_KIND,payload:{destinationType:a.destinationType},idempotencyKey:`ios:agent-build-destinations:${b(t,"Request ID",200)}:${a.id}:${u}`,timeoutSeconds:120,visibility:"SYSTEM"});try{let e=this.result(await this.waitForJob(r.id));return(Array.isArray(e.destinations)?e.destinations:[]).map(e=>(0,n.parseBuildDestination)(e)).map(e=>S(e,l)).filter(e=>e.type===a.destinationType&&!e.generic)}finally{await i.agentJob.deleteMany({where:{id:r.id,visibility:"SYSTEM"}})}}if(!a.worktreeId)throw Error("The build worktree is unavailable");let c=await this.requireWorktree(a.worktreeId,n.IOS_RUN_DESTINATIONS_JOB_KIND);if(a.agentId!==c.codebase.agentId||a.codebaseId!==c.codebaseId)throw Error("The build no longer belongs to this worktree checkout");let d=await this.agentControl.createJob({agentId:c.codebase.agentId,codebaseId:c.codebaseId,worktreeId:c.id,kind:n.IOS_RUN_DESTINATIONS_JOB_KIND,payload:{...this.identity(c),destinationType:a.destinationType},idempotencyKey:`ios:build-destinations:${b(t,"Request ID",200)}:${a.id}`,timeoutSeconds:120,visibility:"SYSTEM"});try{let e=this.result(await this.waitForJob(d.id));return(Array.isArray(e.destinations)?e.destinations:[]).map(e=>(0,n.parseBuildDestination)(e)).map(e=>S(e,l)).filter(e=>e.type===a.destinationType&&!e.generic)}finally{await i.agentJob.deleteMany({where:{id:d.id,visibility:"SYSTEM"}})}}async startBuild(e){let t=b(e.requestId,"Request ID",200),r=`${e.worktreeId}:${t}`,s=await (0,o.getPrismaClient)(),l=await s.build.findUnique({where:{requestKey:r},include:T});if(l){if(this.telemetry){let e=m(l.snapshotJson,{}),t=f(e.configuration??{},"build configuration snapshot"),r=f(e.destination??{},"build destination snapshot");await this.telemetry.addBuildSeparator({buildId:l.id,name:`Build \xb7 ${String(t.name??"iOS")} \xb7 ${String(r.name??"Destination")}`,clientTime:l.createdAt})}return l}let u=await this.requireWorktree(e.worktreeId,n.IOS_BUILD_JOB_KIND);if(await this.diskSpace?.assertWorktreeCanStart(u.id),e.worktreeCoverage&&!w(u.codebase.agent).includes(n.IOS_COVERAGE_REPORT_JOB_KIND))throw Error("Build agent must be updated for worktree coverage");let d=await s.buildConfiguration.findUnique({where:{id:e.configurationId},include:{source:{include:{project:!0}}}});if(!d||d.source.project.repositoryId!==u.codebase.repositoryId)throw Error("Build configuration is not available for this worktree");let h=await s.buildSourceObservation.findUnique({where:{sourceId_scopeKey:{sourceId:d.sourceId,scopeKey:`worktree:${u.id}`}}}),p=e.action??d.defaultAction;if(!n.BUILD_ACTIONS.includes(p))throw Error("Build action is invalid");if(e.exportWhenComplete&&"ARCHIVE"!==p)throw Error("Export when complete is available only for Archive builds");let g="ARCHIVE"===p&&(e.exportWhenComplete??d.autoExport),y=e.exportSettings??m(d.exportSettingsJson,null),E=g||y?(0,n.parseBuildExportSettings)(y):null;if(g&&!E)throw Error("Export settings are required when automatic export is enabled");let S=(0,n.parseBuildDestination)(e.destination);if(!n.BUILD_DESTINATION_TYPES.includes(S.type))throw Error("Destination is invalid");if("ARCHIVE"===p&&("PHYSICAL_DEVICE"!==S.type||!S.generic))throw Error("Archive builds require the generic physical iOS destination");if(S.generic&&!n.GENERIC_BUILD_DESTINATION_ACTIONS.includes(p))throw Error("This build action requires a concrete destination");let v=f(m(d.advancedSettingsJson,{}),"saved advanced settings"),I=e.advancedSettings?f(e.advancedSettings,"advanced settings override"):{},A=(0,n.parseBuildAdvancedSettings)({...v,...I,buildSettingOverrides:{...f(v.buildSettingOverrides??{},"saved overrides"),...f(I.buildSettingOverrides??{},"run overrides")}});if("TEST_WITHOUT_BUILDING"===p){if(!A.priorBuildForTestingId)throw Error("Test Without Building requires a prior Build for Testing result");let e=await s.build.findUnique({where:{id:A.priorBuildForTestingId},include:{artifacts:{where:{kind:{in:["TEST_PRODUCTS","XCTESTRUN"]}},orderBy:{createdAt:"asc"}}}});if(!e||"SUCCEEDED"!==e.status||"BUILD_FOR_TESTING"!==e.action)throw Error("Test Without Building requires a successful Build for Testing result");if(e.agentId!==u.codebase.agentId||e.worktreeId!==u.id||e.configurationId!==d.id)throw Error("The prior Build for Testing result is not compatible with this agent, worktree, and configuration");if(e.destinationType!==S.type)throw Error("The prior Build for Testing result uses a different destination type");let t=f(m(e.snapshotJson,{}),"prior Build for Testing snapshot"),r=f(t.configuration??{},"prior Build for Testing configuration snapshot"),i=(0,n.parseBuildAdvancedSettings)(r.advancedSettings??{});if(A.testPlan&&i.testPlan&&A.testPlan!==i.testPlan)throw Error("The selected test plan does not match the prior Build for Testing result");let o=A.testPlan??i.testPlan??null,l=e.artifacts.filter(e=>"TEST_PRODUCTS"===e.kind&&e.relativePath.endsWith(".xctestproducts")),c=e.artifacts.filter(e=>"XCTESTRUN"===e.kind&&e.relativePath.endsWith(".xctestrun"));if(l.length>1)throw Error("The prior Build for Testing result contains multiple test-products artifacts");let h=l[0];if(h||1!==c.length||(h=c[0]),!h&&c.length>1&&o&&(h=c.find(e=>f(m(e.metadataJson,{}),"test-run artifact metadata").testPlan===o||e.relativePath.endsWith(`/${o}.xctestrun`)||e.relativePath===`${o}.xctestrun`)),!h&&c.length>1)throw Error("Select a test plan to choose among the captured .xctestrun artifacts");let p=h?.relativePath??"test-products.xctestproducts",g=(0,a.resolve)(e.artifactDirectory),y=(0,a.resolve)(g,p),w=(0,a.relative)(g,y);if(!w||w.startsWith("..")||(0,a.isAbsolute)(w))throw Error("The prior Build for Testing artifact path is invalid");A={...A,testPlan:o,priorTestProductsPath:p.endsWith(".xctestproducts")?y:null,priorXctestrunPath:p.endsWith(".xctestrun")?y:null}}let k=await s.codebaseRepositoryBuildScript.findMany({where:{repositoryId:u.codebase.repositoryId,script:{deletedAt:null}},orderBy:[{position:"asc"},{script:{name:"asc"}}],include:{script:!0}}),_=new Set(e.scriptIds??[]);if([..._].some(e=>!k.some(t=>t.scriptId===e)))throw Error("A selected build script is not allowed for this codebase");let C=k.filter(e=>_.has(e.scriptId)),R=(0,i.randomUUID)(),N=(0,c.effectiveBuildsDirectory)(u.codebase.agent);if(!N)throw Error("The agent builds directory is unavailable");let O=(0,a.join)(N,R),D={kind:d.source.kind,relativePath:d.source.relativePath},P=function(e){var t;let r=e.advancedSettings,i="TEST_WITHOUT_BUILDING"===e.action,n=["xcodebuild",...i?[]:[..."PACKAGE"===e.source.kind?[]:"PROJECT"===e.source.kind?["-project",e.source.relativePath]:["-workspace",e.source.relativePath],"-scheme",e.scheme,"-configuration",e.configuration],"-destination",(t=e.destination).generic?"SIMULATOR"===t.type?"generic/platform=iOS Simulator":"generic/platform=iOS":"SIMULATOR"===t.type?`platform=iOS Simulator,id=${t.id}`:`platform=iOS,id=${t.id}`,"-hideShellScriptEnvironment","-resultBundlePath",(0,a.join)(e.artifactDirectory,"result.xcresult")];for(let e of(!i&&("RESOLVED_ONLY"===r.packageResolution?n.push("-onlyUsePackageVersionsFromResolvedFile"):"SKIP_UPDATES"===r.packageResolution?n.push("-skipPackageUpdates"):"DISABLE_AUTOMATIC"===r.packageResolution&&n.push("-disableAutomaticPackageResolution"),r.disablePackageRepositoryCache&&n.push("-disablePackageRepositoryCache"),"PROJECT_DEFAULT"!==r.signingStyle&&n.push(`CODE_SIGN_STYLE=${"AUTOMATIC"===r.signingStyle?"Automatic":"Manual"}`),r.developmentTeam&&n.push(`DEVELOPMENT_TEAM=${r.developmentTeam}`),r.codeSignIdentity&&n.push(`CODE_SIGN_IDENTITY=${r.codeSignIdentity}`),r.provisioningProfileSpecifier&&n.push(`PROVISIONING_PROFILE_SPECIFIER=${r.provisioningProfileSpecifier}`),r.productBundleIdentifier&&n.push(`PRODUCT_BUNDLE_IDENTIFIER=${r.productBundleIdentifier}`),r.allowProvisioningUpdates&&n.push("-allowProvisioningUpdates"),r.allowProvisioningDeviceRegistration&&n.push("-allowProvisioningDeviceRegistration")),r.testPlan&&n.push("-testPlan",r.testPlan),r.codeCoverage&&n.push("-enableCodeCoverage","YES"),null!==r.parallelTesting&&n.push("-parallel-testing-enabled",r.parallelTesting?"YES":"NO"),null!==r.parallelTestingWorkers&&n.push("-parallel-testing-worker-count",String(r.parallelTestingWorkers)),r.onlyTesting))n.push(`-only-testing:${e}`);for(let e of r.skipTesting)n.push(`-skip-testing:${e}`);if(!i)for(let[e,t]of Object.entries(r.buildSettingOverrides))n.push(`${e}=${t}`);"ARCHIVE"===e.action&&n.push("-archivePath",(0,a.join)(e.artifactDirectory,"archive.xcarchive")),"BUILD_FOR_TESTING"===e.action&&n.push("-testProductsPath",(0,a.join)(e.artifactDirectory,"test-products.xctestproducts")),"TEST_WITHOUT_BUILDING"===e.action&&r.priorTestProductsPath&&n.push("-testProductsPath",r.priorTestProductsPath),"TEST_WITHOUT_BUILDING"===e.action&&!r.priorTestProductsPath&&r.priorXctestrunPath&&n.push("-xctestrun",r.priorXctestrunPath),n.push({BUILD:"build",TEST:"test",ANALYZE:"analyze",ARCHIVE:"archive",BUILD_FOR_TESTING:"build-for-testing",TEST_WITHOUT_BUILDING:"test-without-building"}[e.action]);let s=n.map(e=>/^[A-Za-z0-9_./:=,-]+$/.test(e)?e:JSON.stringify(e)).join(" ");return`cd ${JSON.stringify(e.folder)} && xcrun ${s}`}({folder:u.folder,source:D,scheme:d.scheme,configuration:d.buildConfiguration,destination:S,action:p,advancedSettings:A,artifactDirectory:O}),x=C.map(({script:e,position:t})=>({id:e.id,name:e.name,preBuildScript:e.preBuildScript,postBuildScript:e.postBuildScript,timeoutSeconds:e.timeoutSeconds,failureBehavior:e.failureBehavior,position:t})),L=await this.telemetry?.buildSettings(S.type,{requestOrigin:e.telemetryRequestOrigin}),U={repository:{id:u.codebase.repository.id,name:u.codebase.repository.name,canonicalOrigin:u.codebase.repository.canonicalOrigin},codebase:{id:u.codebase.id,folder:u.codebase.folder},worktree:{id:u.id,folder:u.folder,branch:u.branch,headSha:u.headSha,codeStateHash:u.codeStateHash,hasStagedChanges:u.hasStagedChanges,hasUnstagedChanges:u.hasUnstagedChanges},agent:{id:u.codebase.agent.id,name:u.codebase.agent.name,hostname:u.codebase.agent.hostname},configuration:{id:d.id,name:d.name,iconKey:d.iconKey,source:D,scheme:d.scheme,buildConfiguration:d.buildConfiguration,action:p,advancedSettings:A,autoExport:g,exportSettings:E,parse:h?{status:h.status,schemes:m(h.schemesJson,[]),configurations:m(h.configurationsJson,[]),testPlans:m(h.testPlansJson,[]),headSha:h.headSha,xcodeVersion:h.xcodeVersion,parsedAt:h.lastParsedAt?.toISOString()??null}:{status:"UNPARSED",schemes:[],configurations:[],testPlans:[],headSha:null,xcodeVersion:null,parsedAt:null}},destination:S,scripts:x,...L?{telemetry:L}:{},worktreeCoverage:!0===e.worktreeCoverage},B=new Date,M=s.build.create({data:{id:R,requestKey:r,requestId:t,agentId:u.codebase.agentId,codebaseId:u.codebaseId,worktreeId:u.id,repositoryId:u.codebase.repository.id,configurationId:d.id,status:"QUEUED",action:p,destinationType:S.type,destinationJson:JSON.stringify(S),snapshotJson:JSON.stringify(U),commandSummary:P,artifactDirectory:O,createdAt:B,scriptExecutions:{create:x.flatMap(e=>[...e.preBuildScript?[{id:(0,i.randomUUID)(),scriptId:e.id,phase:"PRE_BUILD",position:e.position,nameSnapshot:e.name,sourceSnapshot:e.preBuildScript,timeoutSeconds:e.timeoutSeconds,failureBehavior:e.failureBehavior}]:[],...e.postBuildScript?[{id:(0,i.randomUUID)(),scriptId:e.id,phase:"POST_BUILD",position:e.position,nameSnapshot:e.name,sourceSnapshot:e.postBuildScript,timeoutSeconds:e.timeoutSeconds,failureBehavior:e.failureBehavior}]:[]])}}});if(this.telemetry){let e=(0,i.randomUUID)();await s.$transaction([M,s.telemetryEntry.create({data:{id:e,entryType:"SEPARATOR",clientTime:B,receivedAt:B,separatorKind:"BUILD",separatorName:`Build \xb7 ${d.name} \xb7 ${S.name}`.slice(0,100),buildId:R}})]),this.telemetry.notifyChange([e],"BUILD_SEPARATOR_ADDED")}else await M;try{let r=await this.agentControl.createJob({agentId:u.codebase.agentId,codebaseId:u.codebaseId,worktreeId:u.id,kind:n.IOS_BUILD_JOB_KIND,payload:{...this.identity(u),buildId:R,artifactDirectory:O,source:D,scheme:d.scheme,configuration:d.buildConfiguration,action:p,destination:S,advancedSettings:A,scripts:x,...L?{telemetry:L}:{},worktreeCoverage:!0===e.worktreeCoverage},idempotencyKey:`ios:build:${t}:${u.id}`,timeoutSeconds:604800});await s.build.update({where:{id:R},data:{jobId:r.id}})}catch(e){throw await s.build.update({where:{id:R},data:{status:"FAILED",errorCode:"QUEUE_FAILED",error:e instanceof Error?e.message:String(e),finishedAt:new Date}}),e}return this.publish(R),s.build.findUniqueOrThrow({where:{id:R},include:T})}async rebuildBuild(e,t,r){let i=await (0,o.getPrismaClient)(),a=await i.build.findUnique({where:{id:e},select:{worktreeId:!0,configurationId:!0,destinationJson:!0,action:!0,snapshotJson:!0}});if(!a)throw Error("Build not found");let n=f(m(a.snapshotJson,{}),"build snapshot"),s=f(n.worktree??{},"build worktree snapshot"),l=f(n.configuration??{},"build configuration snapshot"),u=Array.isArray(n.scripts)?n.scripts:[],c=a.worktreeId??("string"==typeof s.id?s.id:null),d=a.configurationId??("string"==typeof l.id?l.id:null);if(!c||!d)throw Error("The original build settings are unavailable");return this.startBuild({worktreeId:c,configurationId:d,destination:m(a.destinationJson,{}),scriptIds:u.flatMap(e=>{if(!e||"object"!=typeof e||Array.isArray(e))return[];let t=e.id;return"string"==typeof t?[t]:[]}),action:a.action,advancedSettings:l.advancedSettings,exportWhenComplete:!0===l.autoExport,...Object.hasOwn(l,"exportSettings")?{exportSettings:l.exportSettings}:{},requestId:t,...r?{telemetryRequestOrigin:r}:{}})}async startWorktreeCoverage(e){let t=await (0,o.getPrismaClient)(),r=await t.worktree.findUnique({where:{id:e.worktreeId},select:{baseBranchOverride:!0,codebase:{select:{defaultBranch:!0}}}});if(!r||!(r.baseBranchOverride??r.codebase.defaultBranch))throw Error("A base branch is required for worktree coverage");let i=f(e.advancedSettings??{},"coverage advanced settings");return this.startBuild({...e,action:"TEST",advancedSettings:{...i,codeCoverage:!0,parseTestResults:!0},worktreeCoverage:!0})}async importCoverageReport(e){let t=await (0,o.getPrismaClient)(),r=await this.requireWorktree(e.worktreeId,s.COVERAGE_IMPORT_JOB_KIND,"Agent must be updated to import coverage reports"),n=r.baseBranchOverride??r.codebase.defaultBranch??null,l=(e.format||"AUTO").toUpperCase();if(!s.COVERAGE_REPORT_FORMATS.includes(l))throw Error("Coverage format must be AUTO, LCOV, or ISTANBUL");let u=b(e.buildName??"Coverage report","Build name",200),d=b(e.reportPath,"Coverage file",4e3),h=b(e.requestId,"Request ID",200),p=`coverage:${e.worktreeId}:${h}`,m=await t.build.findUnique({where:{requestKey:p}});if(m)return m;let f=(0,i.randomUUID)(),g=(0,c.effectiveBuildsDirectory)(r.codebase.agent);if(!g)throw Error("The agent builds directory is unavailable");let y={repository:{id:r.codebase.repository.id,name:r.codebase.repository.name,canonicalOrigin:r.codebase.repository.canonicalOrigin},codebase:{id:r.codebase.id,folder:r.codebase.folder},worktree:{id:r.id,folder:r.folder,branch:r.branch,headSha:r.headSha,codeStateHash:r.codeStateHash,hasStagedChanges:r.hasStagedChanges,hasUnstagedChanges:r.hasUnstagedChanges},agent:{id:r.codebase.agent.id,name:r.codebase.agent.name,hostname:r.codebase.agent.hostname},configuration:{name:u},coverageImport:{reportPath:d,format:l,baseBranch:n},worktreeCoverage:!0},w={type:"HOST",id:r.codebase.agent.id,name:r.codebase.agent.name,platform:r.codebase.agent.architecture,osVersion:r.codebase.agent.osVersion||null,state:"Connected"},E=await t.build.create({data:{id:f,requestKey:p,requestId:h,agentId:r.codebase.agentId,codebaseId:r.codebaseId,worktreeId:r.id,repositoryId:r.codebase.repository.id,status:"RUNNING",action:"TEST",destinationType:"HOST",destinationJson:JSON.stringify(w),snapshotJson:JSON.stringify(y),commandSummary:`Import coverage from ${d}`,artifactDirectory:(0,a.join)(g,f),startedAt:new Date}}),S=null;try{await t.buildReport.create({data:{id:(0,i.randomUUID)(),buildId:f,kind:"CODE_COVERAGE",source:"WORKTREE",status:"PENDING"}}),this.publish(f);let e=await this.agentControl.createJob({agentId:r.codebase.agentId,codebaseId:r.codebaseId,worktreeId:r.id,kind:s.COVERAGE_IMPORT_JOB_KIND,payload:{buildId:f,codebaseId:r.codebaseId,worktreeId:r.id,folder:r.folder,reportPath:d,format:l,baseBranch:n},idempotencyKey:`coverage:import:${h}:${f}`,timeoutSeconds:300,visibility:"SYSTEM"});return S=e.id,await t.build.update({where:{id:f},data:{jobId:e.id}}),{...E,jobId:e.id}}catch(a){S&&await this.agentControl.cancelJob(S).catch(()=>void 0);let e=a instanceof Error?a.message:String(a),r=new Date;throw await t.$transaction(async t=>{await t.buildReport.upsert({where:{buildId_kind:{buildId:f,kind:"CODE_COVERAGE"}},create:{id:(0,i.randomUUID)(),buildId:f,kind:"CODE_COVERAGE",source:"WORKTREE",status:"FAILED",error:e,finishedAt:r},update:{status:"FAILED",error:e,finishedAt:r}}),await t.build.update({where:{id:f},data:{status:"FAILED",errorCode:"QUEUE_FAILED",error:e,finishedAt:r}})}),this.publish(f),a}}async importedCoverageCompletion(e){let t=f(m(e.payloadJson,{}),"coverage import payload");if("string"!=typeof t.buildId)return;let r=t.buildId,a=f(m(e.resultJson,{}),"coverage import result"),n="SUCCEEDED"===e.status&&!!a.report&&"object"==typeof a.report,s=await (0,o.getPrismaClient)();await s.$transaction(async t=>{n?await this.upsertReportProjection(t,r,a.report,"WORKTREE"):await t.buildReport.upsert({where:{buildId_kind:{buildId:r,kind:"CODE_COVERAGE"}},create:{id:(0,i.randomUUID)(),buildId:r,kind:"CODE_COVERAGE",source:"WORKTREE",status:"FAILED",error:e.error||"Coverage import failed",finishedAt:new Date},update:{status:"FAILED",error:e.error||"Coverage import failed",finishedAt:new Date}}),await t.build.update({where:{id:r},data:{status:n?"SUCCEEDED":"FAILED",error:n?null:e.error||"Coverage import failed",finishedAt:new Date}})}),this.publish(r)}async generateReport(e,t,r){let a=await (0,o.getPrismaClient)(),s=await a.buildReport.findUnique({where:{buildId_kind:{buildId:e,kind:t}},include:{artifact:!0}});if(s?.status==="READY")return s;let l=await a.build.findUnique({where:{id:e},include:{agent:!0,artifacts:!0}});if(!l)throw Error("Build not found");if(_.includes(l.status))throw Error("Wait for the build to finish before generating reports");if(!l.agentId||!l.agent||!y(l.agent))throw Error("Build agent is offline");let u="TEST_RESULTS"===t?n.IOS_TEST_RESULTS_JOB_KIND:n.IOS_COVERAGE_REPORT_JOB_KIND;if(!w(l.agent).includes(u))throw Error("Build agent must be updated to generate reports");if(!l.artifacts.some(e=>"RESULT_BUNDLE"===e.kind))throw Error("The build result bundle is unavailable");if("TEST_RESULTS"===t&&!["TEST","TEST_WITHOUT_BUILDING"].includes(l.action))throw Error("This build did not run tests");let c=await a.buildReport.upsert({where:{buildId_kind:{buildId:e,kind:t}},create:{id:(0,i.randomUUID)(),buildId:e,kind:t,source:"MANUAL",status:"PENDING"},update:{source:"MANUAL",status:"PENDING",error:null,finishedAt:null}});this.publish(e);let d=v(l),h=await this.agentControl.createJob({agentId:l.agentId,codebaseId:d,worktreeId:l.worktreeId,kind:u,payload:{buildId:e,artifactDirectory:l.artifactDirectory,codebaseId:d,reportKind:t,source:"MANUAL"},idempotencyKey:`ios:report:${t}:${b(r,"Request ID",200)}:${e}`,timeoutSeconds:180,visibility:"SYSTEM"});try{return await this.waitForJob(h.id,17e4),a.buildReport.findUniqueOrThrow({where:{id:c.id},include:{artifact:!0}})}finally{await a.agentJob.deleteMany({where:{id:h.id,visibility:"SYSTEM"}})}}async coverageHistory(e){return(await (0,o.getPrismaClient)()).buildReport.findMany({where:{kind:"CODE_COVERAGE",source:"WORKTREE",build:{worktreeId:e}},orderBy:{createdAt:"desc"},take:50,select:{id:!0,buildId:!0,artifactId:!0,kind:!0,source:!0,status:!0,summaryJson:!0,error:!0,createdAt:!0,updatedAt:!0,finishedAt:!0,artifact:!0,build:{select:{id:!0,status:!0,action:!0,destinationType:!0,destinationJson:!0,snapshotJson:!0,createdAt:!0,startedAt:!0,finishedAt:!0,updatedAt:!0,worktree:{select:{headSha:!0,codeStateHash:!0,hasStagedChanges:!0,hasUnstagedChanges:!0,lastCheckedAt:!0,_count:{select:{builds:{where:{status:{in:_}}}}}}},artifacts:{orderBy:{createdAt:"asc"}}}}}})}async reportsForBuild(e){return(await (0,o.getPrismaClient)()).buildReport.findMany({where:{buildId:e},orderBy:{createdAt:"asc"},include:{artifact:!0}})}async reportData(e){let t=await (0,o.getPrismaClient)(),r=await t.buildReport.findUnique({where:{id:e},select:{dataJson:!0}});return r?.dataJson??"{}"}async builds(e={}){let t=await (0,o.getPrismaClient)(),r=Math.max(1,Math.min(e.first??50,200)),i=await t.build.findMany({where:{...e.status?{status:e.status}:{},...e.codebaseId?{codebaseId:e.codebaseId}:{},...e.worktreeId?{worktreeId:e.worktreeId}:{},...e.appId?{repository:{apps:{some:{appId:e.appId}}}}:{}},orderBy:[{createdAt:"desc"},{id:"desc"}],...e.after?{cursor:{id:e.after},skip:1}:{},take:r+1,include:T});return{items:i.slice(0,r),nextCursor:i.length>r?i[r-1].id:null}}async getBuild(e){return(await (0,o.getPrismaClient)()).build.findUnique({where:{id:e},include:T})}async deleteBuilds(e){let t=[...new Set(e)];if(!t.length)return 0;if(t.length>200)throw Error("At most 200 builds can be deleted at once");let r=await (0,o.getPrismaClient)(),i=await r.build.findMany({where:{id:{in:t}},select:{id:!0,status:!0,artifactDirectory:!0,snapshotJson:!0,agentId:!0,agent:{select:{capabilitiesJson:!0}},codebaseId:!0,worktreeId:!0,deployments:{where:{status:{in:_}},select:{id:!0}},exports:{where:{status:{in:_}},select:{id:!0}}}});if(i.some(e=>_.includes(e.status)))throw Error("Running builds cannot be deleted");if(i.some(e=>e.deployments.length>0||e.exports.length>0))throw Error("Builds with running deployments or exports cannot be deleted");for(let e of i){if(!(0,a.isAbsolute)(e.artifactDirectory)||(0,a.basename)(e.artifactDirectory)!==e.id)throw Error(`Build folder is invalid for ${e.id}`);if(e.agentId){let t=v(e);if(!e.agent||!w(e.agent).includes(n.IOS_BUILD_DELETE_JOB_KIND))throw Error("Build agent must be updated to delete builds");await this.agentControl.createJob({agentId:e.agentId,codebaseId:t,worktreeId:e.worktreeId,kind:n.IOS_BUILD_DELETE_JOB_KIND,payload:{buildId:e.id,artifactDirectory:e.artifactDirectory,codebaseId:t},idempotencyKey:`ios:build:delete:${e.id}`,timeoutSeconds:300,visibility:"SYSTEM"})}}let s=await r.build.deleteMany({where:{id:{in:i.map(e=>e.id)}}});for(let e of i)this.publish(e.id);return s.count}async artifactForInstall(e,t){let r=await (0,o.getPrismaClient)(),i=await r.buildArtifact.findFirst({where:{id:t,buildId:e}});return i?{id:i.id,kind:i.kind,relativePath:i.relativePath,sizeBytes:i.sizeBytes,checksum:i.checksum,createdAt:i.createdAt.toISOString(),metadata:f(m(i.metadataJson,{}),"build artifact metadata")}:null}async prepareArtifactDownload(e,t,r,i=17e4){let a=await (0,o.getPrismaClient)(),s=await a.buildArtifact.findFirst({where:{id:t,buildId:e},include:{build:{include:{agent:!0}}}});if(!s)throw Error("Build artifact not found");let{build:l}=s;if(!l.agentId||!l.agent)throw Error("The build agent is no longer available");if(!y(l.agent))throw Error("Build agent is offline");if(!w(l.agent).includes(n.IOS_ARTIFACT_DOWNLOAD_JOB_KIND))throw Error("Build agent must be updated to download artifacts");let u=v(l),c=await this.agentControl.createJob({agentId:l.agentId,codebaseId:u,worktreeId:l.worktreeId,kind:n.IOS_ARTIFACT_DOWNLOAD_JOB_KIND,payload:{buildId:l.id,artifactDirectory:l.artifactDirectory,artifactRelativePath:s.relativePath,uploadId:r,codebaseId:u},idempotencyKey:`ios:artifact:download:${r}`,timeoutSeconds:Math.ceil(i/1e3)+10,visibility:"SYSTEM"});try{this.result(await this.waitForJob(c.id,i))}finally{await a.agentJob.deleteMany({where:{id:c.id,visibility:"SYSTEM"}})}}async logChunks(e,t=null,r=1e3){let i=await (0,o.getPrismaClient)(),a=t?await i.buildLogChunk.findFirst({where:{id:t,buildId:e},select:{id:!0,createdAt:!0,sequence:!0}}):null;if(t&&!a)throw Error("Build log cursor not found");return i.buildLogChunk.findMany({where:{buildId:e,...a?{OR:[{createdAt:{gt:a.createdAt}},{createdAt:a.createdAt,sequence:{gt:a.sequence}},{createdAt:a.createdAt,sequence:a.sequence,id:{gt:a.id}}]}:{}},orderBy:[{createdAt:"asc"},{sequence:"asc"},{id:"asc"}],take:Math.max(1,Math.min(r,5e3))})}async cancelBuild(e){let t=await (0,o.getPrismaClient)(),r=await t.build.findUnique({where:{id:e}});if(!r)throw Error("Build not found");return _.includes(r.status)&&(r.jobId&&await this.agentControl.cancelJob(r.jobId),await t.build.update({where:{id:e},data:{status:"CANCELLED",finishedAt:new Date,errorCode:"CANCELLED"}}),this.publish(e)),this.getBuild(e)}async reportProgress(e,t){if(!["PREPARING","RUNNING"].includes(t.status))throw Error("Build progress status is invalid");let r=await (0,o.getPrismaClient)(),i=await r.build.findUnique({where:{id:t.buildId}});if(!i||i.agentId!==e)throw Error("Build not found for agent");if(!_.includes(i.status))return i;let a=await r.build.update({where:{id:t.buildId},data:{status:t.status,startedAt:i.startedAt??(t.startedAt?new Date(t.startedAt):new Date),errorCode:t.errorCode??void 0,error:t.error??void 0}});return this.publish(t.buildId),a}async appendLogChunks(e,t,r){if(!r.length||r.length>200)throw Error("Build log batches must contain 1 to 200 chunks");let a=await (0,o.getPrismaClient)(),n=await a.build.findUnique({where:{id:t}});if(!n||n.agentId!==e)throw Error("Build not found for agent");let s=r.map(e=>{if(!Number.isInteger(e.sequence)||e.sequence<0)throw Error("Log sequence must be a non-negative integer");if(!["STDOUT","STDERR","SYSTEM"].includes(e.stream))throw Error("Log stream is invalid");let r=Buffer.from(e.dataBase64,"base64");if(r.length!==e.byteLength||r.length>262144)throw Error("Log byte length is invalid");let a=Buffer.from(r.toString("utf8").replace(/(Bearer\s+)[A-Za-z0-9._~+\/-]+=*/gi,"$1[REDACTED]").replace(/([A-Za-z][A-Za-z0-9+.-]*:\/\/)[^\s/@]+@/g,"$1[REDACTED]@").replace(/\b([A-Z0-9_]*(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY)[A-Z0-9_]*)\s*=\s*[^\s]+/gi,"$1=[REDACTED]").replace(/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?-----END [^-]*PRIVATE KEY-----/g,"[REDACTED PRIVATE KEY]"),"utf8"),n=new Date(e.createdAt);if(Number.isNaN(n.valueOf()))throw Error("Log date is invalid");return{id:(0,i.randomUUID)(),buildId:t,scope:b(e.scope,"Log scope",40),scopeId:b(e.scopeId,"Log scope ID",200),sequence:e.sequence,phase:b(e.phase,"Log phase",80),stream:e.stream,dataBase64:a.toString("base64"),byteLength:a.byteLength,createdAt:n}}),l=[];for(let e of s){let r=await a.buildLogChunk.upsert({where:{scope_scopeId_sequence:{scope:e.scope,scopeId:e.scopeId,sequence:e.sequence}},create:e,update:{}});l.push(r),u.agentEventBus.publish((0,u.buildLogChunkTopic)(t),{buildLogChunkAdded:r})}return l}async runBuild(e){let t=await (0,o.getPrismaClient)(),r=await t.build.findUnique({where:{id:e.buildId},include:{artifacts:!0,worktree:{include:{codebase:{include:{agent:!0,repository:!0}}}}}});if(!r||"SUCCEEDED"!==r.status)throw Error("A successful build is required");let a=r.artifacts.find(e=>"RUNNABLE_APP"===e.kind);if(!a)throw Error("Build does not contain a runnable app");let s=f(m(a.metadataJson,{}),"runnable metadata"),l=b(String(s.bundleIdentifier??""),"Runnable bundle identifier",512),u=e.destinations.map(n.parseBuildDestination);if(!u.length)throw Error("Select at least one destination");if(new Set(u.map(e=>`${e.type}:${e.id}`)).size!==u.length)throw Error("Run destinations must be unique");if(u.some(e=>e.type!==r.destinationType))throw Error("Run destinations must match the build destination type");let c=r.agentId??r.worktree?.codebase.agentId,p=e.targetAgentId??c;if(!p)throw Error("Build agent is unavailable");let g=p===c;if(!g){let e=(await this.runAgentsForBuild(r.id)).find(e=>e.agent.id===p);if(!e?.available)throw Error("The selected run agent is unavailable")}let y=await this.destinationsForBuild(r.id,`${b(e.requestId,"Request ID",200)}:preflight`,p),w=u.map(e=>y.find(t=>t.type===e.type&&t.id===e.id));if(w.some(e=>!e)||(u=w).some(e=>!1===e.available))throw Error("A selected run destination is no longer available");if(g&&!r.worktree)throw Error("The build worktree is unavailable");let E=g?await this.requireWorktree(r.worktree.id,n.IOS_DEPLOY_JOB_KIND):null,S=(0,i.randomUUID)(),v=[];for(let a of u){let n=`${a.type}:${a.id}`,s=await t.buildDeployment.findUnique({where:{buildId_requestId_targetAgentId_destinationKey:{buildId:r.id,requestId:e.requestId,targetAgentId:p,destinationKey:n}}});v.push(s??await t.buildDeployment.create({data:{id:(0,i.randomUUID)(),buildId:r.id,batchId:S,requestId:e.requestId,destinationJson:JSON.stringify(a),destinationKey:n,targetAgentId:p,status:g?"QUEUED":"TRANSFERRING",commandSummary:"SIMULATOR"===a.type?`open -a Simulator --args -CurrentDeviceUDID ${a.id}; xcrun simctl install/launch ${a.id}`:`xcrun devicectl device install/process launch --device ${a.id}`}}))}let I=v.map((e,t)=>({id:e.id,destination:u[t]}));if(g&&E){let i=await this.agentControl.createJob({agentId:E.codebase.agentId,codebaseId:E.codebaseId,worktreeId:E.id,kind:n.IOS_DEPLOY_JOB_KIND,payload:{...this.identity(E),buildId:r.id,artifactDirectory:r.artifactDirectory,artifactRelativePath:a.relativePath,bundleIdentifier:l,deployments:I},idempotencyKey:`ios:deploy:${r.id}:${e.requestId}`,timeoutSeconds:3600});await t.buildDeployment.updateMany({where:{id:{in:v.map(e=>e.id)}},data:{jobId:i.id}})}else if(!v.find(e=>e.transferId)?.transferId){let s=(0,i.randomUUID)(),o=await (0,d.cachedArtifact)(r.id,a.id),u=o?await (0,h.buildArtifactFileChecksum)(o.path):null;await t.buildArtifactTransfer.create({data:{id:s,artifactId:a.id,sourceAgentId:r.agentId,targetAgentId:p,status:o?"READY":"QUEUED",uploadOffset:o?.size??0,uploadLength:o?.size??null,checksum:u,filename:o?.filename??null,contentType:o?.contentType??null,stagingPath:o?.path??null,expiresAt:new Date(Date.now()+216e5)}});try{let i=null;o||(i=(await this.agentControl.createJob({agentId:r.agentId,kind:n.IOS_ARTIFACT_TRANSFER_UPLOAD_JOB_KIND,payload:{transferId:s,buildId:r.id,artifactDirectory:r.artifactDirectory,artifactRelativePath:a.relativePath},idempotencyKey:`ios:artifact-transfer:${s}`,timeoutSeconds:3600,visibility:"SYSTEM"})).id,await t.buildArtifactTransfer.update({where:{id:s},data:{sourceJobId:i}}));let u=await this.agentControl.createJob({agentId:p,kind:n.IOS_REMOTE_DEPLOY_JOB_KIND,payload:{transferId:s,buildId:r.id,bundleIdentifier:l,deployments:I},idempotencyKey:`ios:remote-deploy:${r.id}:${e.requestId}:${p}`,timeoutSeconds:7200});await t.$transaction([t.buildArtifactTransfer.update({where:{id:s},data:{sourceJobId:i,targetJobId:u.id}}),t.buildDeployment.updateMany({where:{id:{in:v.map(e=>e.id)}},data:{jobId:u.id,transferId:s,targetAgentId:p}})])}catch(a){let e=a instanceof Error?a.message:String(a),i=new Date;throw await t.$transaction([t.buildArtifactTransfer.update({where:{id:s},data:{status:"FAILED",error:e,finishedAt:i}}),t.buildDeployment.updateMany({where:{id:{in:v.map(e=>e.id)}},data:{status:"FAILED",error:e,finishedAt:i}})]).catch(()=>{}),this.publish(r.id),a}}return this.publish(r.id),t.buildDeployment.findMany({where:{id:{in:v.map(e=>e.id)}},orderBy:{createdAt:"asc"}})}async exportArchive(e){let t=await (0,o.getPrismaClient)(),r=await t.buildExport.findUnique({where:{buildId_requestId:{buildId:e.buildId,requestId:e.requestId}}});if(r)return r;let a=await t.build.findUnique({where:{id:e.buildId},include:{artifacts:!0,worktree:!0}});if(!a||"SUCCEEDED"!==a.status||!a.worktree)throw Error("A successful archive build is required");let s=a.artifacts.find(e=>"ARCHIVE"===e.kind);if(!s)throw Error("Build does not contain an archive");let l=(0,n.parseBuildExportSettings)(e.settings),u=await this.requireWorktree(a.worktree.id,n.IOS_EXPORT_JOB_KIND),c=(0,i.randomUUID)(),d=await t.buildExport.create({data:{id:c,buildId:a.id,requestId:e.requestId,settingsSnapshotJson:JSON.stringify(l),commandSummary:`xcrun xcodebuild -exportArchive -archivePath ${JSON.stringify(s.relativePath)} -exportPath exports/${c}`}});try{let r=await this.agentControl.createJob({agentId:u.codebase.agentId,codebaseId:u.codebaseId,worktreeId:u.id,kind:n.IOS_EXPORT_JOB_KIND,payload:{...this.identity(u),buildId:a.id,exportId:c,artifactDirectory:a.artifactDirectory,archiveRelativePath:s.relativePath,settings:l},idempotencyKey:`ios:export:${a.id}:${e.requestId}`,timeoutSeconds:3600}),i=await t.buildExport.update({where:{id:d.id},data:{jobId:r.id}});return this.publish(a.id),i}catch(r){let e=await t.buildExport.update({where:{id:d.id},data:{status:"FAILED",error:r instanceof Error?r.message:String(r),finishedAt:new Date}});return this.publish(a.id),e}}async upsertArtifacts(e,t,r){for(let a of(0,n.parseBuildArtifactSnapshots)(r)){let r={kind:a.kind,sizeBytes:a.sizeBytes,checksum:a.checksum,metadataJson:JSON.stringify(a.metadata)};await e.buildArtifact.upsert({where:{buildId_relativePath:{buildId:t,relativePath:a.relativePath}},create:{id:(0,i.randomUUID)(),buildId:t,relativePath:a.relativePath,...r},update:r})}}async upsertReportProjection(e,t,r,a){let n=f(r,"build report");if("TEST_RESULTS"!==n.kind&&"CODE_COVERAGE"!==n.kind)return;let s=n.kind,o=n.artifact&&"object"==typeof n.artifact?f(n.artifact,"build report artifact"):null,l=o&&"string"==typeof o.relativePath?await e.buildArtifact.findUnique({where:{buildId_relativePath:{buildId:t,relativePath:o.relativePath}}}):null,u="READY"===n.status?"READY":"FAILED";await e.buildReport.upsert({where:{buildId_kind:{buildId:t,kind:s}},create:{id:(0,i.randomUUID)(),buildId:t,artifactId:l?.id??null,kind:s,source:a,status:u,summaryJson:JSON.stringify(n.summary&&"object"==typeof n.summary?n.summary:{}),dataJson:JSON.stringify(n.data&&"object"==typeof n.data?n.data:{}),error:"string"==typeof n.error?n.error:null,finishedAt:new Date},update:{artifactId:l?.id??null,source:a,status:u,summaryJson:JSON.stringify(n.summary&&"object"==typeof n.summary?n.summary:{}),dataJson:JSON.stringify(n.data&&"object"==typeof n.data?n.data:{}),error:"string"==typeof n.error?n.error:null,finishedAt:new Date}})}async projectBuildCompletion(e){let t=await (0,o.getPrismaClient)(),r=await t.build.findFirst({where:{jobId:e.id},include:{worktree:{select:{highlightColor:!0}}}});if(!r)return;let a=f(m(e.resultJson,{}),"build result"),n="CANCELLED"===r.status?"CANCELLED":I(e.status),s="string"==typeof a.sourceStateHash?a.sourceStateHash:null,l="string"==typeof a.finalStateHash?a.finalStateHash:null,u="string"==typeof a.codeStateObservedAt&&Number.isFinite(Date.parse(a.codeStateObservedAt))?new Date(a.codeStateObservedAt):new Date,c=l?u:new Date,d=r.snapshotJson;if(s){let e=f(m(r.snapshotJson,{}),"build snapshot"),t=f(e.worktree??{},"build worktree snapshot");d=JSON.stringify({...e,worktree:{...t,codeStateHash:s}})}let h=null;await t.$transaction(async t=>{if(await t.build.update({where:{id:r.id},data:{status:n,errorCode:"string"==typeof a.errorCode?a.errorCode:"TIMED_OUT"===e.status?"TIMEOUT":"FAILED"===n?"XCODEBUILD_FAILED":r.errorCode,error:e.error??("string"==typeof a.error?a.error:r.error),startedAt:r.startedAt??new Date,finishedAt:c,snapshotJson:d}}),r.worktreeId&&l&&await t.worktree.updateMany({where:{id:r.worktreeId,OR:[{lastCheckedAt:null},{lastCheckedAt:{lt:u}}]},data:{codeStateHash:l,lastCheckedAt:u}}),Array.isArray(a.artifacts))for(let e of a.artifacts){let a=f(e,"build artifact");"string"==typeof a.relativePath&&"string"==typeof a.kind&&await t.buildArtifact.upsert({where:{buildId_relativePath:{buildId:r.id,relativePath:a.relativePath}},create:{id:(0,i.randomUUID)(),buildId:r.id,kind:a.kind,relativePath:a.relativePath,sizeBytes:"number"==typeof a.sizeBytes?a.sizeBytes:null,checksum:"string"==typeof a.checksum?a.checksum:null,metadataJson:JSON.stringify(a.metadata&&"object"==typeof a.metadata?a.metadata:{})},update:{}})}if(Array.isArray(a.scriptExecutions))for(let e of a.scriptExecutions){let i=f(e,"script execution");"string"==typeof i.phase&&"number"==typeof i.position&&await t.buildScriptExecution.updateMany({where:{buildId:r.id,phase:i.phase,position:i.position},data:{status:"string"==typeof i.status?i.status:"FAILED",exitCode:"number"==typeof i.exitCode?i.exitCode:null,durationMs:"number"==typeof i.durationMs?i.durationMs:null,causedBuildFailure:!0===i.causedBuildFailure,outputRelativePath:"string"==typeof i.outputRelativePath?i.outputRelativePath:null,error:"string"==typeof i.error?i.error:null}})}if(Array.isArray(a.reports))for(let e of a.reports){let i=e&&"object"==typeof e&&!Array.isArray(e)?e:{};await this.upsertReportProjection(t,r.id,e,"CODE_COVERAGE"===i.kind?"WORKTREE":"AUTOMATIC")}if(this.notifications&&("SUCCEEDED"===n||"FAILED"===n)){let e=f(m(d,{}),"build notification snapshot"),i=f(e.repository??{},"build repository snapshot"),a=f(e.configuration??{},"build configuration snapshot"),s=f(e.worktree??{},"build worktree snapshot"),o=["string"==typeof i.name?i.name:null,"string"==typeof a.name?a.name:null,"string"==typeof s.branch?s.branch:"string"==typeof s.folder?s.folder:null].filter(e=>!!e);h=await this.notifications.recordInTransaction(t,{dedupeKey:`ios-build:${r.id}:${n}`,typeKey:"SUCCEEDED"===n?"IOS_BUILD_SUCCEEDED":"IOS_BUILD_FAILED",title:"SUCCEEDED"===n?"iOS build succeeded":"iOS build failed",body:o.join(" · ")||`Build ${r.id}`,href:`/builds/${r.id}`,resourceKind:"BUILD",resourceId:r.id,worktreeId:r.worktreeId,highlightColor:r.worktree?.highlightColor??null})}}),this.publish(r.id),this.notifications?.created(h),"SUCCEEDED"===n&&await this.queueAutomaticExport(r.id,d)}async queueAutomaticExport(e,t){let r=f(m(t,{}),"build snapshot"),a=f(r.configuration??{},"build configuration snapshot");if(!0!==a.autoExport)return;let n=a.exportSettings;try{await this.exportArchive({buildId:e,requestId:"automatic",settings:n})}catch(a){let t=await (0,o.getPrismaClient)(),r=a instanceof Error?a.message:String(a);await t.buildExport.upsert({where:{buildId_requestId:{buildId:e,requestId:"automatic"}},create:{id:(0,i.randomUUID)(),buildId:e,requestId:"automatic",status:"FAILED",settingsSnapshotJson:JSON.stringify(n??{}),commandSummary:"Automatic archive export",error:r,finishedAt:new Date},update:{status:"FAILED",error:r,finishedAt:new Date}}),this.publish(e)}}async projectGeneratedReportCompletion(e){let t=f(m(e.payloadJson,{}),"build report payload");if("string"!=typeof t.buildId)return;let r=t.buildId,a=f(m(e.resultJson,{}),"build report result"),n=await (0,o.getPrismaClient)();await n.$transaction(async n=>{if(await this.upsertArtifacts(n,r,a.artifacts),a.report&&"object"==typeof a.report)await this.upsertReportProjection(n,r,a.report,"WORKTREE"===t.source?"WORKTREE":"MANUAL");else{let a="CODE_COVERAGE"===t.reportKind?"CODE_COVERAGE":"TEST_RESULTS";await n.buildReport.upsert({where:{buildId_kind:{buildId:r,kind:a}},create:{id:(0,i.randomUUID)(),buildId:r,kind:a,source:"WORKTREE"===t.source?"WORKTREE":"MANUAL",status:"FAILED",error:e.error||"Report generation failed",finishedAt:new Date},update:{status:"FAILED",error:e.error||"Report generation failed",finishedAt:new Date}})}}),this.publish(r)}async projectDeploymentCompletion(e){let t=await (0,o.getPrismaClient)(),r=await t.buildDeployment.findMany({where:{jobId:e.id}});if(!r.length)return;let i=f(m(e.resultJson,{}),"deployment result"),a=Array.isArray(i.deployments)?i.deployments:[];for(let i of r){let r=a.map(e=>f(e,"deployment outcome")).find(e=>e.id===i.id);await t.buildDeployment.update({where:{id:i.id},data:{status:"string"==typeof r?.status?r.status:I(e.status),error:"string"==typeof r?.error?r.error:e.error,outputRelativePath:"string"==typeof r?.outputRelativePath?r.outputRelativePath:null,startedAt:i.startedAt??new Date,finishedAt:new Date}})}for(let i of[...new Set(r.map(e=>e.transferId).filter(e=>!!e))]){let n=r.some(e=>{let t=a.map(e=>f(e,"deployment outcome")).find(t=>t.id===e.id);return t?.status!=="SUCCEEDED"});await t.buildArtifactTransfer.update({where:{id:i},data:{status:n||"SUCCEEDED"!==e.status?"FAILED":"SUCCEEDED",error:n||"SUCCEEDED"!==e.status?e.error||"One or more remote deployments failed":null,finishedAt:new Date}})}this.publish(r[0].buildId)}async projectExportCompletion(e){let t=await (0,o.getPrismaClient)(),r=await t.buildExport.findFirst({where:{jobId:e.id}});if(!r)return;let a=f(m(e.resultJson,{}),"export result");if(await t.buildExport.update({where:{id:r.id},data:{status:I(e.status),error:e.error??("string"==typeof a.error?a.error:null),outputRelativePath:"string"==typeof a.outputRelativePath?a.outputRelativePath:null,startedAt:r.startedAt??new Date,finishedAt:new Date}}),"SUCCEEDED"===e.status&&"string"==typeof a.outputRelativePath){let e=a.outputRelativePath;await t.$transaction(async t=>{await t.buildArtifact.upsert({where:{buildId_relativePath:{buildId:r.buildId,relativePath:e}},create:{id:(0,i.randomUUID)(),buildId:r.buildId,kind:"EXPORT",relativePath:e,sizeBytes:"number"==typeof a.sizeBytes?a.sizeBytes:null,metadataJson:JSON.stringify({exportId:r.id})},update:{}}),await this.upsertArtifacts(t,r.buildId,a.artifacts)})}this.publish(r.buildId)}}r()}catch(e){r(e)}},!1),224174,e=>e.a(async(t,r)=>{try{e.s([]);var i=e.i(669602);e.i(190714);var a=t([i]);[i]=a.then?(await a)():a,r()}catch(e){r(e)}},!1),483024,e=>{"use strict";var t=e.i(666680),r=e.i(986847),i=e.i(735255),a=e.i(243783);e.i(805422);var n=e.i(694355),s=e.i(661983);let o=["inputTokens","outputTokens","cacheCreationTokens","cacheReadTokens","totalTokens","totalCost"],l=["inputTokens","outputTokens","cacheCreationTokens","cacheReadTokens","cost"];function u(){return{daily:[],totals:c()}}function c(){return{inputTokens:0,outputTokens:0,cacheCreationTokens:0,cacheReadTokens:0,totalTokens:0,totalCost:0}}function d(e){return{modelName:e,inputTokens:0,outputTokens:0,cacheCreationTokens:0,cacheReadTokens:0,cost:0}}function h(e){return[...new Set(e)].sort()}function p(e){let t=[...e.values()].sort((e,t)=>e.period.localeCompare(t.period));return{daily:t,totals:function(e){let t=c();for(let r of e)for(let e of o)t[e]+=r[e];return t}(t)}}function m(e){return new Map(e.daily.map(e=>[e.period,e]))}function f(e){return new Map((e?.modelBreakdowns??[]).map(e=>[e.modelName,e]))}function g(e,t,r){return void 0===r?t+e:r<e?t+e-r:t}function y(e,t){let r=0;for(let i of e)r+=function(e,t){switch(t){case"totalCost":return e.cost;case"totalTokens":return e.inputTokens+e.outputTokens+e.cacheCreationTokens+e.cacheReadTokens;default:return e[t]}}(i,t);return r}function w(e,t){if(e)return Math.max(0,e[t]-y(e.modelBreakdowns,t))}function b(e,t){let r=m(e),i=m(t),a=h([...r.keys(),...i.keys()]),n=new Map;for(let e of a){let t=r.get(e),a=i.get(e),s=c();for(let e of o)s[e]=(t?.[e]??0)+(a?.[e]??0);let u=f(t),p=f(a),m=h([...u.keys(),...p.keys()]);n.set(e,{...s,agent:a?.agent??t?.agent??"all",period:e,metadata:{agents:h([...t?.metadata.agents??[],...a?.metadata.agents??[]])},modelsUsed:h([...t?.modelsUsed??[],...a?.modelsUsed??[]]),modelBreakdowns:m.map(e=>{let t=u.get(e),r=p.get(e),i=d(e);for(let e of l)i[e]=(t?.[e]??0)+(r?.[e]??0);return i})})}return p(n)}function E(e,t,r){let i=m(e),a=m(t),n=m(r),s=h([...i.keys(),...a.keys(),...n.keys()]),u=new Map;for(let e of s){let t=function(e,t,r,i){let a=f(e),n=f(t),s=f(r),u=h([...a.keys(),...n.keys(),...s.keys()]).flatMap(e=>{let t=function(e,t,r,i){let a=d(i);for(let i of l)a[i]=g(t?.[i]??0,e?.[i]??0,r?.[i]);return l.some(e=>a[e]>0)?a:null}(a.get(e),n.get(e),s.get(e),e);return t?[t]:[]}),p=c();for(let i of o){let a=w(e,i)??0,n=w(t,i)??0,s=w(r,i);p[i]=y(u,i)+g(n,a,s)}return o.some(e=>p[e]>0)||0!==u.length?{...p,agent:r?.agent??t?.agent??e?.agent??"all",period:i,metadata:{agents:h([...e?.metadata.agents??[],...t?.metadata.agents??[],...r?.metadata.agents??[]])},modelBreakdowns:u,modelsUsed:h([...e?.modelsUsed??[],...t?.modelsUsed??[],...r?.modelsUsed??[]])}:null}(i.get(e),a.get(e),n.get(e),e);t&&u.set(e,t)}let E=p(u);return{archived:E,live:r,combined:b(E,r)}}function S(e){return(0,r.parseCcusageReport)(JSON.parse(e))}let v=new Set(["SUCCEEDED","FAILED","CANCELLED","TIMED_OUT"]);e.s(["CcusageService",0,class{agentControlService;now;deadlineTimers;initialized;initializationPromise;completionObservers;constructor(e,t=()=>new Date){this.agentControlService=e,this.now=t,this.deadlineTimers=new Map,this.initialized=!1,this.initializationPromise=null,this.completionObservers=new Set}async initialize(){if(!this.initialized)return this.initializationPromise||(this.initializationPromise=this.restoreCollections().then(()=>{this.initialized=!0}).finally(()=>{this.initializationPromise=null})),this.initializationPromise}async restoreCollections(){let e=await (0,a.getPrismaClient)(),t=await e.ccusageCollection.findMany({where:{finishedAt:null},select:{id:!0}});await Promise.all(t.map(async({id:e})=>{await this.ensureJobs(e),await this.getCollection(e)}))}async collect(e){let t=await this.start(e);return"COMPLETED"===t.status?t:this.waitForCompletion(t.id)}async start(e){let r=e?.trim()||(0,t.randomUUID)();await this.ensureCollection(r);let i=await this.getCollection(r);if(!i)throw Error("ccusage collection disappeared");return i}registerCompletionObserver(e){return this.completionObservers.add(e),()=>this.completionObservers.delete(e)}async getCollection(e){let t=await this.loadCollection(e);if(!t)return null;null===t.finishedAt&&t.deadlineAt.getTime()<=this.now().getTime()&&(await this.timeoutMembersWithoutJobs(t),await this.agentControlService.timeoutCollectionJobs(e),t=await this.loadCollection(e)??t);let r=await this.snapshot(t);if("COMPLETED"===r.status&&null===t.finishedAt){let t=this.now(),i=await (0,a.getPrismaClient)(),n=await i.ccusageCollection.updateMany({where:{id:e,finishedAt:null},data:{finishedAt:t}});r.finishedAt=t.toISOString(),this.clearDeadline(e),n.count>0&&await this.notifyCompletion(r)}else"COLLECTING"===r.status&&this.scheduleDeadline(t);return r}async clearHistory(){return(await (0,a.getPrismaClient)()).$transaction(async e=>{let t=this.now(),r=await e.ccusageHistory.deleteMany();return await e.sidebarUsageSummary.deleteMany(),await e.ccusageHistoryState.upsert({where:{id:"default"},create:{id:"default",clearedAt:t},update:{clearedAt:t}}),r.count})}async *subscribe(e){let t=s.agentEventBus.iterate((0,s.ccusageCollectionChangedTopic)(e));try{let r=await this.getCollection(e);for(r&&(yield r);;){if((await t.next()).done)return;let r=await this.getCollection(e);r&&(yield r)}}finally{await t.return?.()}}async ensureCollection(e){let t=await (0,a.getPrismaClient)(),i=await t.ccusageCollection.findUnique({where:{id:e},select:{id:!0}});if(!i){let a=await this.agentControlService.listAgents();try{i=await t.ccusageCollection.create({data:{id:e,deadlineAt:new Date(this.now().getTime()+15e4),agents:{create:a.map(e=>{var t;return{agentId:e.id,initialStatus:(t=this.now().getTime(),null!==e.lastSeenAt&&t-e.lastSeenAt.getTime()<=(0,n.agentOnlineWindowMs)(e)&&null===e.disconnectedAt?(function(e){try{let t=JSON.parse(e.capabilitiesJson);return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}catch{return[]}})(e).includes(r.CCUSAGE_REPORT_JOB_KIND)?"QUEUING":"UNSUPPORTED":"OFFLINE")}})}},select:{id:!0}}),this.publish(e)}catch(r){if(!(i=await t.ccusageCollection.findUnique({where:{id:e},select:{id:!0}})))throw r}}await this.ensureJobs(e);let s=await this.getCollection(e);if(s?.status==="COLLECTING"){let r=await t.ccusageCollection.findUnique({where:{id:e},select:{id:!0,deadlineAt:!0,finishedAt:!0}});r&&this.scheduleDeadline(r)}}async ensureJobs(e){let t=await (0,a.getPrismaClient)(),i=await t.ccusageCollection.findUnique({where:{id:e},select:{deadlineAt:!0,finishedAt:!0}});if(!i||i.finishedAt||i.deadlineAt.getTime()<=this.now().getTime())return;let n=await t.ccusageCollectionAgent.findMany({where:{collectionId:e,initialStatus:"QUEUING"},select:{agentId:!0}}),s=new Set((await t.agentJob.findMany({where:{ccusageCollectionId:e},select:{agentId:!0}})).map(({agentId:e})=>e));await Promise.all(n.filter(({agentId:e})=>!s.has(e)).map(async({agentId:i})=>{try{await this.agentControlService.createJob({agentId:i,kind:r.CCUSAGE_REPORT_JOB_KIND,payload:{},idempotencyKey:`ccusage:${e}`,timeoutSeconds:120,ccusageCollectionId:e})}catch(r){await t.ccusageCollectionAgent.update({where:{collectionId_agentId:{collectionId:e,agentId:i}},data:{initialStatus:"FAILED",error:r instanceof Error?r.message:String(r)}}),this.publish(e)}}))}async waitForCompletion(e){let t=s.agentEventBus.iterate((0,s.ccusageCollectionChangedTopic)(e));try{for(;;){let r=await this.getCollection(e);if(!r)throw Error("ccusage collection disappeared");if("COMPLETED"===r.status)return r;let i=Math.max(1,new Date(r.deadlineAt).getTime()-this.now().getTime()+25);await Promise.race([t.next(),new Promise(e=>setTimeout(e,i))])}}finally{await t.return?.()}}async loadCollection(e){return(await (0,a.getPrismaClient)()).ccusageCollection.findUnique({where:{id:e},include:{agents:{include:{agent:!0}},jobs:!0}})}async timeoutMembersWithoutJobs(e){let t=new Set(e.jobs.map(({agentId:e})=>e)),r=e.agents.filter(({agentId:e,initialStatus:r})=>"QUEUING"===r&&!t.has(e)).map(({agentId:e})=>e);if(0===r.length)return;let i=await (0,a.getPrismaClient)();(await i.ccusageCollectionAgent.updateMany({where:{collectionId:e.id,agentId:{in:r},initialStatus:"QUEUING"},data:{initialStatus:"TIMED_OUT"}})).count>0&&this.publish(e.id)}async snapshot(e){let t=new Map(e.jobs.map(e=>[e.agentId,e])),a=e.agents.map(e=>(function(e,t){let i={agent:e.agent,jobId:t?.id??null};if("QUEUING"!==e.initialStatus)return{progress:{...i,status:e.initialStatus,error:e.error}};if(!t)return{progress:{...i,status:"QUEUING",error:e.error}};if("SUCCEEDED"!==t.status)return{progress:{...i,status:t.status,error:t.error}};try{let e=(0,r.parseCcusageJobResult)(null===t.resultJson?null:JSON.parse(t.resultJson));return{progress:{...i,status:"SUCCEEDED",error:null},report:e.report}}catch(e){return{progress:{...i,status:"INVALID",error:e instanceof Error?e.message:String(e)}}}})(e,t.get(e.agentId))),n=a.map(({progress:e})=>e),s=n.filter(({status:e})=>"OFFLINE"!==e&&"UNSUPPORTED"!==e),o=s.filter(({status:e})=>"INVALID"===e||v.has(e)),l=a.flatMap(({progress:r,report:i})=>i&&r.jobId?[{agent:{id:r.agent.id,name:r.agent.name,hostname:r.agent.hostname},report:i,jobId:r.jobId,observedAt:t.get(r.agent.id)?.startedAt??t.get(r.agent.id)?.createdAt??e.createdAt}]:[]);await this.persistReports(l);let u=await this.loadHistoryReports(),c=new Set(u.reports.map(({agent:e})=>e.id)),d=[...u.reports,...l.filter(({agent:e})=>!c.has(e.id))];return{id:e.id,status:o.length===s.length?"COMPLETED":"COLLECTING",createdAt:e.createdAt.toISOString(),deadlineAt:e.deadlineAt.toISOString(),finishedAt:e.finishedAt?.toISOString()??null,progress:{eligibleCount:s.length,finishedCount:o.length,successfulCount:s.filter(({status:e})=>"SUCCEEDED"===e).length,agents:n},aggregate:(0,i.aggregateUsage)(d),liveAggregate:(0,i.aggregateUsage)(l),hasStoredHistory:u.hasStoredHistory}}async persistReports(e){if(0===e.length)return;let t=await (0,a.getPrismaClient)();for(let r of e)await t.$transaction(async e=>{let t=await e.ccusageHistoryState.findUnique({where:{id:"default"},select:{clearedAt:!0}});if(t?.clearedAt&&r.observedAt<=t.clearedAt)return;let i=await e.ccusageHistory.findUnique({where:{agentId:r.agent.id}});if(null!==i&&(i.lastJobId===r.jobId||!(i.lastObservedAt<r.observedAt)))return;let a=i?E(S(i.archivedReportJson),S(i.lastLiveReportJson),r.report):E(u(),u(),r.report),n={agentName:r.agent.name,hostname:r.agent.hostname,archivedReportJson:JSON.stringify(a.archived),lastLiveReportJson:JSON.stringify(a.live),lastObservedAt:r.observedAt,lastJobId:r.jobId};await e.ccusageHistory.upsert({where:{agentId:r.agent.id},create:{agentId:r.agent.id,...n},update:n})})}async loadHistoryReports(){let e=await (0,a.getPrismaClient)(),t=await e.ccusageHistory.findMany();return{hasStoredHistory:t.length>0,reports:t.flatMap(e=>{try{return[{agent:{id:e.agentId,name:e.agentName,hostname:e.hostname},report:b(S(e.archivedReportJson),S(e.lastLiveReportJson))}]}catch(t){return console.error(`Could not read ccusage history for agent ${e.agentId}:`,t instanceof Error?t.message:t),[]}})}}async notifyCompletion(e){for(let t of this.completionObservers)try{await t(e)}catch(e){console.error("ccusage completion observer failed:",e instanceof Error?e.message:e)}}scheduleDeadline(e){if(e.finishedAt||this.deadlineTimers.has(e.id))return;let t=setTimeout(()=>{this.deadlineTimers.delete(e.id),this.expire(e.id)},Math.max(0,e.deadlineAt.getTime()-this.now().getTime()));t.unref?.(),this.deadlineTimers.set(e.id,t)}async expire(e){try{await this.agentControlService.timeoutCollectionJobs(e),await this.getCollection(e),this.publish(e)}catch(t){console.error(`Could not expire ccusage collection ${e}:`,t instanceof Error?t.message:t)}}clearDeadline(e){let t=this.deadlineTimers.get(e);t&&clearTimeout(t),this.deadlineTimers.delete(e)}publish(e){s.agentEventBus.publish((0,s.ccusageCollectionChangedTopic)(e),{ccusageCollectionChanged:{id:e}})}}],483024)},121717,e=>{"use strict";e.i(483024),e.s([])},764892,e=>{"use strict";var t=e.i(666680),r=e.i(937121),i=e.i(243783),a=e.i(988349);e.i(805422);var n=e.i(661983),s=e.i(694355);let o=["ANY_AGENT_HOME","SPECIFIC_AGENT_HOME","ANY_WORKTREE","REPOSITORY_WORKTREE"],l=["NEVER","ON_FAILURE","ALWAYS"],u=["EXCLUSIVE","NON_EXCLUSIVE","EXCLUDED"],c=["QUEUED","RUNNING","RESTARTING","CANCELLING"],d=["SUCCEEDED","FAILED","CANCELLED"],h=["SUCCEEDED","FAILED","CANCELLED","TIMED_OUT"],p=e=>!!(e&&!h.includes(e.status)),m="aide.command.export",f=()=>({targetAgent:!0,repositories:{include:{repository:!0},orderBy:[{createdAt:"asc"},{repositoryId:"asc"}]}}),g=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}},y=["QUEUED","RESTARTING"],w=(e,t)=>e.queuedAt.getTime()-t.queuedAt.getTime()||e.id.localeCompare(t.id);function b(e,t,r){let i=t.trim().toUpperCase();if(!e.includes(i))throw Error(`${r} is not supported`);return i}function E(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 S(e,t){if(!e||"object"!=typeof e||Array.isArray(e))throw Error(`${t} must be an object`);return e}let v=e=>"string"==typeof e&&e.trim()?e.trim():null;function I(e){n.agentEventBus.publish(n.COMMANDS_CHANGED_TOPIC,{commandsChanged:e})}function A(e){n.agentEventBus.publish(n.COMMAND_RUNS_CHANGED_TOPIC,{commandRunsChanged:e}),n.agentEventBus.publish((0,n.commandRunChangedTopic)(e.id),{commandRunChanged:e}),n.agentEventBus.publish(n.SIDEBAR_STATUS_CHANGED_TOPIC,{sidebarStatusChanged:!0})}e.s(["CommandsService",0,class{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(r.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,i.getPrismaClient)();return(await t.commandDefinition.findMany({where:e?{}:{archivedAt:null},include:f(),orderBy:[{archivedAt:"asc"},{name:"asc"}]})).map(g)}async getDefinition(e){let t=await (0,i.getPrismaClient)(),r=await t.commandDefinition.findUnique({where:{id:e},include:f()});return r?g(r):null}normalizeDefinition(e){let t=b(o,e.targetKind,"Target scope"),r=b(l,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 c=b(u,e.concurrency??"NON_EXCLUSIVE","Concurrency");return{name:E(e.name,"Name",120),description:(e.description??"").trim().slice(0,2e3),script:E(e.script,"Script",1e6),targetKind:t,targetAgentId:e.targetAgentId??null,targetRepositoryIds:s,restartPolicy:r,restartLimit:i,concurrency:c,blocksGitOperations:"EXCLUSIVE"===c||(e.blocksGitOperations??!1),quickActionEnabled:e.quickActionEnabled??!1,quickActionIconKey:E(e.quickActionIconKey??"terminal","Quick action icon",40),quickActionButtonVariant:E(e.quickActionButtonVariant??"default","Quick action style",40),notificationsEnabled:e.notificationsEnabled??!0}}async assertRepositoriesExist(e){if(!e.length)return;let t=await (0,i.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 r=await (0,i.getPrismaClient)(),{targetRepositoryIds:a,...n}=this.normalizeDefinition(e);await this.assertRepositoriesExist(a);let s=g(await r.commandDefinition.create({data:{id:(0,t.randomUUID)(),...n,repositories:{create:a.map(e=>({repositoryId:e}))}},include:f()}));return I(s),s}async updateDefinition(e,t){let r=await (0,i.getPrismaClient)(),{targetRepositoryIds:a,...n}=this.normalizeDefinition(t);await this.assertRepositoriesExist(a);let s=g(await r.commandDefinition.update({where:{id:e},data:{...n,repositories:{deleteMany:{},create:a.map(e=>({repositoryId:e}))}},include:f()}));return I(s),s}async deleteDefinition(e){let t=await (0,i.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}}),I(r),!0}async exportDefinition(e){let t=await this.getDefinition(e);if(!t)throw Error("Command not found");return{format:m,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=b(o,v(e.targetKind)??"ANY_AGENT_HOME","Target scope"),r=await (0,i.getPrismaClient)();if("SPECIFIC_AGENT_HOME"===t){let i=v(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=>S(e,"Exported target repository")):[];if(i.length){let e=await r.codebaseRepository.findMany({where:{OR:i.flatMap(e=>{let t=v(e.canonicalOrigin),r=v(e.name);return[...t?[{canonicalOrigin:t}]:[],...r?[{name:r}]:[]]})},orderBy:{id:"asc"}}),a=i.map(t=>{let r=v(t.canonicalOrigin),i=v(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=v(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=S(t,"Command import"),i=r.format===m?S(r.command,"Exported command"):r,{widened:a,...n}=await this.resolveImportTarget(i),s=e.name?.trim()||v(i.name);if(!s)throw Error("Name is required");let o=v(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:v(i.restartPolicy)??"NEVER",restartLimit:null===i.restartLimit||"number"==typeof i.restartLimit?i.restartLimit:3,concurrency:v(i.concurrency)??"NON_EXCLUSIVE",blocksGitOperations:!0===i.blocksGitOperations,quickActionEnabled:!a&&!0===i.quickActionEnabled,quickActionIconKey:v(i.quickActionIconKey)??"terminal",quickActionButtonVariant:v(i.quickActionButtonVariant)??"default",notificationsEnabled:!1!==i.notificationsEnabled})}async archiveDefinition(e,t){let r=await (0,i.getPrismaClient)(),a=g(await r.commandDefinition.update({where:{id:e},data:{archivedAt:t?new Date:null},include:f()}));return I(a),a}async eligibleForAgent(e){let t=await (0,i.getPrismaClient)();return(await t.commandDefinition.findMany({where:{archivedAt:null,OR:[{targetKind:"ANY_AGENT_HOME"},{targetKind:"SPECIFIC_AGENT_HOME",targetAgentId:e}]},include:f(),orderBy:{name:"asc"}})).map(g)}async eligibleForWorktree(e){let t=await (0,i.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:f(),orderBy:{name:"asc"}})).map(g)}async listRuns(e){let t=await (0,i.getPrismaClient)(),r=Math.max(1,Math.min(e.first??50,200)),a=e.search?.trim(),n={...e.includeArchived?{}:{archivedAt:null},...e.agentId?{agentId:e.agentId}:{},...e.worktreeId?{worktreeId:e.worktreeId}:{},...e.statuses?.length?{status:{in:e.statuses}}:{},...a?{OR:[{snapshotName:{contains:a}},{agentName:{contains:a}},{worktreePath:{contains:a}}]}:{}},[s,o]=await Promise.all([t.commandRun.findMany({where:n,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:n})]),l=s.length>r,u=s.slice(0,r);return{nodes:u,totalCount:o,pageInfo:{hasNextPage:l,endCursor:u.at(-1)?.id??null}}}async getRun(e){return(await (0,i.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,i.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 a=r.attempts[0],n=!!(r.agent?.lastSeenAt&&!r.agent.disconnectedAt&&Date.now()-r.agent.lastSeenAt.getTime()<=(0,s.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(w),n=[...e.peers.filter(e=>!e.holdingTarget),...t.holdingTarget?[]:[t]].sort(w),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),u=i.filter(l),c=o.filter(l),d=t.stopRequested||!y.includes(t.status)?"NOT_QUEUED":t.holdingTarget?e.agentOnline?"WAITING_FOR_AGENT":"AGENT_OFFLINE":e.predecessorPending?"WAITING_FOR_PREDECESSOR":e.restartPending?"RESTART_DELAY":u.length?"TARGET_BUSY":c.length?"QUEUED_BEHIND":e.agentOnline?"READY":"AGENT_OFFLINE",h=new Set("TARGET_BUSY"===d||"QUEUED_BEHIND"===d?[...u,...c].map(e=>e.id):[]);return{reason:d,position:s<0?0:s+1,waitingCount:n.length,entries:[...a,...n].map(e=>({...e,blocking:h.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:!!(a?.agentJobId&&!a.completionProcessedAt)},peers:"EXCLUDED"===r.snapshotConcurrency?[]:await this.targetPeers(r),agentOnline:n,predecessorPending:!!(r.predecessor&&!d.includes(r.predecessor.status)),restartPending:!!("RESTARTING"===r.status&&r.nextRestartAt&&r.nextRestartAt.getTime()>Date.now())})}async listOutput(e,t=0,r=-1,a=1e3){let n=await (0,i.getPrismaClient)();return a<1?[]:n.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(a,5e3))})}async resolveTarget(e,t){let r=await (0,i.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 a=await r.worktree.findUnique({where:{id:t.worktreeId},include:{codebase:{include:{agent:!0,repository:!0}}}});if(!a||a.missingAt)throw Error("Worktree is unavailable");if("REPOSITORY_WORKTREE"===e.targetKind&&!e.repositories.some(e=>e.repositoryId===a.codebase.repositoryId))throw Error("This command is not eligible for the selected repository");return this.requireCapability(a.codebase.agent.capabilitiesJson),{agent:a.codebase.agent,worktree:a}}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(r.COMMAND_RUN_JOB_KIND))throw Error("The selected agent must be upgraded before it can run commands")}async startRun(e){let r,a=await (0,i.getPrismaClient)(),n=e.idempotencyKey?.trim()||(0,t.randomUUID)(),s=await a.commandRun.findUnique({where:{idempotencyKey:n}});if(s)return this.getRun(s.id);let o=await a.commandDefinition.findUnique({where:{id:e.commandId},include:f()});if(!o||o.archivedAt)throw Error("Command not found");let{agent:l,worktree:u}=await this.resolveTarget(o,e);try{r=await a.$transaction(async r=>{let i=await r.commandRunNumberSequence.upsert({where:{id:"default"},create:{id:"default",nextValue:1},update:{nextValue:{increment:1}}});return r.commandRun.create({data:{id:(0,t.randomUUID)(),displayNumber:i.nextValue,commandId:o.id,idempotencyKey:n,origin:(e.origin??"MANUAL").trim().toUpperCase(),snapshotName:o.name,snapshotDescription:o.description,snapshotScript:o.script,snapshotTargetKind:o.targetKind,snapshotRestartPolicy:o.restartPolicy,snapshotRestartLimit:o.restartLimit,snapshotConcurrency:o.concurrency,snapshotBlocksGitOperations:o.blocksGitOperations||!0===e.blocksGitOperations,snapshotNotificationsEnabled:o.notificationsEnabled,snapshotJson:JSON.stringify(g(o)),agentId:l.id,worktreeId:u?.id??null,agentName:l.name,agentHostname:l.hostname,worktreePath:u?.folder??null,worktreeBranch:u?.branch??null}})})}catch(t){let e=await a.commandRun.findUnique({where:{idempotencyKey:n}});if(!e)throw t;return this.getRun(e.id)}return A(r),await this.dispatch(r.id),this.getRun(r.id)}async startCustomRun(e){let r,a=await (0,i.getPrismaClient)(),n=e.idempotencyKey?.trim()||(0,t.randomUUID)(),s=await a.commandRun.findUnique({where:{idempotencyKey:n}});if(s)return this.getRun(s.id);let o=E(e.script,"Script",1e6),l=e.agentId&&!e.worktreeId?"ANY_AGENT_HOME":e.worktreeId&&!e.agentId?"ANY_WORKTREE":null;if(!l)throw Error("A custom command requires exactly one agent-home or worktree target");let{agent:u,worktree:c}=await this.resolveTarget({targetKind:l,targetAgentId:null,repositories:[]},e),d={name:"Custom command",description:"",script:o,targetKind:l,restartPolicy:"NEVER",restartLimit:null,concurrency:"NON_EXCLUSIVE",blocksGitOperations:!0===e.blocksGitOperations,notificationsEnabled:!0};try{r=await a.$transaction(async r=>{let i=await r.commandRunNumberSequence.upsert({where:{id:"default"},create:{id:"default",nextValue:1},update:{nextValue:{increment:1}}});return r.commandRun.create({data:{id:(0,t.randomUUID)(),displayNumber:i.nextValue,commandId:null,idempotencyKey:n,origin:(e.origin??"MANUAL").trim().toUpperCase(),status:"QUEUED",snapshotName:d.name,snapshotDescription:d.description,snapshotScript:d.script,snapshotTargetKind:d.targetKind,snapshotRestartPolicy:d.restartPolicy,snapshotRestartLimit:d.restartLimit,snapshotConcurrency:d.concurrency,snapshotBlocksGitOperations:d.blocksGitOperations,snapshotNotificationsEnabled:d.notificationsEnabled,snapshotJson:JSON.stringify(d),agentId:u.id,worktreeId:c?.id??null,agentName:u.name,agentHostname:u.hostname,worktreePath:c?.folder??null,worktreeBranch:c?.branch??null}})})}catch(t){let e=await a.commandRun.findUnique({where:{idempotencyKey:n}});if(!e)throw t;return this.getRun(e.id)}A(r);try{await this.dispatch(r.id)}catch(e){throw await this.failDispatch(r.id,e instanceof Error?e.message:String(e)),e}return this.getRun(r.id)}async targetPeers(e){let t=await (0,i.getPrismaClient)();return(await t.commandRun.findMany({where:{id:{not:e.id},status:{in:[...c]},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 n=await (0,i.getPrismaClient)(),s=await n.commandRun.findUnique({where:{id:e},include:{agent:!0,worktree:{include:{codebase:!0}},attempts:!0}});if(!s||s.stopRequested)return;if(!s.agentId||!s.agent)return void await this.failDispatch(s.id,"The command agent is no longer available");if(s.predecessorRunId){let e=await n.commandRun.findUnique({where:{id:s.predecessorRunId},select:{status:!0}});if(e&&!d.includes(e.status))return}if(new Set(["ANY_WORKTREE","REPOSITORY_WORKTREE"]).has(s.snapshotTargetKind)&&(!s.worktreeId||!s.worktree||s.worktree.missingAt))return void await this.failDispatch(s.id,"The command worktree is no longer available");if(s.worktree&&s.worktree.codebase.agentId!==s.agentId)return void await this.failDispatch(s.id,"The worktree is no longer assigned to the command agent");try{this.requireCapability(s.agent.capabilitiesJson)}catch(e){await this.failDispatch(s.id,e instanceof Error?e.message:String(e));return}let o=s.attempts.reduce((e,t)=>!e||t.attempt>e.attempt?t:e,null);if(!(o?.agentJobId&&!o.completionProcessedAt)&&!await this.admitRun(s))return;let l=!o||o.agentJobId||o.completionProcessedAt||o.finishedAt?(o?.attempt??0)+1:o.attempt,u=o?.attempt===l?o:await n.commandRunAttempt.findUnique({where:{runId_attempt:{runId:e,attempt:l}}});if(!u)try{u=await n.commandRunAttempt.create({data:{id:(0,t.randomUUID)(),runId:e,attempt:l}})}catch(t){if(!(u=await n.commandRunAttempt.findUnique({where:{runId_attempt:{runId:e,attempt:l}}})))throw t}if(!u.agentJobId){let e;try{e=await this.agentControl.createJob({agentId:s.agentId,kind:r.COMMAND_RUN_JOB_KIND,payload:{commandRunId:s.id,attemptId:u.id,targetKind:s.worktreeId?"WORKTREE":"AGENT_HOME",cwd:s.worktree?.folder??null,script:s.snapshotScript},idempotencyKey:`command-run:${s.id}:attempt:${l}`,timeoutSeconds:0,worktreeId:s.worktreeId,codebaseId:s.worktree?.codebaseId??null,visibility:"SYSTEM",blocksGitOperations:s.snapshotBlocksGitOperations})}catch(e){if(!(0,a.isCodebaseBusyError)(e))throw e;return}u=await n.commandRunAttempt.update({where:{id:u.id},data:{agentJobId:e.id,status:e.status}})}A(await n.commandRun.update({where:{id:s.id},data:{status:"RUNNING"===u.status?"RUNNING":"QUEUED",startedAt:"RUNNING"===u.status?s.startedAt??new Date:null,nextRestartAt:null,error:null}}))}async failDispatch(e,t){let r=await (0,i.getPrismaClient)(),a=await r.commandRun.update({where:{id:e},data:{status:"FAILED",error:t,finishedAt:new Date,nextRestartAt:null},include:{worktree:{select:{highlightColor:!0}}}});A(a),await this.notifyFinishedRun(a)}async terminateRun(e){let t=await (0,i.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(d.includes(r.status))return r;let a=await t.commandRun.update({where:{id:e},data:{stopRequested:!0,status:"CANCELLING",nextRestartAt:null}}),n=r.attempts[0]?.agentJobId;return p(n?await this.agentControl.cancelJob(n):null)||await this.finishCancelled(e),A(a),this.getRun(e)}async rerun(e){let r=await (0,i.getPrismaClient)(),a=await r.commandRun.findUnique({where:{id:e}});if(!a)throw Error("Command run not found");let n=await r.commandRun.findUnique({where:{predecessorRunId:a.id}});if(n)return this.getRun(n.id);let s=await r.$transaction(async e=>{let r=await e.commandRunNumberSequence.upsert({where:{id:"default"},create:{id:"default",nextValue:1},update:{nextValue:{increment:1}}});return e.commandRun.create({data:{id:(0,t.randomUUID)(),displayNumber:r.nextValue,commandId:a.commandId,idempotencyKey:`rerun:${a.id}:${(0,t.randomUUID)()}`,origin:"RERUN",snapshotName:a.snapshotName,snapshotDescription:a.snapshotDescription,snapshotScript:a.snapshotScript,snapshotTargetKind:a.snapshotTargetKind,snapshotRestartPolicy:a.snapshotRestartPolicy,snapshotRestartLimit:a.snapshotRestartLimit,snapshotConcurrency:a.snapshotConcurrency,snapshotBlocksGitOperations:a.snapshotBlocksGitOperations,snapshotNotificationsEnabled:a.snapshotNotificationsEnabled,snapshotJson:a.snapshotJson,agentId:a.agentId,worktreeId:a.worktreeId,agentName:a.agentName,agentHostname:a.agentHostname,worktreePath:a.worktreePath,worktreeBranch:a.worktreeBranch,predecessorRunId:a.id}})});return A(s),d.includes(a.status)?await this.dispatch(s.id):await this.terminateRun(a.id),this.getRun(s.id)}async archiveRuns(e,t){let r=await (0,i.getPrismaClient)();for(let i of(await r.commandRun.updateMany({where:{id:{in:e},status:{in:[...d]}},data:{archivedAt:t?new Date:null}}),e)){let e=await r.commandRun.findUnique({where:{id:i}});e&&A(e)}return!0}async deleteRuns(e){let t=await (0,i.getPrismaClient)();return(await t.commandRun.deleteMany({where:{id:{in:e},status:{in:[...d]}}})).count}async appendOutput(e,a,s,o){if(!o.length||o.length>r.MAX_COMMAND_OUTPUT_BATCH_CHUNKS)throw Error(`Output batches must contain 1 to ${r.MAX_COMMAND_OUTPUT_BATCH_CHUNKS} chunks`);let l=await (0,i.getPrismaClient)(),u=await l.commandRunAttempt.findUnique({where:{id:s},include:{run:!0}});if(!u||u.agentJobId!==a||u.run.agentId!==e)throw Error("Command attempt not found for this agent job");let c=o.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(c.map(e=>l.commandRunOutputChunk.upsert({where:{attemptId_sequence:{attemptId:s,sequence:e.sequence}},create:{id:(0,t.randomUUID)(),attemptId:s,...e},update:{}})));let d=await l.commandRunOutputChunk.findMany({where:{attemptId:s,sequence:{in:c.map(e=>e.sequence)}},orderBy:{sequence:"asc"}});for(let e of d){let t={...e,runId:u.runId,attemptNumber:u.attempt};n.agentEventBus.publish((0,n.commandRunOutputTopic)(u.runId),{commandRunOutputAdded:t}),n.agentEventBus.publish(n.COMMAND_RUN_OUTPUT_CHANGED_TOPIC,{commandRunOutputAdded:t})}return d}async finishCancelled(e){let t=await (0,i.getPrismaClient)();A(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,i.getPrismaClient)(),a=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(a)}catch(e){console.error("Command run notification failed:",e)}}async handleAttemptCompletion(e){let t=await (0,i.getPrismaClient)(),r=await t.commandRunAttempt.findUnique({where:{agentJobId:e.id},include:{run:!0,agentJob:!0}});if(!r||r.completionProcessedAt)return;let a=new Date,n=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:n.exitCode??null,signal:n.signal??null,error:e.error,startedAt:r.agentJob?.startedAt??r.startedAt,finishedAt:r.agentJob?.finishedAt??a,completionProcessedAt:a}})).count)return;if(r.run.stopRequested||"CANCELLED"===e.status)return void await this.finishCancelled(r.runId);let s="SUCCEEDED"===e.status&&0===n.exitCode,o=b(l,r.run.snapshotRestartPolicy,"Restart policy"),u=r.agentJob?.startedAt??r.createdAt,c=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:o,limit:r.run.snapshotRestartLimit,restartCount:r.run.restartCount,durationMs:a.getTime()-u.getTime(),clean:s,manualStop:r.run.stopRequested});if(c.restart)return void A(await t.commandRun.update({where:{id:r.runId},data:{status:"RESTARTING",restartCount:c.restartCount,nextRestartAt:new Date(a.getTime()+1e3),exitCode:n.exitCode??null,signal:n.signal??null,error:e.error}}));let d=await t.commandRun.update({where:{id:r.runId},data:{status:s?"SUCCEEDED":"FAILED",exitCode:n.exitCode??null,signal:n.signal??null,error:e.error??(c.exhausted?"Restart limit reached":s?null:"Command failed"),finishedAt:a,nextRestartAt:null},include:{worktree:{select:{highlightColor:!0}}}});A(d),await this.notifyFinishedRun(d)}async reconcile(e={}){let t=await (0,i.getPrismaClient)(),r=new Date;for(let i of(await t.commandRun.findMany({where:{status:{in:[...c]},...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&&p(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&&A(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)}}}])},344518,e=>{"use strict";e.i(764892),e.s([])},508813,e=>{"use strict";e.i(805422);var t=e.i(694355);e.s(["diskSpaceSessionData",0,function(e,r,i=null){let a=[...r.volumes].filter(e=>e.monitored).sort((e,t)=>e.freeBytes-t.freeBytes||e.id.localeCompare(t.id))[0],n=a&&a.totalBytes>0?a.freeBytes/a.totalBytes*100:null,s=null===r.agent.disconnectedAt&&null!==r.agent.lastSeenAt&&Date.now()-r.agent.lastSeenAt.getTime()<=(0,t.agentOnlineWindowMs)(r.agent);return{agent:{id:r.agent.id,name:r.agent.name,hostname:r.agent.hostname,connected:s,diskTotalBytes:r.agent.diskTotalBytes,diskFreeBytes:r.agent.diskFreeBytes},codebase:{agentId:r.agent.id},disk:{enabled:r.enabled,status:r.status,pressureMode:r.pressureMode,manualPressureMode:r.manualPressureMode,automaticPressureMode:r.automaticPressureMode,lastReportedAt:r.lastReportedAt,lastError:r.lastError,warnings:[...r.warnings],monitoredVolumeId:a?.id??null,freeBytes:a?.freeBytes??null,totalBytes:a?.totalBytes??null,freeGiB:a?a.freeBytes/0x40000000:null,freePercent:n,usedPercent:null===n?null:100-n,effectiveThresholdBytes:a?.effectiveThresholdBytes??null,normalThresholdGiB:e.normalThresholdGiB,pressureThresholdGiB:e.pressureThresholdGiB,pollIntervalSeconds:e.pollIntervalSeconds,staleAfterSeconds:e.staleAfterSeconds,changeReason:i,volumes:r.volumes.map(e=>({...e}))}}},"diskSpaceStateCursor",0,function(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}}])},599600,e=>{"use strict";var t=e.i(666680),r=e.i(885418),i=e.i(586589),a=e.i(243783);e.i(805422);var n=e.i(694355),s=e.i(661983),o=e.i(504173),l=e.i(518733),u=e.i(508813);function c(e){try{let t=JSON.parse(e??"[]");return Array.isArray(t)?t:[]}catch{return[]}}function d(e,t){if(!Number.isFinite(e)||e<=0||e>1e6)throw Error(`${t} must be a positive finite GiB value`);return e}e.s(["DiskSpaceService",0,class{agentControl;constructor(e){this.agentControl=e,this.agentControl.registerCompletionObserver(e=>this.observeCompletion(e))}async settings(){let e=await (0,a.getPrismaClient)(),t=await e.diskSpaceSettings.upsert({where:{id:"default"},create:{id:"default",normalThresholdGiB:i.DEFAULT_DISK_SPACE_THRESHOLD_GIB,pressureThresholdGiB:i.DEFAULT_DISK_SPACE_PRESSURE_THRESHOLD_GIB},update:{}});return{normalThresholdGiB:t.normalThresholdGiB,pressureThresholdGiB:t.pressureThresholdGiB,pollIntervalSeconds:i.DISK_SPACE_POLL_INTERVAL_SECONDS,staleAfterSeconds:i.DISK_SPACE_STALE_AFTER_SECONDS}}async updateSettings(e){let t=d(e.normalThresholdGiB,"Normal disk threshold"),r=d(e.pressureThresholdGiB,"Pressure disk threshold");if(r>=t)throw Error("Pressure disk threshold must be lower than the normal threshold");let i=await (0,a.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,a.getPrismaClient)(),[r,n,s]=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:n?.enabled??!0,pollIntervalSeconds:i.DISK_SPACE_POLL_INTERVAL_SECONDS,baseRepoDirectory:r.baseRepoDirectory,derivedDataLocationMode:r.derivedDataLocationMode,derivedDataPath:r.derivedDataPath,worktrees:s}}async report(e,t){let r=(0,i.parseAgentDiskSpaceReport)(t),n=await (0,a.getPrismaClient)(),[s,l]=await Promise.all([n.agent.findUnique({where:{id:e}}),n.worktree.findMany({where:{missingAt:null,codebase:{agentId:e}},include:{codebase:{select:{agentId:!0}}}})]);if(!s)throw Error("Agent not found");let u=new Date(r.observedAt),c=r.entries.map(e=>{let t=e.workspacePath?l.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,o.worktreeDisplayPath)(t.folder,s.baseRepoDirectory):null}});await n.agentDiskSpaceState.upsert({where:{agentId:e},create:{agentId:e,volumesJson:JSON.stringify(r.volumes),entriesJson:JSON.stringify(c),warningsJson:JSON.stringify(r.warnings),lastReportedAt:u,lastError:null},update:{volumesJson:JSON.stringify(r.volumes),entriesJson:JSON.stringify(c),warningsJson:JSON.stringify(r.warnings),lastReportedAt:u,lastError:null}}),this.publish(e,"REPORT_RECEIVED"),this.reconcileAgent(e)}async overview(){let e=await (0,a.getPrismaClient)();await e.derivedDataCleanupLease.deleteMany({where:{jobId:null,expiresAt:{lte:new Date}}});let[t,r,n]=await Promise.all([this.settings(),e.agent.findMany({orderBy:{name:"asc"},include:{diskSpaceState:!0}}),e.derivedDataCleanupLease.findMany({select:{agentId:!0}})]),s=new Set(n.map(e=>e.agentId));return{settings:t,agents:r.map(e=>{let r=e.diskSpaceState,a=r?.enabled??!0,n=r?.manualPressureMode??!1,o=r?.automaticPressureMode??!1,l=r?.lastReportedAt??null,u=!l||Date.now()-l.getTime()>1e3*t.staleAfterSeconds,d=(n||o?t.pressureThresholdGiB:t.normalThresholdGiB)*0x40000000,h=c(r?.volumesJson),p=(0,i.monitoredDiskSpaceVolumes)(h),m=p.some(e=>e.freeBytes<=0x40000000*t.pressureThresholdGiB),f=p.some(e=>e.freeBytes<d),g="IDLE";a?u?g="STALE":r?.lastError||0===h.length&&c(r?.warningsJson).length>0?g="ERROR":m?g="CRITICAL":s.has(e.id)?g="DELETING":n||o?g="PRESSURE":f&&(g="CLEANUP_REQUIRED"):g="DISABLED";let y=h.map(r=>{let l=(0,i.isMonitoredDiskSpaceVolume)(r);return{...r,effectiveThresholdBytes:d,monitored:l,status:a?u?"STALE":l?r.freeBytes<=0x40000000*t.pressureThresholdGiB?"CRITICAL":s.has(e.id)&&r.freeBytes<d?"DELETING":n||o?"PRESSURE":r.freeBytes<d?"CLEANUP_REQUIRED":"IDLE":"IDLE":"DISABLED"}}),w=c(r?.warningsJson);return a&&!u&&h.length>0&&0===p.length&&w.push("No Derived Data volume was reported, so free space is not being monitored for this agent"),{agent:e,enabled:a,status:g,pressureMode:n?"MANUAL":o?"AUTOMATIC":"NORMAL",manualPressureMode:n,automaticPressureMode:o,lastReportedAt:l?.toISOString()??null,lastError:r?.lastError??null,warnings:w,volumes:y}})}}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(0,u.diskSpaceSessionData)(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,a.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,a.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,a.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,a.getPrismaClient)(),[r,n]=await Promise.all([this.settings(),t.agentDiskSpaceState.findUnique({where:{agentId:e}})]);if(!(!n?.enabled||!n.lastReportedAt||n.lastError||Date.now()-n.lastReportedAt.getTime()>1e3*r.staleAfterSeconds)&&(0,i.monitoredDiskSpaceVolumes)(c(n.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 s.agentEventBus.iterate(s.DISK_SPACE_CHANGED_TOPIC)}async reconcileAgent(e){let s=await (0,a.getPrismaClient)();await s.derivedDataCleanupLease.deleteMany({where:{jobId:null,expiresAt:{lte:new Date}}});let[o,u,d,h,p]=await Promise.all([this.settings(),s.agentDiskSpaceState.findUnique({where:{agentId:e}}),s.derivedDataLock.findMany({where:{agentId:e},select:{path:!0}}),s.derivedDataCleanupLease.findFirst({where:{agentId:e}}),s.agent.findUnique({where:{id:e}})]);if(!u?.enabled||!u.lastReportedAt||u.lastError||h||!p||null!==p.disconnectedAt||null===p.lastSeenAt||Date.now()-p.lastSeenAt.getTime()>(0,n.agentOnlineWindowMs)(p)||!c(p.capabilitiesJson).includes(r.BUILD_DATA_DELETE_JOB_KIND)||Date.now()-u.lastReportedAt.getTime()>1e3*o.staleAfterSeconds)return;let m=c(u.entriesJson),f=c(u.volumesJson),g=(0,i.monitoredDiskSpaceVolumes)(f),y=m.map(e=>e.worktreeId).filter(e=>!!e),w=await (0,l.executingResourcesByWorktree)(y),b=new Set(d.map(e=>e.path));m=m.filter(e=>"PROJECT"===e.kind&&!!e.worktreeId&&!b.has(e.path)&&(w.get(e.worktreeId)?.length??0)===0);let E=0x40000000*o.normalThresholdGiB,S=0x40000000*o.pressureThresholdGiB,v=g.filter(e=>e.freeBytes<E),I=e=>e.capacityId??e.id,A=new Map(f.map(e=>[e.id,I(e)])),k=e=>m.some(t=>A.get(t.volumeId)===I(e)),_=u.automaticPressureMode;if(!u.manualPressureMode){let t=v.length>0&&v.some(e=>!k(e)),r=_&&(0===v.length||v.every(e=>k(e)));t?_=!0:r&&(_=!1),_!==u.automaticPressureMode&&(await s.agentDiskSpaceState.update({where:{agentId:e},data:{automaticPressureMode:_}}),this.publish(e,"AUTOMATIC_PRESSURE_CHANGED"))}let T=u.manualPressureMode||_?S:E,C=new Set(g.filter(e=>e.freeBytes<T).map(I)),R=m.filter(e=>C.has(A.get(e.volumeId)??"")).sort((e,t)=>new Date(e.modifiedAt).getTime()-new Date(t.modifiedAt).getTime()||e.path.localeCompare(t.path))[0];if(!R?.worktreeId)return;try{await s.derivedDataCleanupLease.create({data:{worktreeId:R.worktreeId,agentId:e,path:R.path,source:"AUTOMATIC",expiresAt:new Date(Date.now()+6e5)}})}catch{return}let N=await (0,l.executingResourcesByWorktree)([R.worktreeId]);if((N.get(R.worktreeId)?.length??0)>0){await s.derivedDataCleanupLease.deleteMany({where:{worktreeId:R.worktreeId,jobId:null}}),this.publish(e,"CLEANUP_SKIPPED");return}try{var O;let i=await this.agentControl.createJob({agentId:e,kind:r.BUILD_DATA_DELETE_JOB_KIND,payload:{source:"AUTOMATIC",targets:[{path:R.path,rootPath:R.rootPath,name:R.name,kind:R.kind,worktreeId:R.worktreeId,worktreePath:R.worktreePath}]},idempotencyKey:`disk-space:auto:${(O=R.path,(0,t.createHash)("sha256").update(e).update("\0").update(O).digest("base64url"))}:${(0,t.randomUUID)()}`,timeoutSeconds:600,visibility:"SYSTEM"});await s.derivedDataCleanupLease.update({where:{worktreeId:R.worktreeId},data:{jobId:i.id}}),this.publish(e,"CLEANUP_STARTED")}catch(t){await s.derivedDataCleanupLease.deleteMany({where:{worktreeId:R.worktreeId}}),await s.agentDiskSpaceState.update({where:{agentId:e},data:{lastError:t instanceof Error?t.message:String(t)}}),this.publish(e,"CLEANUP_START_FAILED")}}async observeCompletion(e){if(e.kind!==r.BUILD_DATA_DELETE_JOB_KIND)return;let t="USER",i=[];try{let a=(0,r.buildDataDeletePayload)(JSON.parse(e.payloadJson));t=a.source,i=a.targets}catch{}let n=await (0,a.getPrismaClient)(),s=await n.derivedDataCleanupLease.deleteMany({where:{jobId:e.id}});if("AUTOMATIC"===t&&"SUCCEEDED"!==e.status&&await n.agentDiskSpaceState.updateMany({where:{agentId:e.agentId},data:{lastError:e.error||"Automatic Derived Data cleanup failed"}}),s.count||"AUTOMATIC"===t){let a=[];if("AUTOMATIC"===t&&e.resultJson)try{a=(0,r.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:i,deleted:a}:null),this.agentControl.requestDiskSpacePoll(e.agentId)}}publish(e,r,i=null){s.agentEventBus.publish(s.DISK_SPACE_CHANGED_TOPIC,{diskSpaceChanged:e,diskSpaceChange:{id:(0,t.randomUUID)(),reason:r,cleanup:i}}),s.agentEventBus.publish(s.SIDEBAR_STATUS_CHANGED_TOPIC,{sidebarStatusChanged:!0}),s.agentEventBus.publish(s.POLLING_CHANGED_TOPIC,{pollingOperationChanged:`agent-disk-space:${e}`})}}])},714327,e=>{"use strict";e.i(599600),e.i(518733),e.i(508813),e.s([])},695248,e=>{"use strict";var t=e.i(666680),r=e.i(243783),i=e.i(483291);e.i(582482);var a=e.i(318905),n=e.i(783396),s=e.i(919412),o=e.i(407188),l=e.i(616204),u=e.i(334416),c=e.i(963910),d=e.i(940045);let h="server:github-actions-notifications",p=new Set(["failure","timed_out","startup_failure","action_required"]);function m(e){return"string"==typeof e&&e.trim()?e.trim():null}function f(e){return"number"==typeof e&&Number.isInteger(e)&&e>0?e:null}function g(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||"object"!=typeof e||Array.isArray(e))return[];let t=f(e.number);return t?[{number:t,url:m(e.html_url)??m(e.url)}]:[]}):[]}function y(e,t,r){let i=f(r?.id),a=f(r?.workflow_id),n=m(r?.updated_at),s=n?new Date(n):null;return i&&a&&s&&Number.isFinite(s.getTime())?{id:String(i),workflowId:String(a),runAttempt:f(r?.run_attempt)??1,name:m(r?.name)??"GitHub Actions",displayTitle:m(r?.display_title)??m(r?.name)??"Workflow run",status:m(r?.status)?.toLowerCase()??"unknown",conclusion:m(r?.conclusion)?.toLowerCase()??null,headBranch:m(r?.head_branch),headSha:m(r?.head_sha),pullRequests:g(r?.pull_requests),url:m(r?.html_url)??"",updatedAt:s,repositoryGithubId:m(t?.node_id),repositoryNameWithOwner:m(t?.full_name)??`${e.owner}/${e.repository}`,repositoryUrl:m(t?.html_url)??`https://github.com/${e.owner}/${e.repository}`,checkSuiteId:m(r?.check_suite_node_id)}:null}function w(e,t){let r=(0,d.normalizePipelineState)(e,t);return"SUCCESS"===r||"NEUTRAL"===r||"SKIPPED"===r?"IN_PROGRESS":r}function b(e,t){if(!e||!t)return null;try{let r=(0,i.compileRe2)(t,{flags:"i",label:"Jira branch regex"}).exec(e),a=(r?.[1]??r?.[0])?.trim();return a?a.toUpperCase():null}catch{return null}}e.s(["GitHubActionsNotificationsService",0,class{credentials;notifications;polling;workflowEvents;cache;pipelineStatus;timer;running;rerunRequested;constructor(e,t,r,i=!0,a,n=new s.GitHubCache,o=new c.GitHubPipelineStatusService){this.credentials=e,this.notifications=t,this.polling=r,this.workflowEvents=a,this.cache=n,this.pipelineStatus=o,this.timer=null,this.running=!1,this.rerunRequested=!1,this.polling.register({id:h,kind:"GITHUB_ACTIONS_NOTIFICATIONS",runtime:"SERVER",enabled:!1,cadenceSeconds:60,details:{mode:"DISABLED"}}),i&&queueMicrotask(()=>void this.tick())}async appConnection(){let e=await this.credentials.getJson(a.CREDENTIALS.githubAppSettings);return e?(0,n.githubAppConnectionSettings)(e):null}async recordWorkflowRunEvent(e,t){if(!this.workflowEvents||"completed"!==t.status)return;let i=await (0,r.getPrismaClient)(),[a,n]=await Promise.all([t.headBranch?i.worktree.findFirst({where:{branch:t.headBranch,missingAt:null,codebase:{repositoryId:e.id}},orderBy:{updatedAt:"desc"},select:{id:!0,folder:!0,branch:!0,baseBranchOverride:!0,headSha:!0,codebase:{select:{id:!0,folder:!0,agentId:!0,defaultBranch:!0,agent:{select:{id:!0,name:!0,hostname:!0}}}}}}):null,i.codebaseSettings.findUnique({where:{id:"default"}})]),s=b(t.headBranch,e.jiraBranchRegex??n?.defaultJiraBranchRegex??""),o=t.pullRequests[0]??null,l={repo:{id:e.id,name:e.name,owner:e.owner,url:`https://github.com/${e.owner}/${e.repository}`,canonicalOrigin:e.canonicalOrigin,displayOrigin:e.displayOrigin,defaultBranch:a?.codebase.defaultBranch??null},pipeline:{runId:t.id,workflowId:t.workflowId,name:t.name,displayTitle:t.displayTitle,status:t.status,conclusion:t.conclusion,headBranch:t.headBranch,headSha:t.headSha,pullRequests:t.pullRequests,url:t.url},...a?{worktree:{id:a.id,path:a.folder,branch:a.branch,baseBranch:a.baseBranchOverride??a.codebase.defaultBranch,headSha:a.headSha},codebase:{id:a.codebase.id,folder:a.codebase.folder,agentId:a.codebase.agentId},agent:a.codebase.agent}:{},...o?{pr:o}:{},...s?{ticket:{key:s}}:{}},u={cursorValue:`${t.id}:${t.runAttempt}:${t.conclusion??"none"}`};await this.workflowEvents.record({kind:"GITHUB_ACTIONS_RESULT",subjectKey:e.id,dedupeKey:`github-actions-trigger:${e.id}:${t.id}:${t.runAttempt}`,payload:{...l,...u,sessionData:l}});let c="success"===t.conclusion?"GITHUB_WORKFLOW_SUCCEEDED":t.conclusion&&p.has(t.conclusion)?"GITHUB_CHECK_FAILED":null;c&&await this.workflowEvents.record({kind:c,subjectKey:e.id,dedupeKey:`github-workflow-trigger:${c}:${e.id}:${t.id}:${t.runAttempt}`,payload:{...l,...u,sessionData:l}})}async observePipelineRun(e,t,r,i=!0){if(!t.repositoryGithubId||!t.headSha)return!1;let a="completed"===t.status,n=!!t.checkSuiteId;return await this.pipelineStatus.observeSnapshot({repositoryGithubId:t.repositoryGithubId,repositoryNameWithOwner:t.repositoryNameWithOwner,repositoryUrl:t.repositoryUrl,headSha:t.headSha,pipelines:[{id:t.id,name:t.name,status:(0,d.normalizePipelineState)(t.status,t.conclusion),url:t.url,checkSuiteId:t.checkSuiteId,workflowRunId:t.id,workflowId:t.workflowId,runAttempt:t.runAttempt,canRetry:a&&n&&i,retryUnavailableReason:a?n?i?null:"GITHUB_APP_NOT_CONFIGURED":"WORKFLOW_RUN_UNAVAILABLE":"NOT_COMPLETED",source:r,githubUpdatedAt:t.updatedAt}]}),!0}async observeEnhancedWebhook(e,t,r,i){let a={workflow_run:new Set(["requested","in_progress","completed"]),workflow_job:new Set(["queued","in_progress","completed"]),check_run:new Set(["created","rerequested","completed"]),check_suite:new Set(["requested","rerequested","in_progress","completed"]),status:new Set([null])};if(!a[t]?.has(r))return!1;let n=i.repository,s=m(n?.node_id),o="status"===t?m(i.sha):m((i[t]??{}).head_sha);if(!s||!o)return!1;let l=m(n?.full_name)??`${e.owner}/${e.repository}`,u=m(n?.html_url)??`https://github.com/${e.owner}/${e.repository}`;if("workflow_run"===t){let t=y(e,n,i.workflow_run);return!!t&&this.observePipelineRun(e,t,"WEBHOOK")}if("status"===t){let e,t=m(i.context);return!!t&&(await this.pipelineStatus.observeSnapshot({repositoryGithubId:s,repositoryNameWithOwner:l,repositoryUrl:u,headSha:o,pipelines:[{id:t,name:t,status:(0,d.normalizePipelineState)(m(i.state)),url:m(i.target_url),statusContext:t,source:"WEBHOOK",githubUpdatedAt:(e=m(i.updated_at)??m(i.created_at))?new Date(e):null}]}),!0)}if("check_suite"===t){let e=i.check_suite,t=m(e?.node_id);if(!e||!t)return!1;let r=e.app,a=m(e.updated_at)??m(e.completed_at)??m(e.started_at);return await this.pipelineStatus.observeSnapshot({repositoryGithubId:s,repositoryNameWithOwner:l,repositoryUrl:u,headSha:o,pipelines:[{id:t,name:m(r?.name)??"GitHub checks",status:(0,d.normalizePipelineState)(m(e.status),m(e.conclusion)),url:m(e.url),checkSuiteId:t,source:"WEBHOOK",githubUpdatedAt:a?new Date(a):null}]}),!0}if("check_run"===t){let e=i.check_run,t=e?.check_suite,r=m(t?.node_id),a=m(e?.node_id);if(!e||!r||!a)return!1;let n=m(e.completed_at)??m(e.started_at)??m(e.updated_at);return await this.pipelineStatus.observeSnapshot({repositoryGithubId:s,repositoryNameWithOwner:l,repositoryUrl:u,headSha:o,pipelines:[{id:a,name:m(e.name)??"GitHub check",status:w(m(e.status),m(e.conclusion)),url:m(e.details_url)??m(e.html_url),checkSuiteId:r,source:"WEBHOOK",githubUpdatedAt:n?new Date(n):null}]}),!0}let c=i.workflow_job,h=f(c?.run_id)?.toString()??null;if(!c||!h)return!1;let p=m(c.completed_at)??m(c.started_at)??m(c.created_at),g=p?new Date(p):null,b=Array.isArray(c.steps)?c.steps.flatMap(e=>{if(!e||"object"!=typeof e||Array.isArray(e))return[];let t=f(e.number);return t?[{number:t,name:m(e.name)??`Step ${t}`,status:(0,d.normalizePipelineState)(m(e.status),m(e.conclusion))}]:[]}):[],E={id:f(c.id)?.toString()??m(c.node_id)??"unknown",name:m(c.name)??"Workflow job",status:(0,d.normalizePipelineState)(m(c.status),m(c.conclusion)),url:m(c.html_url),canRetry:m(c.status)?.toLowerCase()==="completed",retryUnavailableReason:m(c.status)?.toLowerCase()==="completed"?null:"NOT_COMPLETED",steps:b,runAttempt:f(c.run_attempt)};return await this.pipelineStatus.observeSnapshot({repositoryGithubId:s,repositoryNameWithOwner:l,repositoryUrl:u,headSha:o,pipelines:[{id:h,name:m(c.workflow_name)??"GitHub Actions",status:w(m(c.status),m(c.conclusion)),url:m(c.html_url),workflowRunId:h,runAttempt:f(c.run_attempt),source:"WEBHOOK",githubUpdatedAt:g}]}),await this.pipelineStatus.observeJobs(s,h,[E],"WEBHOOK",g),!0}async recordWebhookTrigger(e,t,i,a,n){if(!this.workflowEvents)return!1;let s=n.repository??{},o=n.pull_request??{},l=n.review??{},u=n.comment??{},c=n.check_run??n.check_suite??{},d=null;if("pull_request"===t&&new Set(["opened","reopened","ready_for_review"]).has(i??"")?d="GITHUB_PR_STATE":"pull_request"===t&&"synchronize"===i?d="GITHUB_PR_SYNCHRONIZED":"pull_request"===t&&"closed"===i?d="GITHUB_PR_CLOSED":"pull_request"===t&&"labeled"===i?d="GITHUB_PR_LABEL":"pull_request_review"===t&&"submitted"===i&&m(l.state)?.toLowerCase()==="changes_requested"?d="GITHUB_REVIEW_CHANGES_REQUESTED":"pull_request_review"===t&&"submitted"===i&&m(l.state)?.toLowerCase()==="approved"?d="GITHUB_REVIEW_APPROVED":"pull_request_review_comment"===t&&"created"===i?d="GITHUB_REVIEW_COMMENT":("check_run"===t||"check_suite"===t)&&p.has(m(c.conclusion)?.toLowerCase()??"")?d="GITHUB_CHECK_FAILED":"push"===t&&m(n.ref)===`refs/heads/${m(s.default_branch)}`?d="GITHUB_PUSH_DEFAULT":"issue_comment"===t&&"created"===i&&(d="GITHUB_ISSUE_COMMAND"),!d)return!1;let h=u.user??{},g=Array.isArray(o.labels)?o.labels.flatMap(e=>{let t=e&&"object"==typeof e?m(e.name):null;return t?[t]:[]}):[],y=o.head,w=o.base,E=c.check_suite??n.check_suite??{},S=m(y?.ref),v=m(n.ref)?.replace(/^refs\/heads\//,"")??null,I=m(c.head_branch)??m(E.head_branch),A=S??v??I,k=await (0,r.getPrismaClient)(),_=await k.codebaseSettings.findUnique({where:{id:"default"}}),T=b(A,e.jiraBranchRegex??_?.defaultJiraBranchRegex??""),C=A?await k.worktree.findFirst({where:{branch:A,primary:!1,missingAt:null,codebase:{repositoryId:e.id}},orderBy:{updatedAt:"desc"},select:{id:!0,folder:!0,branch:!0,baseBranchOverride:!0,headSha:!0,pushStatus:!0,hasStagedChanges:!0,hasUnstagedChanges:!0,codebase:{select:{id:!0,folder:!0,agentId:!0,branch:!0,headSha:!0,defaultBranch:!0,agent:{select:{id:!0,name:!0,hostname:!0}}}}}}):null,R={repo:{id:e.id,name:e.name,owner:e.owner,url:m(s.html_url),canonicalOrigin:e.canonicalOrigin,displayOrigin:m(s.full_name)??e.displayOrigin,defaultBranch:m(s.default_branch)},pr:{number:f(o.number)??f(n.issue?.number),url:m(o.html_url),state:m(o.state)?.toUpperCase()??null,merged:!0===o.merged,labels:g,title:m(o.title),isDraft:!0===o.draft,headBranch:S,headSha:m(y?.sha),baseBranch:m(w?.ref),reviewDecision:m(l.state)?.toUpperCase()??null},pipeline:{checkSuiteId:f(c.id)?.toString()??null,status:m(c.status),conclusion:m(c.conclusion),headBranch:I,headSha:m(c.head_sha)??m(E.head_sha)},comment:{id:f(u.id)?.toString()??null,body:m(u.body)??"",author:{login:m(h.login)}},push:{ref:m(n.ref),before:m(n.before),after:m(n.after)},...C?{worktree:{id:C.id,path:C.folder,branch:C.branch,baseBranch:C.baseBranchOverride??C.codebase.defaultBranch,headSha:C.headSha,pushStatus:C.pushStatus,dirty:C.hasStagedChanges||C.hasUnstagedChanges},codebase:{id:C.codebase.id,folder:C.codebase.folder,agentId:C.codebase.agentId,branch:C.codebase.branch,headSha:C.codebase.headSha},agent:C.codebase.agent}:{},...T?{ticket:{key:T}}:{}};return await this.workflowEvents.record({kind:d,subjectKey:e.id,dedupeKey:`github-webhook-trigger:${a}:${d}`,payload:{...R,sessionData:R,cursorValue:`${a}:${d}`,webhook:{event:t,action:i,deliveryId:a}}}),!0}schedule(e){this.timer&&clearTimeout(this.timer);let t=1e3*Math.max(30,e);this.timer=setTimeout(()=>void this.tick(),t),this.timer.unref(),this.polling.schedule(h,new Date(Date.now()+t))}configurationChanged(){if(this.running){this.rerunRequested=!0;return}this.timer&&clearTimeout(this.timer),this.timer=null,queueMicrotask(()=>void this.tick())}async tick(){if(this.running)return;this.running=!0;let e=60;try{let t=await (0,r.getPrismaClient)(),[i,n,s,o,l]=await Promise.all([t.gitHubSettings.upsert({where:{id:"default"},create:{id:"default"},update:{}}),t.gitHubAppSettings.findUnique({where:{id:"default"}}),this.appConnection(),this.credentials.isConfigured(a.CREDENTIALS.githubPersonalAccessToken),this.credentials.isConfigured(a.CREDENTIALS.githubAppWebhookSecret)]);if(e=i.actionsNotificationPollIntervalSeconds,s?.webhookUrl&&n?.webhookConfiguredAt&&l)return void this.polling.configure(h,{enabled:!1,cadenceSeconds:e,details:{mode:"WEBHOOK"}});if(!o)return void this.polling.configure(h,{enabled:!1,cadenceSeconds:e,details:{mode:"DISABLED",reason:"GITHUB_TOKEN_REQUIRED"}});this.polling.configure(h,{enabled:!0,cadenceSeconds:e,details:{mode:"POLLING"}}),await this.polling.run(h,()=>this.pollRepositories(),e=>e)}catch{}finally{this.running=!1,this.rerunRequested?(this.rerunRequested=!1,queueMicrotask(()=>void this.tick())):this.schedule(e)}}async repositories(){return(await (await (0,r.getPrismaClient)()).codebaseRepository.findMany({orderBy:{name:"asc"},select:{id:!0,name:!0,canonicalOrigin:!0,displayOrigin:!0,jiraBranchRegex:!0}})).flatMap(e=>{let t=/^github\.com\/([^/]+)\/([^/]+)$/i.exec(e.canonicalOrigin.trim());return t?.[1]&&t[2]?[{id:e.id,name:e.name,owner:t[1],repository:t[2],canonicalOrigin:e.canonicalOrigin,displayOrigin:e.displayOrigin,jiraBranchRegex:e.jiraBranchRegex}]:[]})}async fetchRuns(e,t,r){let i=[];for(let a=1;;a+=1){let n,s=`${o.GITHUB_API_BASE_URL}/repos/${encodeURIComponent(e.owner)}/${encodeURIComponent(e.repository)}/actions/runs?per_page=100&page=${a}`,c=Date.now(),d=e=>this.cache.recordRestCall({authentication:"PAT",method:"GET",endpoint:s,operation:u.GITHUB_REST_OPERATIONS.actions.listWorkflowRunsForRepo,requestSource:"ACTIONS_NOTIFICATIONS",durationMs:Date.now()-c,...e}).catch(()=>void 0);try{n=await fetch(s,{headers:{accept:"application/vnd.github+json",authorization:`Bearer ${t}`,"user-agent":"ai-development-environment","x-github-api-version":"2022-11-28"},cache:"no-store"})}catch(t){let e=t instanceof Error?t.message:String(t);throw await d({error:e}),t}let h=await (0,l.observeGitHubRateLimit)("PAT",n),p=await n.json().catch(()=>null);if(!n.ok||!Array.isArray(p?.workflow_runs)){let t=p?.message||`GitHub returned HTTP ${n.status} while polling ${e.owner}/${e.repository}`;throw await d({statusCode:n.status,error:t,rateLimit:h}),Error(t)}await d({statusCode:n.status,rateLimit:h});let y=p.workflow_runs.flatMap(t=>{let r=f(t.id),i=f(t.workflow_id),a=m(t.updated_at),n=a?new Date(a):null,s=t.repository;return r&&i&&n&&Number.isFinite(n.getTime())?[{id:String(r),workflowId:String(i),runAttempt:f(t.run_attempt)??1,name:m(t.name)??"GitHub Actions",displayTitle:m(t.display_title)??m(t.name)??"Workflow run",status:m(t.status)?.toLowerCase()??"unknown",conclusion:m(t.conclusion)?.toLowerCase()??null,headBranch:m(t.head_branch),headSha:m(t.head_sha),pullRequests:g(t.pull_requests),url:m(t.html_url)??"",updatedAt:n,repositoryGithubId:m(s?.node_id),repositoryNameWithOwner:m(s?.full_name)??`${e.owner}/${e.repository}`,repositoryUrl:m(s?.html_url)??`https://github.com/${e.owner}/${e.repository}`,checkSuiteId:m(t.check_suite_node_id)}]:[]});if(i.push(...y),!r||p.workflow_runs.length<100||y.some(e=>e.updatedAt<=r))return i}}async worktreeContext(e,t,r){return r?e.worktree.findFirst({where:{branch:r,missingAt:null,codebase:{repositoryId:t}},orderBy:{updatedAt:"desc"},select:{id:!0,highlightColor:!0}}):null}async observeRun(e,r,i,a,n){var s;let o=new Date,l="success"===(s=i.conclusion)?"GITHUB_ACTIONS_SUCCEEDED":s&&p.has(s)?"GITHUB_ACTIONS_FAILED":null,u=await e.gitHubWorkflowRunObservation.findUnique({where:{codebaseRepositoryId_workflowRunId_runAttempt:{codebaseRepositoryId:r.id,workflowRunId:i.id,runAttempt:i.runAttempt}}});if(await e.gitHubWorkflowRunObservation.upsert({where:{codebaseRepositoryId_workflowRunId_runAttempt:{codebaseRepositoryId:r.id,workflowRunId:i.id,runAttempt:i.runAttempt}},create:{id:(0,t.randomUUID)(),codebaseRepositoryId:r.id,workflowRunId:i.id,runAttempt:i.runAttempt,workflowId:i.workflowId,status:i.status,conclusion:i.conclusion,githubUpdatedAt:i.updatedAt,source:a,lastObservedAt:o},update:{workflowId:i.workflowId,status:i.status,conclusion:i.conclusion,githubUpdatedAt:i.updatedAt,source:a,lastObservedAt:o}}),!(u?"completed"!==u.status||u.conclusion!==i.conclusion:n)||!l||"completed"!==i.status||u?.notifiedAt)return null;let c=await this.worktreeContext(e,r.id,i.headBranch),d=new URLSearchParams({repository:r.id});i.headBranch&&d.set("branch",i.headBranch),d.set("pipeline",i.workflowId);let h=await this.notifications.recordInTransaction(e,{dedupeKey:`github-actions:${r.id}:${i.id}:${i.runAttempt}`,typeKey:l,title:"GITHUB_ACTIONS_SUCCEEDED"===l?"GitHub Actions succeeded":"GitHub Actions failed",body:[r.name,i.name,i.headBranch].filter(e=>!!e).join(" · "),href:`/actions?${d.toString()}`,resourceKind:"GITHUB_WORKFLOW_RUN",resourceId:`${r.id}:${i.id}:${i.runAttempt}`,worktreeId:c?.id??null,highlightColor:c?.highlightColor??null});return await e.gitHubWorkflowRunObservation.update({where:{codebaseRepositoryId_workflowRunId_runAttempt:{codebaseRepositoryId:r.id,workflowRunId:i.id,runAttempt:i.runAttempt}},data:{notifiedAt:o}}),h}async pollRepository(e,t,i){let a=await (0,r.getPrismaClient)(),n=new Date,s=await a.gitHubActionsPollingState.findUnique({where:{codebaseRepositoryId:e.id}});await a.gitHubActionsPollingState.upsert({where:{codebaseRepositoryId:e.id},create:{codebaseRepositoryId:e.id,initializedAt:n,lastPollStartedAt:n},update:{lastPollStartedAt:n}});try{let r=await this.fetchRuns(e,t,s?s.lastPollSucceededAt??s.initializedAt:null),n=[];return await a.$transaction(async t=>{for(let i of r){let r=await this.observeRun(t,e,i,"POLL",!!(s&&i.updatedAt>(s.lastPollSucceededAt??s.initializedAt)));r&&n.push(r)}let i=new Date;await t.gitHubActionsPollingState.update({where:{codebaseRepositoryId:e.id},data:{lastPollCompletedAt:i,lastPollSucceededAt:i,lastError:null}})}),n.forEach(e=>this.notifications.created(e)),await Promise.allSettled(r.flatMap(t=>[this.observePipelineRun(e,t,"REST",i),this.recordWorkflowRunEvent(e,t)])),n.length}catch(t){throw await a.gitHubActionsPollingState.update({where:{codebaseRepositoryId:e.id},data:{lastPollCompletedAt:new Date,lastError:t instanceof Error?t.message:String(t)}}),t}}async pollRepositories(){let e=await this.credentials.getText(a.CREDENTIALS.githubPersonalAccessToken);if(!e)throw Error("GitHub personal access token is unavailable");let[t,i,n]=await Promise.all([this.repositories(),(await (0,r.getPrismaClient)()).gitHubAppSettings.findUnique({where:{id:"default"},select:{id:!0}}),this.credentials.isConfigured(a.CREDENTIALS.githubAppPrivateKey)]),s=!!(i&&n),o=await Promise.allSettled(t.map(t=>this.pollRepository(t,e,s))),l=o.filter(e=>"rejected"===e.status),u=o.reduce((e,t)=>e+("fulfilled"===t.status?t.value:0),0);if(await this.prune(),l.length===t.length&&t.length>0)throw l[0].reason;return{mode:"POLLING",repositories:t.length,failures:l.length,notificationsCreated:u}}async prune(){let e=new Date(Date.now()-2592e6),t=await (0,r.getPrismaClient)();await Promise.all([t.gitHubWorkflowRunObservation.deleteMany({where:{lastObservedAt:{lt:e}}}),t.gitHubWebhookDelivery.deleteMany({where:{receivedAt:{lt:e}}})])}async handleWebhook(e){var i,n;let s,o,l=await this.credentials.getText(a.CREDENTIALS.githubAppWebhookSecret);if(!l)throw Error("GitHub webhook is not configured");if(!e.signature?.startsWith("sha256="))throw Error("GitHub webhook signature is missing");if(i=`sha256=${(0,t.createHmac)("sha256",l).update(e.body).digest("hex")}`,n=e.signature,s=Buffer.from(i),o=Buffer.from(n),!(s.length===o.length&&(0,t.timingSafeEqual)(s,o)))throw Error("GitHub webhook signature is invalid");if(!e.deliveryId?.trim())throw Error("GitHub delivery ID is missing");let u=await (0,r.getPrismaClient)(),c=e.deliveryId.trim();try{await u.gitHubWebhookDelivery.create({data:{deliveryId:c,event:e.event??"unknown",outcome:"RECEIVED"}})}catch(t){if("object"==typeof t&&null!==t&&"code"in t&&"P2002"===t.code){if(0===(await u.gitHubWebhookDelivery.updateMany({where:{deliveryId:c,outcome:{notIn:["PROCESSED","IGNORED"]}},data:{event:e.event??"unknown",action:null,repositoryName:null,workflowRunId:null,outcome:"RECEIVED",error:null,receivedAt:new Date,processedAt:null}})).count)return{outcome:"DUPLICATE",notificationCreated:!1}}else throw t}let d=async(e,t=null)=>{await u.gitHubWebhookDelivery.update({where:{deliveryId:c},data:{outcome:e,error:t,processedAt:new Date}})};try{let t;try{t=JSON.parse(Buffer.from(e.body).toString("utf8"))}catch{throw Error("GitHub webhook payload is invalid JSON")}let r=m(t.action),i=t.repository,a=t.workflow_run;if(await u.gitHubWebhookDelivery.update({where:{deliveryId:c},data:{action:r,repositoryName:m(i?.full_name),workflowRunId:f(a?.id)?.toString()??null}}),"workflow_run"!==e.event||"completed"!==r){let[a,n]=await Promise.all([u.gitHubAppSettings.findUnique({where:{id:"default"}}),this.appConnection()]),s=t.installation;if(!a||!n||String(f(s?.id)??"")!==n.installationId)return await d("IGNORED","Installation does not match configured App"),{outcome:"IGNORED",notificationCreated:!1};let o=m(i?.full_name),l=o?(await this.repositories()).find(e=>`${e.owner}/${e.repository}`.toLowerCase()===o.toLowerCase()):null;if(!l)return await d("IGNORED","Repository is not registered"),{outcome:"IGNORED",notificationCreated:!1};let h=e.event??"unknown",[p,g]=await Promise.all([!!a.enhancedPipelineWebhooksEnabled&&this.observeEnhancedWebhook(l,h,r,t),this.recordWebhookTrigger(l,h,r,c,t)]),y=p||g;return await d(y?"PROCESSED":"IGNORED"),{outcome:y?"PROCESSED":"IGNORED",notificationCreated:!1}}let[n,s]=await Promise.all([u.gitHubAppSettings.findUnique({where:{id:"default"}}),this.appConnection()]),o=t.installation;if(!n||!s||String(f(o?.id)??"")!==s.installationId)return await d("IGNORED","Installation does not match configured App"),{outcome:"IGNORED",notificationCreated:!1};let l=m(i?.full_name),p=f(a?.id),g=f(a?.workflow_id),w=m(a?.updated_at);if(!l||!p||!g||!w)throw Error("GitHub workflow_run payload is incomplete");let b=(await this.repositories()).find(e=>`${e.owner}/${e.repository}`.toLowerCase()===l.toLowerCase());if(!b)return await d("IGNORED","Repository is not registered"),{outcome:"IGNORED",notificationCreated:!1};let E=y(b,i,a);if(!E)throw Error("GitHub workflow_run payload is incomplete");let S=null;return await u.$transaction(async e=>{S=await this.observeRun(e,b,E,"WEBHOOK",!0)}),this.notifications.created(S),await this.observePipelineRun(b,E,"WEBHOOK"),await this.recordWorkflowRunEvent(b,E),await d("PROCESSED"),this.polling.configure(h,{enabled:!1,details:{mode:"WEBHOOK",lastDeliveryId:c,lastDeliveryAt:new Date().toISOString()}}),this.prune().catch(()=>void 0),{outcome:"PROCESSED",notificationCreated:!!S}}catch(t){let e=t instanceof Error?t.message:String(t);throw await d("ERROR",e),t}}}])},963910,940045,e=>{"use strict";var t=e.i(666680),r=e.i(243783);e.i(805422);var i=e.i(661983);let a={LEGACY:0,GRAPHQL:1,REST:2,WEBHOOK:3,MUTATION:4},n=new Set(["CANCELLED","FAILURE","STALE","STARTUP_FAILURE","TIMED_OUT"]),s=new Set(["ACTION_REQUIRED","IN_PROGRESS","PENDING","QUEUED"]),o=new Set(["SUCCESS","NEUTRAL","SKIPPED"]);function l(e,t=null){return e.some(e=>"ERROR"===e)?"ERROR":e.some(e=>n.has(e))?"FAILURE":e.some(e=>s.has(e))?"PENDING":e.some(e=>"EXPECTED"===e)||"EXPECTED"===t?"EXPECTED":e.length>0&&e.every(e=>o.has(e))?"SUCCESS":0===e.length&&t?t:"NONE"}function u(e){return e.checkSuiteId?`CHECK_SUITE:${e.checkSuiteId}`:e.workflowRunId?`WORKFLOW_RUN:${e.workflowRunId}`:e.statusContext?`STATUS_CONTEXT:${e.statusContext}`:`PIPELINE:${e.id}`}function c(e){return s.has(e)?1:2*("NONE"!==e&&"EXPECTED"!==e)}function d(e,t,r){let i=e.runAttempt??0,n=t.runAttempt??0;if(n!==i)return n>i;let s=e.githubUpdatedAt?.getTime()??0,o=t.githubUpdatedAt?.getTime()??0;if(o!==s)return o>s;if("MUTATION"===e.source&&e.optimisticUntil&&e.optimisticUntil.getTime()>r.getTime())return"MUTATION"===t.source;let l="MUTATION"===e.source?a.LEGACY:a[e.source],u=a[t.source];if("MUTATION"!==e.source&&"MUTATION"!==t.source&&e.status&&t.status){let r=c(e.status),i=c(t.status);if(i!==r)return i>r}return u===l||u>l}function h(e){return"ACTION_REQUIRED"===e||"CANCELLED"===e||"ERROR"===e||"EXPECTED"===e||"FAILURE"===e||"IN_PROGRESS"===e||"NEUTRAL"===e||"PENDING"===e||"QUEUED"===e||"SKIPPED"===e||"STALE"===e||"STARTUP_FAILURE"===e||"SUCCESS"===e||"TIMED_OUT"===e||"NONE"===e}function p(e){return"ERROR"===e||"EXPECTED"===e||"FAILURE"===e||"PENDING"===e||"SUCCESS"===e||"NONE"===e}function m(e){try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function f(e){return"NONE"===e||"EXPECTED"===e?0:"ACTION_REQUIRED"===e||"PENDING"===e||"QUEUED"===e?1:"IN_PROGRESS"===e?2:3}function g(e){return"GRAPHQL"===e||"REST"===e||"WEBHOOK"===e||"MUTATION"===e?e:"LEGACY"}function y(e){return{id:e.githubPipelineId,name:e.name,status:h(e.status)?e.status:"NONE",url:e.url,checkSuiteId:e.checkSuiteId,canRetry:e.canRetry,retryUnavailableReason:e.retryUnavailableReason,jobs:m(e.jobsJson),workflowRunId:e.workflowRunId,workflowId:e.workflowId,runNumber:e.runNumber,runAttempt:e.runAttempt}}function w(e,t){return{...y(t),repositoryGithubId:e.repositoryGithubId,headSha:e.headSha,revision:e.revision,isCurrent:t.isCurrent}}function b(e){return{repositoryGithubId:e.repositoryGithubId,repositoryNameWithOwner:e.repositoryNameWithOwner,repositoryUrl:e.repositoryUrl,headSha:e.headSha,pipelineStatus:p(e.pipelineStatus)?e.pipelineStatus:"NONE",pipelines:e.records.filter(e=>e.isCurrent).map(y).sort((e,t)=>e.name.localeCompare(t.name)),revision:e.revision,updatedAt:e.updatedAt.toISOString()}}function E(e){return JSON.stringify({identityKey:e.identityKey,githubPipelineId:e.githubPipelineId,name:e.name,status:e.status,url:e.url,checkSuiteId:e.checkSuiteId,workflowRunId:e.workflowRunId,workflowId:e.workflowId,runNumber:e.runNumber,runAttempt:e.runAttempt,canRetry:e.canRetry,retryUnavailableReason:e.retryUnavailableReason,jobsJson:e.jobsJson,isCurrent:e.isCurrent})}function S(e){return JSON.stringify({repositoryNameWithOwner:e.repositoryNameWithOwner,repositoryUrl:e.repositoryUrl,pipelineStatus:e.pipelineStatus,records:e.records.map(E).sort((e,t)=>e.localeCompare(t))})}e.s(["GITHUB_PIPELINE_OPTIMISTIC_MS",0,12e4,"GITHUB_PIPELINE_RETENTION_MS",0,2592e6,"aggregatePipelineStatus",0,l,"isPipelineState",0,h,"isPipelineStatus",0,p,"normalizePipelineState",0,function(e,t){let r=(t||e||"NONE").toUpperCase();return h(r)?r:"REQUESTED"===r||"WAITING"===r?"QUEUED":"NONE"},"pipelineIdentity",0,u,"shouldReplacePipelineRecord",0,d],940045),e.s(["GitHubPipelineStatusService",0,class{lastPrunedAt=0;async snapshot(e){let t=await (0,r.getPrismaClient)(),i=await t.gitHubPipelineSnapshot.findUnique({where:{repositoryGithubId_headSha:{repositoryGithubId:e.repositoryGithubId.trim(),headSha:e.headSha.trim()}},include:{records:!0}});return i?b(i):null}async snapshots(e){let t=e.map(e=>({repositoryGithubId:e.repositoryGithubId.trim(),headSha:e.headSha.trim()})).filter(e=>e.repositoryGithubId&&e.headSha);if(0===t.length)return[];let i=await (0,r.getPrismaClient)();return(await i.gitHubPipelineSnapshot.findMany({where:{OR:t},include:{records:!0}})).map(b)}async records(e){let t=e.map(e=>({repositoryGithubId:e.repositoryGithubId.trim(),workflowRunId:e.workflowRunId.trim()})).filter(e=>e.repositoryGithubId&&e.workflowRunId);if(0===t.length)return[];let i=await (0,r.getPrismaClient)();return(await i.gitHubPipelineRecord.findMany({where:{OR:t.map(e=>({workflowRunId:e.workflowRunId,snapshot:{repositoryGithubId:e.repositoryGithubId}}))},include:{snapshot:{include:{records:!0}}}})).map(e=>w(e.snapshot,e))}async observeWorkflowRuns(e,t="REST",r=!0){let i=new Map;for(let t of e){if(!t.repositoryGithubId||!t.headSha)continue;let e=`${t.repositoryGithubId}\u0000${t.headSha}`,r=i.get(e)??[];r.push(t),i.set(e,r)}let a=new Map;for(let e of i.values()){let i=e[0];await this.observeSnapshot({repositoryGithubId:i.repositoryGithubId,repositoryNameWithOwner:i.repositoryNameWithOwner,repositoryUrl:i.repositoryUrl,headSha:i.headSha,pipelines:e.map(e=>(function(e,t,r=!0){return{id:e.id,name:e.name,status:e.status,url:e.url,checkSuiteId:e.checkSuiteId,workflowRunId:e.id,workflowId:e.workflowId,runNumber:e.runNumber,runAttempt:e.runAttempt,canRetry:e.canRetry,retryUnavailableReason:e.retryUnavailableReason,source:t,githubUpdatedAt:new Date(e.updatedAt),sourceFetchedAt:new Date,isCurrent:r}})(e,t,r))})}for(let t of(await this.records(e.map(e=>({repositoryGithubId:e.repositoryGithubId,workflowRunId:e.id})))))t.workflowRunId&&a.set(t.workflowRunId,t);return a}async observeJobs(e,t,i,a="REST",n=null){let s=await (0,r.getPrismaClient)(),o=await s.gitHubPipelineRecord.findFirst({where:{workflowRunId:t,...e?{snapshot:{repositoryGithubId:e}}:{}},include:{snapshot:!0},orderBy:[{runAttempt:"desc"},{sourceFetchedAt:"desc"}]});if(!o)return null;let u=i.filter(e=>null==e.runAttempt||null==o.runAttempt||e.runAttempt===o.runAttempt);if(i.length>0&&0===u.length)return w({...o.snapshot,records:[o]},o);let c=m(o.jobsJson),d=new Map(c.map(e=>[e.id,e])),p=u.map(e=>(function(e,t){if(!e)return t;let r=e.runAttempt??0,i=t.runAttempt??0;if(i!==r)return i>r?t:e;let a=f(e.status),n=f(t.status);return n<a?e:n===a&&t.steps.length<e.steps.length?{...t,steps:e.steps}:t})(d.get(e.id),e)),g="WEBHOOK"===a?[...new Map([...c,...p].map(e=>[e.id,e])).values()]:p,b=h(o.status)?o.status:"NONE",E="REST"===a&&u.length>0?l(u.map(e=>e.status),null):"NONE",S=("ERROR"===E||"FAILURE"===E||"SUCCESS"===E)&&o.snapshot.graphqlRollupStatus===E?E:b;return(await this.observeSnapshot({repositoryGithubId:o.snapshot.repositoryGithubId,repositoryNameWithOwner:o.snapshot.repositoryNameWithOwner,repositoryUrl:o.snapshot.repositoryUrl,headSha:o.snapshot.headSha,pipelines:[{...y(o),status:S,source:a,jobs:g,githubUpdatedAt:n??o.githubUpdatedAt,isCurrent:o.isCurrent}]})).changedPipeline}async optimisticByCheckSuite(e,t,r){return this.optimisticRecord({repositoryGithubId:e,checkSuiteId:t,workflowRunId:null},r)}async optimisticByWorkflowRun(e,t,r){return this.optimisticRecord({repositoryGithubId:e,checkSuiteId:null,workflowRunId:t},r)}async optimisticJobByCheckSuite(e,t,i){let a=await (0,r.getPrismaClient)(),n=await a.gitHubPipelineRecord.findFirst({where:{checkSuiteId:t,snapshot:{repositoryGithubId:e}},orderBy:[{runAttempt:"desc"},{sourceFetchedAt:"desc"}]});if(!n)return null;let s=m(n.jobsJson).map(e=>e.id===i?{...e,status:"QUEUED",canRetry:!1,retryUnavailableReason:"NOT_COMPLETED"}:e);return this.optimisticByCheckSuite(e,t,{status:"QUEUED",jobs:s})}async optimisticJobByWorkflowRun(e,t,i){let a=await (0,r.getPrismaClient)(),n=await a.gitHubPipelineRecord.findFirst({where:{workflowRunId:t,...e?{snapshot:{repositoryGithubId:e}}:{}},orderBy:[{runAttempt:"desc"},{sourceFetchedAt:"desc"}]});if(!n)return null;let s=m(n.jobsJson).map(e=>e.id===i?{...e,status:"QUEUED",canRetry:!1,retryUnavailableReason:"NOT_COMPLETED"}:e);return this.optimisticByWorkflowRun(e,t,{status:"QUEUED",jobs:s})}async optimisticRecord(e,t){let i=await (0,r.getPrismaClient)(),a=await i.gitHubPipelineRecord.findFirst({where:{...e.repositoryGithubId?{snapshot:{repositoryGithubId:e.repositoryGithubId}}:{},...e.checkSuiteId?{checkSuiteId:e.checkSuiteId}:{workflowRunId:e.workflowRunId}},include:{snapshot:!0},orderBy:[{runAttempt:"desc"},{sourceFetchedAt:"desc"}]});if(!a)return null;let n=new Date;return(await this.observeSnapshot({repositoryGithubId:a.snapshot.repositoryGithubId,repositoryNameWithOwner:a.snapshot.repositoryNameWithOwner,repositoryUrl:a.snapshot.repositoryUrl,headSha:a.snapshot.headSha,pipelines:[{...y(a),status:t.status,jobs:t.jobs,canRetry:!1,retryUnavailableReason:"NOT_COMPLETED",source:"MUTATION",githubUpdatedAt:a.githubUpdatedAt,sourceFetchedAt:n,optimisticUntil:new Date(n.getTime()+12e4),isCurrent:a.isCurrent}]})).changedPipeline}async observeSnapshot(e){let a=e.repositoryGithubId.trim(),n=e.headSha.trim();if(!a||!n)throw Error("GitHub repository ID and head SHA are required");let s=new Date,o=e.sourceFetchedAt??s,c=await (0,r.getPrismaClient)(),f=await c.$transaction(async r=>{let i=await r.gitHubPipelineSnapshot.upsert({where:{repositoryGithubId_headSha:{repositoryGithubId:a,headSha:n}},create:{id:(0,t.randomUUID)(),repositoryGithubId:a,repositoryNameWithOwner:e.repositoryNameWithOwner,repositoryUrl:e.repositoryUrl,headSha:n,pipelineStatus:"NONE",graphqlRollupStatus:null,revision:0,lastGraphqlSyncAt:null,lastObservedAt:s},update:{lastObservedAt:s},include:{records:!0}}),c=S(i),f=!!(e.completeGraphqlRollup&&(!i.lastGraphqlSyncAt||o.getTime()>=i.lastGraphqlSyncAt.getTime())),y=new Set,v=null;for(let a of e.pipelines){let e=u({id:a.id,checkSuiteId:a.checkSuiteId,workflowRunId:a.workflowRunId,statusContext:a.statusContext}),n=(await r.gitHubPipelineRecord.findMany({where:{snapshotId:i.id}})).filter(t=>t.identityKey===e||a.checkSuiteId&&t.checkSuiteId===a.checkSuiteId||a.workflowRunId&&t.workflowRunId===a.workflowRunId),l=n[0]??null;for(let e of n.slice(1))l&&d({runAttempt:l.runAttempt,githubUpdatedAt:l.githubUpdatedAt,source:g(l.source),optimisticUntil:l.optimisticUntil,status:h(l.status)?l.status:"NONE"},{runAttempt:e.runAttempt,githubUpdatedAt:e.githubUpdatedAt,source:g(e.source),status:h(e.status)?e.status:"NONE"},s)&&(l=e);for(let e of n)l&&e.id!==l.id&&(0===m(l.jobsJson).length&&m(e.jobsJson).length>0&&(l=await r.gitHubPipelineRecord.update({where:{id:l.id},data:{jobsJson:e.jobsJson}})),await r.gitHubPipelineRecord.delete({where:{id:e.id}}),v=l.id);let c=a.sourceFetchedAt??o,p=a.githubUpdatedAt??null,w=void 0===a.runAttempt?l?.runAttempt??null:a.runAttempt,b=void 0!==a.jobs?JSON.stringify(a.jobs):l&&(w??0)<=(l.runAttempt??0)?l.jobsJson:"[]",S=!!f||(!1===a.isCurrent?l?.isCurrent??!1:a.isCurrent??l?.isCurrent??!0);if(l){y.add(l.id);let t=E(l),i=d({runAttempt:l.runAttempt,githubUpdatedAt:l.githubUpdatedAt,source:g(l.source),optimisticUntil:l.optimisticUntil,status:h(l.status)?l.status:"NONE"},{runAttempt:w,githubUpdatedAt:p,source:a.source,status:a.status},s),n=!!(!i&&"MUTATION"===l.source&&l.optimisticUntil&&l.optimisticUntil.getTime()>s.getTime()&&"MUTATION"!==a.source);t!==E(l=await r.gitHubPipelineRecord.update({where:{id:l.id},data:i?{identityKey:e,githubPipelineId:a.id,name:a.name,status:a.status,url:void 0===a.url?l.url:a.url,checkSuiteId:void 0===a.checkSuiteId?l.checkSuiteId:a.checkSuiteId,workflowRunId:void 0===a.workflowRunId?l.workflowRunId:a.workflowRunId,workflowId:void 0===a.workflowId?l.workflowId:a.workflowId,runNumber:void 0===a.runNumber?l.runNumber:a.runNumber,runAttempt:w,canRetry:void 0===a.canRetry?l.canRetry:a.canRetry,retryUnavailableReason:void 0===a.retryUnavailableReason?l.retryUnavailableReason:a.retryUnavailableReason,jobsJson:b,source:a.source,githubUpdatedAt:p,sourceFetchedAt:c,lastObservedAt:s,optimisticUntil:void 0===a.optimisticUntil?l.optimisticUntil:a.optimisticUntil,isCurrent:S}:{lastObservedAt:s,...void 0!==a.jobs&&!n?{jobsJson:b}:{},...f?{isCurrent:!0}:{}}}))&&(v=l.id)}else v=(l=await r.gitHubPipelineRecord.create({data:{id:(0,t.randomUUID)(),snapshotId:i.id,identityKey:e,githubPipelineId:a.id,name:a.name,status:a.status,url:a.url??null,checkSuiteId:a.checkSuiteId??null,workflowRunId:a.workflowRunId??null,workflowId:a.workflowId??null,runNumber:a.runNumber??null,runAttempt:w,canRetry:a.canRetry??!1,retryUnavailableReason:a.retryUnavailableReason??null,jobsJson:b,source:a.source,githubUpdatedAt:p,sourceFetchedAt:c,lastObservedAt:s,optimisticUntil:a.optimisticUntil??null,isCurrent:S}})).id;y.add(l.id)}if(f)for(let e of(await r.gitHubPipelineRecord.findMany({where:{snapshotId:i.id,isCurrent:!0}})))!y.has(e.id)&&e.sourceFetchedAt.getTime()<=o.getTime()&&(!e.optimisticUntil||e.optimisticUntil.getTime()<=s.getTime())&&(await r.gitHubPipelineRecord.update({where:{id:e.id},data:{isCurrent:!1}}),v??=e.id);let I=await r.gitHubPipelineRecord.findMany({where:{snapshotId:i.id}}),A=f?e.graphqlRollupStatus??null:i.graphqlRollupStatus,k=l(I.filter(e=>e.isCurrent).map(e=>h(e.status)?e.status:"NONE"),A&&p(A)?A:null),_=c!==S(i=await r.gitHubPipelineSnapshot.update({where:{id:i.id},data:{repositoryNameWithOwner:e.repositoryNameWithOwner,repositoryUrl:e.repositoryUrl,pipelineStatus:k,graphqlRollupStatus:A,lastGraphqlSyncAt:f?o:i.lastGraphqlSyncAt,lastObservedAt:s},include:{records:!0}}))||null!==v;_&&(i=await r.gitHubPipelineSnapshot.update({where:{id:i.id},data:{revision:{increment:1}},include:{records:!0}}));let T=i,C=v?T.records.find(e=>e.id===v)??null:null;return{changed:_,change:{snapshot:b(T),changedPipeline:C?w(T,C):null}}});return f.changed&&i.agentEventBus.publish(i.GITHUB_PIPELINE_STATUS_CHANGED_TOPIC,{githubPipelineStatusChanged:f.change}),this.pruneIfNeeded().catch(()=>void 0),f.change}subscribe(){return i.agentEventBus.iterate(i.GITHUB_PIPELINE_STATUS_CHANGED_TOPIC)}async pruneIfNeeded(){let e=Date.now();if(e-this.lastPrunedAt<864e5)return;this.lastPrunedAt=e;let t=await (0,r.getPrismaClient)();await t.gitHubPipelineSnapshot.deleteMany({where:{lastObservedAt:{lt:new Date(e-2592e6)}}})}}],963910)},616204,334416,919412,407188,e=>{"use strict";var t=e.i(243783);function r(e){if(null===e||!/^\d+$/.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null}function i(e){let t=r(e.get("x-ratelimit-limit")),i=r(e.get("x-ratelimit-remaining")),a=r(e.get("x-ratelimit-used")),n=r(e.get("x-ratelimit-reset")),s=e.get("x-ratelimit-resource")?.trim()??"";if(null===t||null===i||null===a||null===n||!s)return null;let o=new Date(1e3*n);return Number.isFinite(o.getTime())?{limit:t,remaining:i,used:a,resetAt:o,resource:s}:null}async function a(e,r){let a=i(r.headers);if(!a)return null;try{let r=await (0,t.getPrismaClient)(),i=`${e}:${a.resource}`,n=new Date;await r.gitHubRateLimitSnapshot.upsert({where:{authentication_resource:{authentication:e,resource:a.resource}},create:{id:i,authentication:e,observedAt:n,...a},update:{observedAt:n,...a}})}catch{}return a}async function n(){let e=await (0,t.getPrismaClient)();return(await e.gitHubRateLimitSnapshot.findMany({orderBy:[{resource:"asc"},{authentication:"asc"}]})).map(e=>({authentication:e.authentication,resource:e.resource,limit:e.limit,remaining:e.remaining,used:e.used,resetAt:e.resetAt.toISOString(),observedAt:e.observedAt.toISOString()}))}e.s(["listGitHubRateLimitSnapshots",0,n,"observeGitHubRateLimit",0,a,"parseGitHubRateLimitHeaders",0,i],616204),e.s(["GITHUB_REST_OPERATIONS",0,{actions:{cancelWorkflowRun:"actions.cancelWorkflowRun",dispatchWorkflow:"actions.dispatchWorkflow",forceCancelWorkflowRun:"actions.forceCancelWorkflowRun",getJobForWorkflowRun:"actions.getJobForWorkflowRun",getWorkflowRun:"actions.getWorkflowRun",getWorkflowRunAttempt:"actions.getWorkflowRunAttempt",listJobsForWorkflowRun:"actions.listJobsForWorkflowRun",listJobsForWorkflowRunAttempt:"actions.listJobsForWorkflowRunAttempt",listRepoWorkflows:"actions.listRepoWorkflows",listWorkflowRuns:"actions.listWorkflowRuns",listWorkflowRunsForRepo:"actions.listWorkflowRunsForRepo",reRunJobForWorkflowRun:"actions.reRunJobForWorkflowRun",reRunWorkflow:"actions.reRunWorkflow",reRunWorkflowFailedJobs:"actions.reRunWorkflowFailedJobs"},apps:{createInstallationAccessToken:"apps.createInstallationAccessToken",getAuthenticated:"apps.getAuthenticated",getInstallation:"apps.getInstallation",updateWebhookConfigForApp:"apps.updateWebhookConfigForApp"},repos:{listPullRequestsAssociatedWithCommit:"repos.listPullRequestsAssociatedWithCommit"},users:{listEmailsForAuthenticatedUser:"users.listEmailsForAuthenticatedUser"}}],334416);var s=e.i(666680);let o=/^[_A-Za-z][_0-9A-Za-z]*$/,l=new Map([["GitHubWorktreePullRequestStatuses",60]]),u=[{window:"5m",milliseconds:3e5},{window:"10m",milliseconds:6e5},{window:"1h",milliseconds:36e5},{window:"24h",milliseconds:864e5}];function c(e){return JSON.stringify(function e(t){return Array.isArray(t)?t.map(e):t&&"object"==typeof t?Object.fromEntries(Object.keys(t).sort().map(r=>[r,e(t[r])])):t}(e))}let d=/(?:authorization|password|private.?key|secret|token)$/i;function h(e,t=""){return d.test(t)?"[REDACTED]":Array.isArray(e)?e.map(e=>h(e)):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,h(t,e)])):e}function p(e){try{return JSON.parse(e)}catch{return null}}function m(e){return e&&"object"==typeof e?{statusCode:"number"==typeof e.statusCode?e.statusCode:null,rateLimit:e.rateLimit&&"object"==typeof e.rateLimit?e.rateLimit:null}:{statusCode:null,rateLimit:null}}e.s(["GitHubCache",0,class{recordCallLogs;inFlight;cacheWrites;cacheGeneration;lastPrunedAt;constructor(e="true"!==process.env.GITHUB_CACHE_LOGGING_DISABLED){this.recordCallLogs=e,this.inFlight=new Map,this.cacheWrites=new Set,this.cacheGeneration=0,this.lastPrunedAt=0}cacheKey(e){return(0,s.createHash)("sha256").update(c({authentication:e.authentication,endpoint:e.endpoint,query:e.normalizedQuery,variables:e.variables})).digest("hex")}inFlightKey(e,t,r){return[r,e,!0===t.force?"force":"normal",!1===t.allowStaleOnError?"strict":"stale"].join(":")}async defaultTtlSeconds(){let e=await (0,t.getPrismaClient)();return(await e.gitHubSettings.upsert({where:{id:"default"},create:{id:"default",cacheTtlSeconds:300},update:{}})).cacheTtlSeconds}async effectiveTtlSeconds(e){let r=await (0,t.getPrismaClient)(),[i,a]=await Promise.all([r.gitHubGraphqlCacheTtlOverride.findUnique({where:{operation:e}}),this.defaultTtlSeconds()]);return i?.ttlSeconds??a}async query(e){let r=this.cacheGeneration,i=await (0,t.getPrismaClient)(),a=this.cacheKey(e),n=this.inFlightKey(a,e,r),o=Date.now(),[l,u,d]=await Promise.all([i.gitHubGraphqlCacheEntry.findUnique({where:{cacheKey:a}}),this.effectiveTtlSeconds(e.operation),i.gitHubRateLimitSnapshot.findUnique({where:{authentication_resource:{authentication:e.authentication,resource:"graphql"}}})]);if(r!==this.cacheGeneration)return this.query(e);let h=null!==l&&Date.now()-l.fetchedAt.getTime()<1e3*u;if(!e.force&&h)return(await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"CACHE",durationMs:Date.now()-o,pointCost:0,pointsAvoided:l.pointCost??0}).catch(()=>void 0),r!==this.cacheGeneration)?this.query(e):{data:p(l.responseJson),source:"CACHE",stale:!1,fetchedAt:l.fetchedAt,entryId:l.id,pointCost:l.pointCost};let f=this.inFlight.get(n);if(f){let t=await f;return r!==this.cacheGeneration||(await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"CACHE",durationMs:Date.now()-o,pointCost:0,pointsAvoided:t.pointCost??0}).catch(()=>void 0),r!==this.cacheGeneration)?this.query(e):{...t,source:"CACHE"}}if(d?.remaining===0&&d.resetAt.getTime()>Date.now()){let t=`GitHub GraphQL rate limit is exhausted until ${d.resetAt.toISOString()}`,i=null!==l&&!1!==e.allowStaleOnError;if(await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"ERROR",durationMs:Date.now()-o,error:t,servedStale:i,pointCost:0,pointsAvoided:i?l.pointCost??0:0,rateLimit:{limit:d.limit,remaining:d.remaining,used:d.used,resetAt:d.resetAt,resource:d.resource}}).catch(()=>void 0),r!==this.cacheGeneration)return this.query(e);if(i)return{data:p(l.responseJson),source:"ERROR",stale:!0,fetchedAt:l.fetchedAt,entryId:l.id,pointCost:l.pointCost};throw Error(t)}let g=(async()=>{try{let t=await e.fetcher(),n=new Date,l=null;if(r===this.cacheGeneration){let r=i.gitHubGraphqlCacheEntry.upsert({where:{cacheKey:a},create:{id:(0,s.randomUUID)(),cacheKey:a,authentication:e.authentication,endpoint:e.endpoint,operation:e.operation,query:e.query,variablesJson:c(e.variables),responseJson:JSON.stringify(t.data),fetchedAt:n,pointCost:t.pointCost},update:{operation:e.operation,query:e.query,variablesJson:c(e.variables),responseJson:JSON.stringify(t.data),fetchedAt:n,pointCost:t.pointCost}});this.cacheWrites.add(r);try{l=await r}finally{this.cacheWrites.delete(r)}}return await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"LIVE",durationMs:Date.now()-o,statusCode:t.statusCode,pointCost:t.pointCost,rateLimit:t.rateLimit}).catch(()=>void 0),{data:t.data,source:"LIVE",stale:!1,fetchedAt:n,entryId:r===this.cacheGeneration?l?.id??null:null,pointCost:t.pointCost}}catch(a){let t=m(a),i=r===this.cacheGeneration&&null!==l&&!1!==e.allowStaleOnError;if(await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"ERROR",durationMs:Date.now()-o,statusCode:t.statusCode,error:a instanceof Error?a.message:String(a),servedStale:i,pointsAvoided:i?l?.pointCost??0:0,rateLimit:t.rateLimit}).catch(()=>void 0),r!==this.cacheGeneration)throw a;if(i)return{data:p(l.responseJson),source:"ERROR",stale:!0,fetchedAt:l.fetchedAt,entryId:l.id,pointCost:l.pointCost};throw a}})();this.inFlight.set(n,g);try{return await g}finally{this.inFlight.get(n)===g&&this.inFlight.delete(n)}}async mutation(e){let t,r=Date.now();try{t=await e.fetcher()}catch(i){let t=m(i);throw await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"ERROR",durationMs:Date.now()-r,statusCode:t.statusCode,error:i instanceof Error?i.message:String(i),rateLimit:t.rateLimit}).catch(()=>void 0),i}return await this.clear(),await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"LIVE",durationMs:Date.now()-r,statusCode:t.statusCode,pointCost:null,rateLimit:t.rateLimit}).catch(()=>void 0),t.data}async updateTtl(e,r){if(!Number.isInteger(e)||e<1||e>1440)throw Error("Cache TTL must be an integer from 1 to 1440 minutes");let i=await (0,t.getPrismaClient)();return await i.gitHubSettings.upsert({where:{id:"default"},create:{id:"default",cacheTtlSeconds:60*e},update:{cacheTtlSeconds:60*e}}),r()}async ttlOverrides(){let e=await (0,t.getPrismaClient)();return(await e.gitHubGraphqlCacheTtlOverride.findMany({orderBy:{operation:"asc"}})).map(e=>({operation:e.operation,ttlSeconds:e.ttlSeconds,builtIn:l.has(e.operation),createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString()}))}async cacheableOperations(){let e=await (0,t.getPrismaClient)(),[r,i]=await Promise.all([e.gitHubGraphqlCacheTtlOverride.findMany({select:{operation:!0}}),e.gitHubGraphqlCacheEntry.findMany({distinct:["operation"],select:{operation:!0}})]);return[...new Set([...l.keys(),...r.map(({operation:e})=>e),...i.map(({operation:e})=>e)])].sort((e,t)=>e.localeCompare(t))}async saveTtlOverride(e,r){let i=e.trim();if(!o.test(i))throw Error("Operation must be a valid GraphQL operation name");if(!Number.isInteger(r)||r<1||r>86400)throw Error("Cache TTL must be an integer from 1 to 86400 seconds");let a=await (0,t.getPrismaClient)(),n=await a.gitHubGraphqlCacheTtlOverride.upsert({where:{operation:i},create:{operation:i,ttlSeconds:r},update:{ttlSeconds:r}});return{operation:n.operation,ttlSeconds:n.ttlSeconds,builtIn:l.has(n.operation),createdAt:n.createdAt.toISOString(),updatedAt:n.updatedAt.toISOString()}}async deleteTtlOverride(e){let r=e.trim();if(l.has(r))throw Error("Built-in cache TTL overrides cannot be deleted");let i=await (0,t.getPrismaClient)();return(await i.gitHubGraphqlCacheTtlOverride.deleteMany({where:{operation:r}})).count>0}async recordRestCall(e){let t=e.endpoint,r={};try{let i=new URL(e.endpoint);t=i.pathname,r={path:i.pathname,query:Object.fromEntries(i.searchParams)}}catch{r={endpoint:e.endpoint}}await this.log({authentication:e.authentication,apiType:"REST",method:e.method.toUpperCase(),endpoint:e.endpoint,operation:e.operation,requestSource:e.requestSource,requestSummary:`${e.method.toUpperCase()} ${t}`,variables:r,source:e.error?"ERROR":"LIVE",durationMs:e.durationMs,statusCode:e.statusCode,error:e.error,pointCost:1,rateLimit:e.rateLimit})}async recordGraphqlTransportCall(e){await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,requestSource:e.requestSource,source:e.error?"ERROR":"LIVE",durationMs:e.durationMs,statusCode:e.statusCode,error:e.error,rateLimit:e.rateLimit})}async clear(){let{cacheWrites:e}=this.beginInvalidation();await Promise.allSettled(e);let r=await (0,t.getPrismaClient)();return await r.gitHubGraphqlCacheEntry.deleteMany(),!0}async clearForCredentialChange(e){let{cacheWrites:r,inFlight:i}=this.beginInvalidation();await Promise.allSettled(r);let a=await (0,t.getPrismaClient)();return await a.gitHubGraphqlCacheEntry.deleteMany(),await Promise.allSettled(i),await a.gitHubRateLimitSnapshot.deleteMany({where:{authentication:e}}),!0}async clearCalls(){let e=await (0,t.getPrismaClient)();return await e.gitHubApiCallLog.deleteMany(),!0}async delete(e){let r=await (0,t.getPrismaClient)();return(await r.gitHubGraphqlCacheEntry.deleteMany({where:{id:e}})).count>0}async entries(e=50,r=0){let i=this.pagination(e,r),a=await (0,t.getPrismaClient)(),[n,s,o,l]=await Promise.all([a.gitHubGraphqlCacheEntry.findMany({take:i.limit,skip:i.offset,orderBy:{fetchedAt:"desc"}}),a.gitHubGraphqlCacheEntry.count(),this.defaultTtlSeconds(),a.gitHubGraphqlCacheTtlOverride.findMany({select:{operation:!0,ttlSeconds:!0}})]),u=new Map(l.map(({operation:e,ttlSeconds:t})=>[e,t]));return{...i,total:s,items:n.map(e=>this.entryView(e,u.get(e.operation)??o))}}async entry(e){let r=await (0,t.getPrismaClient)(),i=await r.gitHubGraphqlCacheEntry.findUnique({where:{id:e}});if(!i)return null;let a=await this.effectiveTtlSeconds(i.operation);return{...this.entryView(i,a),query:i.query,variables:p(i.variablesJson),response:p(i.responseJson)}}async calls(e=50,r=0,i={}){let a=this.pagination(e,r);await this.pruneLogs();let n=await (0,t.getPrismaClient)(),s={...i.apiType?{apiType:i.apiType}:{},...i.requestSource?{requestSource:i.requestSource}:{},...i.source?{source:i.source}:{}},[o,l]=await Promise.all([n.gitHubApiCallLog.findMany({where:s,take:a.limit,skip:a.offset,orderBy:{createdAt:"desc"}}),n.gitHubApiCallLog.count({where:s})]);return{...a,total:l,items:o.map(e=>({id:e.id,authentication:e.authentication,apiType:e.apiType,method:e.method,endpoint:e.endpoint,operation:e.operation,requestSource:e.requestSource,requestSummary:e.requestSummary,variables:p(e.variablesJson),source:e.source,durationMs:e.durationMs,statusCode:e.statusCode,error:e.error,servedStale:e.servedStale,pointCost:e.pointCost,pointsAvoided:e.pointsAvoided,rateLimitLimit:e.rateLimitLimit,rateLimitRemaining:e.rateLimitRemaining,rateLimitUsed:e.rateLimitUsed,rateLimitResetAt:e.rateLimitResetAt?.toISOString()??null,rateLimitResource:e.rateLimitResource,createdAt:e.createdAt.toISOString()}))}}async metrics(){await this.pruneLogs();let e=await (0,t.getPrismaClient)(),r=Date.now(),i=await e.gitHubApiCallLog.findMany({where:{createdAt:{gte:new Date(r-u.at(-1).milliseconds)}},orderBy:{createdAt:"asc"}}),a=u.map(e=>this.metricWindow(e.window,i.filter(t=>t.createdAt.getTime()>=r-e.milliseconds)));return{windows:a,apiTypes:["GRAPHQL","REST"].map(e=>({apiType:e,windows:u.map(t=>this.metricWindow(t.window,i.filter(i=>i.apiType===e&&i.createdAt.getTime()>=r-t.milliseconds)))})),operations:[...new Set(i.map(e=>e.operation))].sort().map(e=>({operation:e,windows:u.map(t=>this.metricWindow(t.window,i.filter(i=>i.operation===e&&i.createdAt.getTime()>=r-t.milliseconds)))})),requestSources:[...new Set(i.map(e=>e.requestSource))].sort().map(e=>({requestSource:e,windows:u.map(t=>this.metricWindow(t.window,i.filter(i=>i.requestSource===e&&i.createdAt.getTime()>=r-t.milliseconds)))}))}}entryView(e,t){return{id:e.id,authentication:e.authentication,operation:e.operation,endpoint:e.endpoint,fetchedAt:e.fetchedAt.toISOString(),pointCost:e.pointCost,stale:Date.now()-e.fetchedAt.getTime()>=1e3*t}}metricWindow(e,t){let r=t.length;return{window:e,total:r,live:t.filter(e=>"LIVE"===e.source).length,cache:t.filter(e=>"CACHE"===e.source).length,errors:t.filter(e=>"ERROR"===e.source).length,averageMs:0===r?0:Math.round(t.reduce((e,t)=>e+t.durationMs,0)/r),pointsUsed:t.reduce((e,t)=>e+Math.max(0,t.pointCost??0),0),pointsAvoided:t.reduce((e,t)=>e+Math.max(0,t.pointsAvoided),0)}}pagination(e,t){if(!Number.isInteger(e)||e<1||e>100)throw Error("limit must be an integer from 1 to 100");if(!Number.isInteger(t)||t<0)throw Error("offset must be a non-negative integer");return{limit:e,offset:t}}beginInvalidation(){let e=[...this.cacheWrites],t=[...new Set(this.inFlight.values())];return this.cacheGeneration+=1,this.inFlight.clear(),{cacheWrites:e,inFlight:t}}graphqlContext(e){let t=h(e.variables);return{apiType:"GRAPHQL",method:"POST",endpoint:e.endpoint,requestSource:e.requestSource,requestSummary:function(e){if(!e||"object"!=typeof e||Array.isArray(e))return"No variables";let t=Object.entries(e);return t.length?t.map(([e,t])=>{let r=("string"==typeof t?t:JSON.stringify(t))??String(t);return`${e}=${r.length>120?`${r.slice(0,117)}…`:r}`}).join(" · "):"No variables"}(t),variables:t}}async log(e){if(!this.recordCallLogs)return;await this.pruneLogs();let r=await (0,t.getPrismaClient)();await r.gitHubApiCallLog.create({data:{id:(0,s.randomUUID)(),authentication:e.authentication,apiType:e.apiType,method:e.method,endpoint:e.endpoint,operation:e.operation,requestSource:e.requestSource,requestSummary:e.requestSummary,variablesJson:c(h(e.variables)),source:e.source,durationMs:Math.max(0,Math.round(e.durationMs)),statusCode:e.statusCode??null,error:e.error?.slice(0,2e3)??null,servedStale:e.servedStale??!1,pointCost:e.pointCost??null,pointsAvoided:Math.max(0,e.pointsAvoided??0),rateLimitLimit:e.rateLimit?.limit??null,rateLimitRemaining:e.rateLimit?.remaining??null,rateLimitUsed:e.rateLimit?.used??null,rateLimitResetAt:e.rateLimit?.resetAt??null,rateLimitResource:e.rateLimit?.resource??null}})}async pruneLogs(){let e=Date.now();if(e-this.lastPrunedAt<36e5)return;this.lastPrunedAt=e;let r=await (0,t.getPrismaClient)();await r.gitHubApiCallLog.deleteMany({where:{createdAt:{lt:new Date(e-2592e6)}}})}}],919412);let f=(process.env.GITHUB_API_BASE_URL||"https://api.github.com").replace(/\/+$/,""),g=process.env.GITHUB_GRAPHQL_URL||`${f}/graphql`;e.s(["GITHUB_API_BASE_URL",0,f,"GITHUB_GRAPHQL_URL",0,g],407188)},112627,685155,e=>{"use strict";var t=e.i(666680),r=e.i(243783),i=e.i(483291);e.i(582482);var a=e.i(318905),n=e.i(91022),s=e.i(783396),o=e.i(397554),l=e.i(827957),u=e.i(616204),c=e.i(334416);class d extends Error{code;githubRequestId;statusCode;rateLimit;constructor(e,t,r=null,i=null,a=null){super(t),this.code=e,this.githubRequestId=r,this.statusCode=i,this.rateLimit=a,this.name="GitHubAppError"}}let h=new Map,p=new Map;function m(e,t,r){let i=e.trim();if(!/^[1-9]\d*$/.test(i))throw new d(r,`${t} must be a positive integer`);return i}function f(e){let{privateKeyPkcs8:r,keyFingerprint:i}=function(e){try{let r=(0,t.createPrivateKey)({key:e.trim(),format:"pem"});if("rsa"!==r.asymmetricKeyType)throw Error("The key is not RSA");let i=r.export({format:"pem",type:"pkcs8"}).toString(),a=(0,t.createPublicKey)(r).export({format:"der",type:"spki"}),n=`SHA256:${(0,t.createHash)("sha256").update(a).digest("base64url")}`;return{key:r,privateKeyPkcs8:i,keyFingerprint:n}}catch{throw new d("INVALID_PRIVATE_KEY","The GitHub App private key is not a valid RSA PEM")}}(e.privateKey);return{...e,appId:m(e.appId,"GitHub App ID","INVALID_APP_ID"),installationId:m(e.installationId,"GitHub installation ID","INVALID_INSTALLATION_ID"),privateKeyPkcs8:r,keyFingerprint:i}}async function g(e){try{let t=await (0,o.importPKCS8)(e.privateKeyPkcs8,"RS256"),r=Math.floor(Date.now()/1e3);return await new l.SignJWT({}).setProtectedHeader({alg:"RS256",typ:"JWT"}).setIssuer(e.appId).setIssuedAt(r-60).setExpirationTime(r+540).sign(t)}catch{throw new d("INVALID_PRIVATE_KEY","The GitHub App private key could not sign an App JWT")}}function y(e){return`${e.appId}:${e.installationId}:${e.keyFingerprint}`}function w(e){return{accept:"application/vnd.github+json",authorization:e,"user-agent":"ai-development-environment","x-github-api-version":"2022-11-28"}}async function b(e,t,r,i,a){let n,s=Date.now(),o=(t.method??"GET").toUpperCase(),l=e===i?.graphqlUrl&&"string"==typeof t.body?t.body:null;try{n=await fetch(e,{...t,cache:"no-store"})}catch{throw i?.requestObserver&&await Promise.resolve(i.requestObserver({url:e,method:o,operation:r,requestSource:a,body:l,durationMs:Date.now()-s,statusCode:null,error:"GitHub could not be reached",rateLimit:null})).catch(()=>void 0),new d("GITHUB_APP_REQUEST_FAILED","GitHub could not be reached")}return i?.responseObserver&&await Promise.resolve(i.responseObserver(n)).catch(()=>void 0),i?.requestObserver&&await Promise.resolve(i.requestObserver({url:e,method:o,operation:r,requestSource:a,body:l,durationMs:Date.now()-s,statusCode:n.status,error:n.ok?null:`GitHub returned HTTP ${n.status}`,rateLimit:(0,u.parseGitHubRateLimitHeaders)(n.headers)})).catch(()=>void 0),n}async function E(e){try{return await e.json()}catch{return null}}function S(e){return e.headers.get("x-github-request-id")}function v(e,t,r=[]){let i=`GitHub returned HTTP ${t}`;for(let t of(e&&"object"==typeof e&&"message"in e&&"string"==typeof e.message&&(i=e.message),r))t&&(i=i.split(t).join("[REDACTED]"));return i}async function I(e,t){let r=await b(`${e.apiBaseUrl}/app/installations/${e.installationId}`,{headers:w(`Bearer ${t}`)},c.GITHUB_REST_OPERATIONS.apps.getInstallation,e,"GITHUB_SETTINGS"),i=await E(r),a=S(r);if(401===r.status)throw new d("GITHUB_APP_UNAUTHORIZED","GitHub rejected the App ID or private key",a);if(404===r.status)throw new d("INSTALLATION_NOT_FOUND","The GitHub App installation was not found",a);if(!r.ok||!i||"object"!=typeof i)throw new d("GITHUB_APP_REQUEST_FAILED",v(i,r.status,[t,e.privateKey,e.privateKeyPkcs8]),a);if(String(i.app_id)!==e.appId)throw new d("APP_INSTALLATION_MISMATCH","The installation does not belong to the configured GitHub App",a);return i}async function A(e,t){let r=await b(`${e.apiBaseUrl}/app`,{headers:w(`Bearer ${t}`)},c.GITHUB_REST_OPERATIONS.apps.getAuthenticated,e,"GITHUB_SETTINGS"),i=await E(r),a=S(r);if(401===r.status)throw new d("GITHUB_APP_UNAUTHORIZED","GitHub rejected the App ID or private key",a);if(!r.ok||!i||"object"!=typeof i)throw new d("GITHUB_APP_REQUEST_FAILED",v(i,r.status,[t,e.privateKey,e.privateKeyPkcs8]),a);if(String(i.id)!==e.appId||!i.slug||!i.owner?.login||!i.owner.type)throw new d("GITHUB_APP_REQUEST_FAILED","GitHub returned incomplete GitHub App registration details",a);return{details:i,githubRequestId:a}}async function k(e){let t=f(e),r=await g(t),i=await A(t,r);return{appSlug:i.details.slug,appOwnerLogin:i.details.owner.login,appOwnerType:i.details.owner.type,githubRequestId:i.githubRequestId}}async function _(e,t,r){let i=r??await g(e),a=await b(`${e.apiBaseUrl}/app/installations/${e.installationId}/access_tokens`,{method:"POST",headers:w(`Bearer ${i}`)},c.GITHUB_REST_OPERATIONS.apps.createInstallationAccessToken,e,t),n=await E(a),s=S(a);if(401===a.status)throw new d("GITHUB_APP_UNAUTHORIZED","GitHub rejected the App ID or private key",s);if(404===a.status)throw new d("INSTALLATION_NOT_FOUND","The GitHub App installation was not found",s);if(!a.ok||!n||"object"!=typeof n)throw new d("GITHUB_APP_REQUEST_FAILED",v(n,a.status,[i,e.privateKey,e.privateKeyPkcs8]),s);if("string"!=typeof n.token||!n.token||"string"!=typeof n.expires_at||Number.isNaN(Date.parse(n.expires_at)))throw new d("GITHUB_APP_REQUEST_FAILED","GitHub returned an invalid installation token response",s);if("write"!==(n.permissions?.actions??"none"))throw new d("ACTIONS_PERMISSION_REQUIRED","The GitHub App installation must grant Actions: read and write",s);return{token:n.token,expiresAt:new Date(n.expires_at),permissions:n.permissions??{},repositorySelection:n.repository_selection??"selected"}}async function T(e,t){let r=y(e),i=h.get(r);if(i&&i.expiresAt.getTime()-3e5>Date.now())return i;let a=p.get(r);if(a)return a;let n=_(e,t).then(e=>(h.set(r,e),e)).finally(()=>p.delete(r));return p.set(r,n),n}function C(){h.clear(),p.clear()}async function R(e,t,r){let i=f(e),a=await T(i,r),n=await t(a.token);return 401===n.status&&(h.delete(y(i)),a=await T(i,r),n=await t(a.token)),{response:n,token:a.token}}async function N(e,t,r,i){let{response:a,token:n}=await R(e,a=>b(e.graphqlUrl,{method:"POST",headers:{...w(`Bearer ${a}`),"content-type":"application/json"},body:JSON.stringify({query:t,variables:r})},null,e,i),i),s=await E(a),o=S(a),l=(0,u.parseGitHubRateLimitHeaders)(a.headers);if(401===a.status)throw new d("GITHUB_APP_UNAUTHORIZED","GitHub rejected the installation access token",o,a.status,l);if(!a.ok||s?.errors?.length||!s?.data){let t=s?.errors?.map(e=>e.message).filter(Boolean).join("; ")||v(s,a.status,[n]);throw new d("GITHUB_APP_REQUEST_FAILED",v({message:t},a.status,[n,e.privateKey]),o,a.status,l)}return{data:s.data,githubRequestId:o,statusCode:a.status,rateLimit:l}}async function O(e){let t=f(e),r=await g(t),[i,a]=await Promise.all([I(t,r),A(t,r)]),n=await _(t,"GITHUB_SETTINGS",r);h.set(y(t),n);let s=await N(t,"query VerifyGitHubApp { viewer { login } }",{},"GITHUB_SETTINGS");return{appId:t.appId,installationId:t.installationId,keyFingerprint:t.keyFingerprint,appSlug:a.details.slug,appOwnerLogin:a.details.owner.login,appOwnerType:a.details.owner.type,accountLogin:i.account.login,repositorySelection:n.repositorySelection,actionsPermission:n.permissions.actions??"none",checksPermission:n.permissions.checks??"none",commitStatusesPermission:n.permissions.statuses??"none",webhookEvents:Array.isArray(i.events)?i.events:[],viewerLogin:s.data.viewer.login,verifiedAt:new Date,githubRequestId:s.githubRequestId}}async function D(e,t){let r=f(e),i=await g(r),a=await b(`${r.apiBaseUrl}/app/hook/config`,{method:"PATCH",headers:{...w(`Bearer ${i}`),"content-type":"application/json"},body:JSON.stringify({url:t.url,content_type:"json",secret:t.secret,insecure_ssl:"0"})},c.GITHUB_REST_OPERATIONS.apps.updateWebhookConfigForApp,r,"GITHUB_SETTINGS"),n=S(a);if(404===a.status)return{configured:!1,githubRequestId:n};if(!a.ok)throw new d("GITHUB_APP_REQUEST_FAILED",v(await E(a),a.status,[i,t.secret,r.privateKey]),n);return{configured:!0,githubRequestId:n}}async function P(e,t){let r=`${e.apiBaseUrl}/repos/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repository)}/actions/runs/${encodeURIComponent(t.workflowRunId)}/rerun`,{response:i,token:a}=await R(e,i=>b(r,{method:"POST",headers:w(`Bearer ${i}`)},c.GITHUB_REST_OPERATIONS.actions.reRunWorkflow,e,t.requestSource),t.requestSource),n=S(i);if(401===i.status)throw new d("GITHUB_APP_UNAUTHORIZED","GitHub rejected the installation access token",n);if(!i.ok){let t=await E(i);throw new d(404===i.status?"REPOSITORY_NOT_INSTALLED":"GITHUB_APP_REQUEST_FAILED",404===i.status?"The repository or workflow run is not available to this installation":v(t,i.status,[a,e.privateKey]),n)}return{githubRequestId:n}}async function x(e,t){let r=`${e.apiBaseUrl}/repos/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repository)}/actions/runs/${encodeURIComponent(t.workflowRunId)}/rerun-failed-jobs`,{response:i,token:a}=await R(e,i=>b(r,{method:"POST",headers:w(`Bearer ${i}`)},c.GITHUB_REST_OPERATIONS.actions.reRunWorkflowFailedJobs,e,t.requestSource),t.requestSource),n=S(i);if(!i.ok){let t=await E(i);throw new d(404===i.status?"REPOSITORY_NOT_INSTALLED":"GITHUB_APP_REQUEST_FAILED",404===i.status?"The repository or workflow run is not available to this installation":v(t,i.status,[a,e.privateKey]),n)}return{githubRequestId:n}}async function L(e,t){let r=t.force?"force-cancel":"cancel",i=t.force?c.GITHUB_REST_OPERATIONS.actions.forceCancelWorkflowRun:c.GITHUB_REST_OPERATIONS.actions.cancelWorkflowRun,a=`${e.apiBaseUrl}/repos/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repository)}/actions/runs/${encodeURIComponent(t.workflowRunId)}/${r}`,{response:n,token:s}=await R(e,r=>b(a,{method:"POST",headers:w(`Bearer ${r}`)},i,e,t.requestSource),t.requestSource),o=S(n);if(401===n.status)throw new d("GITHUB_APP_UNAUTHORIZED","GitHub rejected the installation access token",o);if(!n.ok){let t=await E(n);throw new d(404===n.status?"REPOSITORY_NOT_INSTALLED":"GITHUB_APP_REQUEST_FAILED",404===n.status?"The repository or workflow run is not available to this installation":v(t,n.status,[s,e.privateKey]),o)}return{githubRequestId:o}}async function U(e,t){let r=[],i=1,a=0;do{let n=`${e.apiBaseUrl}/repos/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repository)}/actions/runs/${encodeURIComponent(t.workflowRunId)}/jobs?filter=latest&per_page=100&page=${i}`,{response:s,token:o}=await R(e,r=>b(n,{headers:w(`Bearer ${r}`)},c.GITHUB_REST_OPERATIONS.actions.listJobsForWorkflowRun,e,t.requestSource),t.requestSource),l=S(s);if(401===s.status)throw new d("GITHUB_APP_UNAUTHORIZED","GitHub rejected the installation access token",l);let u=await E(s);if(!s.ok||!u||"object"!=typeof u)throw new d("GITHUB_APP_REQUEST_FAILED",v(u,s.status,[o,e.privateKey]),l);if(!Number.isInteger(u.total_count)||!Array.isArray(u.jobs))throw new d("GITHUB_APP_REQUEST_FAILED","GitHub returned an invalid workflow jobs response",l);a=u.total_count??0,r.push(...u.jobs),i+=1}while(r.length<a)return r}async function B(e,t){let r=`${e.apiBaseUrl}/repos/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repository)}`,i=`${r}/actions/jobs/${encodeURIComponent(t.jobId)}`,a=await R(e,r=>b(i,{headers:w(`Bearer ${r}`)},c.GITHUB_REST_OPERATIONS.actions.getJobForWorkflowRun,e,t.requestSource),t.requestSource),n=S(a.response);if(401===a.response.status)throw new d("GITHUB_APP_UNAUTHORIZED","GitHub rejected the installation access token",n);let s=await E(a.response);if(!a.response.ok||!s||"object"!=typeof s)throw new d(404===a.response.status?"ACTIONS_JOB_NOT_FOUND":"GITHUB_APP_REQUEST_FAILED",404===a.response.status?"The GitHub Actions job is not available to this installation":v(s,a.response.status,[a.token,e.privateKey]),n);if(String(s.run_id??"")!==t.workflowRunId)throw new d("ACTIONS_JOB_RUN_MISMATCH","The GitHub Actions job does not belong to the selected workflow run",n);if(s.status?.toLowerCase()!=="completed")throw new d("ACTIONS_JOB_NOT_COMPLETED","The GitHub Actions job must be completed before it can be retried",n);let o=await R(e,r=>b(`${i}/rerun`,{method:"POST",headers:w(`Bearer ${r}`)},c.GITHUB_REST_OPERATIONS.actions.reRunJobForWorkflowRun,e,t.requestSource),t.requestSource),l=S(o.response);if(401===o.response.status)throw new d("GITHUB_APP_UNAUTHORIZED","GitHub rejected the installation access token",l);if(!o.response.ok){let t=await E(o.response);throw new d(404===o.response.status?"ACTIONS_JOB_NOT_FOUND":"GITHUB_APP_REQUEST_FAILED",404===o.response.status?"The GitHub Actions job is not available to this installation":v(t,o.response.status,[o.token,e.privateKey]),l)}return{githubRequestId:l}}let M=new Set(["FAILURE","ERROR","STARTUP_FAILURE","TIMED_OUT"]),q=new Set(["ACTION_REQUIRED","EXPECTED","IN_PROGRESS","PENDING","QUEUED"]),j=["COMPLETED","EXHAUSTED","STOPPED"],$={WORKFLOW_RUN:4,PULL_REQUEST:3,WORKTREE_BRANCH:2,REPOSITORY:1},G="server:github-auto-retry";function F(e){return e.toISOString()}function z(e){return{...e,scope:e.scope,mode:e.mode,failureStrategy:e.failureStrategy,status:e.status,executions:e.executions.map(e=>({...e,lastStatus:e.lastStatus,updatedAt:F(e.updatedAt)})),createdAt:F(e.createdAt),updatedAt:F(e.updatedAt)}}class H{github;polling;timer;pollingTickRunning;rerunRequested;reconciling;constructor(e,t,r=!0){this.github=e,this.polling=t,this.timer=null,this.pollingTickRunning=!1,this.rerunRequested=!1,this.reconciling=!1,this.polling?.register({id:G,kind:"GITHUB_AUTO_RETRY",runtime:"SERVER",enabled:!0,cadenceSeconds:60,details:{}}),r&&queueMicrotask(()=>void this.pollReconcile())}schedule(e){this.timer&&clearTimeout(this.timer);let t=1e3*Math.max(30,e);this.timer=setTimeout(()=>void this.pollReconcile(),t),this.timer.unref(),this.polling?.schedule(G,new Date(Date.now()+t))}configurationChanged(){if(this.pollingTickRunning){this.rerunRequested=!0;return}this.timer&&clearTimeout(this.timer),this.timer=null,queueMicrotask(()=>void this.pollReconcile())}async pollReconcile(){if(this.pollingTickRunning)return;this.pollingTickRunning=!0;let e=60;try{let t=async()=>(e=(await (await (0,r.getPrismaClient)()).gitHubSettings.upsert({where:{id:"default"},create:{id:"default"},update:{}})).actionsNotificationPollIntervalSeconds,this.polling?.configure(G,{cadenceSeconds:e}),this.reconcile());this.polling?await this.polling.run(G,t,e=>({activeRules:e})):await t()}catch{}finally{this.pollingTickRunning=!1,this.rerunRequested?(this.rerunRequested=!1,queueMicrotask(()=>void this.pollReconcile())):this.schedule(e)}}include(){return{targets:{orderBy:{createdAt:"asc"}},executions:{orderBy:{updatedAt:"desc"}}}}async list(e){let t=await (0,r.getPrismaClient)(),i=e.codebaseRepositoryId?await this.github.autoRetryRepositoryId(e.codebaseRepositoryId):null;return(await t.gitHubAutoRetryRule.findMany({where:{...i?{codebaseRepositoryId:i}:{},...e.workflowRunId?{targets:{some:{workflowRunId:e.workflowRunId}}}:{}},include:this.include(),orderBy:{updatedAt:"desc"}})).map(z)}validate(e){if(!e.codebaseRepositoryId.trim())throw Error("Codebase repository is required");if("COUNT"===e.mode&&null==e.retryLimit)throw Error("Count mode requires a retry limit");if(null!=e.retryLimit&&(!Number.isInteger(e.retryLimit)||e.retryLimit<1||e.retryLimit>100))throw Error("Retry limit must be an integer from 1 to 100");if("FAILURE"===e.mode&&void 0===e.retryLimit)throw Error("Failure retry limit must be a number or null");if("WORKFLOW_RUN"===e.scope){if(!e.targets.length||e.targets.some(e=>!e.workflowRunId))throw Error("Current-run rules require workflow run targets")}else if(!e.allWorkflows&&!e.targets.length)throw Error("Select at least one workflow or choose all workflows");if("WORKTREE_BRANCH"===e.scope&&!e.worktreeId)throw Error("Worktree future rules require a worktree");if("PULL_REQUEST"===e.scope&&!e.pullRequestNumber)throw Error("Pull request future rules require a pull request number")}async save(e){if(!await this.github.autoRetryCredentialsReady())throw Error("A GitHub token and verified GitHub App with Actions write access are required");e={...e,codebaseRepositoryId:await this.github.autoRetryRepositoryId(e.codebaseRepositoryId)},this.validate(e);let i=await (0,r.getPrismaClient)(),a=e.branch?.trim()||null;if("WORKTREE_BRANCH"===e.scope&&e.worktreeId){let t=await i.worktree.findUnique({where:{id:e.worktreeId},select:{branch:!0}});if(!(a=t?.branch??null))throw Error("The worktree does not have a branch")}let n=await i.gitHubAutoRetryRule.findMany({where:{id:e.id?{not:e.id}:void 0,enabled:!0,scope:e.scope,codebaseRepositoryId:e.codebaseRepositoryId},include:{targets:!0}}),s=new Set(e.targets.map(e=>e.workflowRunId).filter(e=>!!e));if(n.find(t=>"WORKFLOW_RUN"===e.scope?t.targets.some(e=>e.workflowRunId&&s.has(e.workflowRunId)):"WORKTREE_BRANCH"===e.scope?t.branch===a:"PULL_REQUEST"!==e.scope||t.pullRequestNumber===e.pullRequestNumber))throw Error("An enabled Auto Retry rule already exists for this scope");let o=e.id??(0,t.randomUUID)(),l=await i.$transaction(async r=>(await r.gitHubAutoRetryRule.upsert({where:{id:o},create:{id:o,scope:e.scope,codebaseRepositoryId:e.codebaseRepositoryId,repositoryGithubId:e.repositoryGithubId??null,worktreeId:e.worktreeId??null,branch:a,pullRequestNumber:e.pullRequestNumber??null,allWorkflows:e.allWorkflows,mode:e.mode,retryLimit:e.retryLimit??null,failureStrategy:e.failureStrategy,status:"ACTIVE",enabled:!0},update:{scope:e.scope,codebaseRepositoryId:e.codebaseRepositoryId,repositoryGithubId:e.repositoryGithubId??null,worktreeId:e.worktreeId??null,branch:a,pullRequestNumber:e.pullRequestNumber??null,allWorkflows:e.allWorkflows,mode:e.mode,retryLimit:e.retryLimit??null,failureStrategy:e.failureStrategy,status:"ACTIVE",enabled:!0,lastError:null,activatedAt:new Date}}),await r.gitHubAutoRetryTarget.deleteMany({where:{ruleId:o}}),e.targets.length&&await r.gitHubAutoRetryTarget.createMany({data:e.targets.map(e=>({id:(0,t.randomUUID)(),ruleId:o,workflowId:e.workflowId?.trim()||null,workflowRunId:e.workflowRunId?.trim()||null,jobName:e.jobName?.trim()||null}))}),await r.gitHubAutoRetryExecution.deleteMany({where:{ruleId:o}}),r.gitHubAutoRetryRule.findUniqueOrThrow({where:{id:o},include:this.include()})));return queueMicrotask(()=>void this.reconcile().catch(()=>void 0)),z(l)}async setEnabled(e,t){let i=await (0,r.getPrismaClient)(),a=await i.$transaction(async r=>(t&&await r.gitHubAutoRetryExecution.updateMany({where:{ruleId:e,pendingFromAttempt:{not:null}},data:{pendingFromAttempt:null,observedAttempt:0,status:"WATCHING",lastError:null,finishedAt:null}}),r.gitHubAutoRetryRule.update({where:{id:e},data:{enabled:t,status:t?"ACTIVE":"PAUSED",lastError:null,...t?{activatedAt:new Date}:{}},include:this.include()})));return t&&queueMicrotask(()=>void this.reconcile().catch(()=>void 0)),z(a)}async delete(e){return(await (await (0,r.getPrismaClient)()).gitHubAutoRetryRule.deleteMany({where:{id:e}})).count>0}matches(e,t,r=!1){if("WORKFLOW_RUN"!==e.scope){let i=q.has(t.status);if(!r&&!i&&Date.parse(t.createdAt)<e.activatedAt.getTime())return!1}return"WORKTREE_BRANCH"===e.scope?t.headBranch===e.branch:"PULL_REQUEST"!==e.scope||t.pullRequests.some(t=>t.number===e.pullRequestNumber)}async execution(e,i,a){return(await (0,r.getPrismaClient)()).gitHubAutoRetryExecution.upsert({where:{ruleId_workflowRunId_targetKey:{ruleId:e,workflowRunId:i.id,targetKey:a}},create:{id:(0,t.randomUUID)(),ruleId:e,workflowRunId:i.id,workflowId:i.workflowId,targetKey:a},update:{}})}targetKeys(e,t){if(e.allWorkflows)return["workflow"];let r=e.targets.filter(e=>e.workflowRunId===t.id||e.workflowId===t.workflowId);return r.some(e=>!e.jobName)||"FAILURE"===e.mode&&"ALL_JOBS"===e.failureStrategy?["workflow"]:r.flatMap(e=>e.jobName?[`job:${e.jobName}`]:[])}async finishExecution(e,t,i){await (await (0,r.getPrismaClient)()).gitHubAutoRetryExecution.update({where:{id:e},data:{status:i,observedAttempt:t.runAttempt,lastStatus:t.status,pendingFromAttempt:null,finishedAt:new Date,lastError:null}})}async trigger(e,t,i,a,n){let s=await (0,r.getPrismaClient)();await s.gitHubAutoRetryExecution.update({where:{id:t.id},data:{status:"RETRYING",pendingFromAttempt:i.runAttempt,observedAttempt:i.runAttempt,lastStatus:i.status,lastError:null}});try{await this.github.autoRetryRerun(e.codebaseRepositoryId,i.id,a,n,{actor:"auto-retry",ipAddress:null,autoRetryRuleId:e.id,autoRetryExecutionId:t.id}),await s.gitHubAutoRetryExecution.update({where:{id:t.id},data:{automaticRetries:{increment:1},lastError:null}})}catch(i){let r=i instanceof Error?i.message:String(i);await s.gitHubAutoRetryExecution.update({where:{id:t.id},data:{lastError:r}}),await s.gitHubAutoRetryRule.update({where:{id:e.id},data:{lastError:r}})}}async reconcileExecution(e,t,i,a){var n;let s,o=await this.execution(e.id,t,i);if(null!=o.pendingFromAttempt)if(t.runAttempt>o.pendingFromAttempt)await (await (0,r.getPrismaClient)()).gitHubAutoRetryExecution.update({where:{id:o.id},data:{pendingFromAttempt:null,status:"WATCHING",lastError:null}});else{if(Date.now()-o.updatedAt.getTime()<12e4)return!1;let t=await (0,r.getPrismaClient)(),i="GitHub did not report a new attempt after the rerun request; automatic retries are paused to prevent a duplicate rerun";return await t.$transaction(async t=>{await t.gitHubAutoRetryExecution.update({where:{id:o.id},data:{status:"ERROR",lastError:i}}),await t.gitHubAutoRetryRule.update({where:{id:e.id},data:{enabled:!1,status:"PAUSED",lastError:i}})}),!1}if(o.observedAttempt===t.runAttempt&&null==o.pendingFromAttempt)return!1;let l=a?.status??t.status,u=(s=null!=(n={mode:e.mode,retryLimit:e.retryLimit,automaticRetries:o.automaticRetries,state:l}).retryLimit&&n.automaticRetries>=n.retryLimit,"COUNT"===n.mode?"SUCCESS"!==n.state?"STOP":s?"COMPLETE":"RETRY":"SUCCESS"===n.state?"COMPLETE":M.has(n.state)?s?"EXHAUSTED":"RETRY":"STOP");return"COMPLETE"===u?(await this.finishExecution(o.id,t,"COMPLETED"),!1):"EXHAUSTED"===u?(await this.finishExecution(o.id,t,"EXHAUSTED"),!1):"STOP"===u?(await this.finishExecution(o.id,t,"STOPPED"),!1):("COUNT"===e.mode?await this.trigger(e,o,t,a?"JOB":"ALL_JOBS",a?.id??null):await this.trigger(e,o,t,a?"ALL_JOBS"===e.failureStrategy?"ALL_JOBS":"JOB":"ALL_JOBS"===e.failureStrategy?"ALL_JOBS":"FAILED_JOBS",a?.id??null),!0)}async reconcile(){if(this.reconciling)return 0;this.reconciling=!0;let e=0;try{let t=await (0,r.getPrismaClient)(),i=await t.gitHubAutoRetryRule.findMany({where:{enabled:!0,status:"ACTIVE"},include:{targets:!0},orderBy:{createdAt:"asc"}});e=i.length;let a=new Map,n=i.length?await t.gitHubAutoRetryExecution.findMany({where:{ruleId:{in:i.map(e=>e.id)},status:{notIn:j}},select:{ruleId:!0,workflowRunId:!0}}):[],s=new Map;for(let e of n){let t=s.get(e.ruleId)??new Set;t.add(e.workflowRunId),s.set(e.ruleId,t)}let o=new Map;for(let e of i){let r=a.get(e.codebaseRepositoryId);if(!r)try{r=await this.github.autoRetryRuns(e.codebaseRepositoryId),a.set(e.codebaseRepositoryId,r)}catch(r){await t.gitHubAutoRetryRule.update({where:{id:e.id},data:{lastError:r instanceof Error?r.message:String(r)}});continue}let i=new Set(e.targets.map(e=>e.workflowRunId).filter(e=>!!e)),n=s.get(e.id)??new Set;for(let a of new Set([...i,...n]))if(!r.some(e=>e.id===a))try{r.push(await this.github.autoRetryRun(e.codebaseRepositoryId,a,!1))}catch(r){await t.gitHubAutoRetryRule.update({where:{id:e.id},data:{lastError:r instanceof Error?r.message:String(r)}})}for(let t of r){if("WORKFLOW_RUN"===e.scope&&!i.has(t.id)||!this.matches(e,t,n.has(t.id))||!e.allWorkflows&&!e.targets.some(e=>e.workflowRunId===t.id||e.workflowId===t.workflowId))continue;let r=o.get(t.id);(!r||$[e.scope]>$[r.rule.scope])&&o.set(t.id,{rule:e,run:t})}}for(let{rule:e,run:r}of o.values()){let i=this.targetKeys(e,r);if(q.has(r.status)){await Promise.all(i.map(t=>this.execution(e.id,r,t)));continue}let a=r,n=e.allWorkflows?[{jobName:null}]:e.targets.filter(e=>e.workflowRunId===a.id||e.workflowId===a.workflowId);if(n.some(e=>!e.jobName)){await this.reconcileExecution(e,a,"workflow",null);continue}let s=await Promise.all(i.map(t=>this.execution(e.id,a,t)));if(!s.some(e=>e.observedAttempt!==a.runAttempt||null!=e.pendingFromAttempt&&a.runAttempt>e.pendingFromAttempt)){for(let t=0;t<s.length;t+=1)s[t]?.pendingFromAttempt!=null&&await this.reconcileExecution(e,a,i[t],null);continue}try{a=await this.github.autoRetryRun(e.codebaseRepositoryId,a.id)}catch(r){await t.gitHubAutoRetryRule.update({where:{id:e.id},data:{lastError:r instanceof Error?r.message:String(r)}});continue}if("FAILURE"===e.mode&&"ALL_JOBS"===e.failureStrategy){let t=a.jobs.filter(e=>n.some(t=>t.jobName===e.name)),r=t.find(e=>M.has(e.status))??t.find(e=>"SUCCESS"!==e.status)??t[0];r?await this.reconcileExecution(e,a,"workflow",r):s[0]&&await this.finishExecution(s[0].id,a,"STOPPED");continue}let o=new Map(i.map((e,t)=>[e,s[t]]));for(let t of n){let r=a.jobs.find(e=>e.name===t.jobName);if(!r){let e=o.get(`job:${t.jobName}`);e&&await this.finishExecution(e.id,a,"STOPPED");continue}if(await this.reconcileExecution(e,a,`job:${r.name}`,r))break}}for(let e of i.filter(e=>"WORKFLOW_RUN"===e.scope)){let r=await t.gitHubAutoRetryExecution.findMany({where:{ruleId:e.id},select:{status:!0}});r.length>0&&r.every(e=>j.includes(e.status))&&await t.gitHubAutoRetryRule.update({where:{id:e.id},data:{enabled:!1,status:r.some(e=>"EXHAUSTED"===e.status)?"EXHAUSTED":"COMPLETED"}})}}finally{this.reconciling=!1}return e}}e.s(["GitHubAutoRetryService",0,H],685155);var V=e.i(963910),K=e.i(940045),W=e.i(919412),J=e.i(407188),Y=e.i(995702),Q=e.i(151112),Z=e.i(312851);let X="_adeRateLimit";function ee(e){let t=(0,Q.parse)(e),r=t.definitions.filter(e=>e.kind===Y.Kind.OPERATION_DEFINITION);if(1!==r.length||!r[0])throw Error("GitHub GraphQL requests must contain one operation");let i=r[0],a=i.name?.value??("mutation"===i.operation?"AnonymousMutation":"AnonymousQuery"),n=(0,Z.print)(t);if("query"!==i.operation)return{kind:"mutation",operation:a,normalizedQuery:n,liveQuery:n};let s={...t,definitions:t.definitions.map(e=>e===i?{...i,selectionSet:{...i.selectionSet,selections:[...i.selectionSet.selections,{kind:Y.Kind.FIELD,alias:{kind:Y.Kind.NAME,value:X},name:{kind:Y.Kind.NAME,value:"rateLimit"},arguments:[],directives:[],selectionSet:{kind:Y.Kind.SELECTION_SET,selections:[{kind:Y.Kind.FIELD,name:{kind:Y.Kind.NAME,value:"cost"},arguments:[],directives:[]}]}}]}}:e)};return{kind:"query",operation:a,normalizedQuery:n,liveQuery:(0,Z.print)(s)}}function et(e){if(!e||"object"!=typeof e||Array.isArray(e))return{data:e,pointCost:null};let t=e[X],r=t&&"object"==typeof t&&!Array.isArray(t)&&Number.isSafeInteger(t.cost)?t.cost:null;if(!(X in e))return{data:e,pointCost:r};let i={...e};return delete i[X],{data:i,pointCost:r}}let er="default",ei="default",ea=String.raw`\b([A-Z][A-Z0-9_]*-\d+)\b`,en=["workflow_run","workflow_job","check_run","check_suite","status"];function es(e){return"read"===e||"write"===e}function eo(e){let t=[];for(let r of(e.webhookConfigured||t.push("configure the signed webhook URL"),es(e.actionsPermission)||t.push("grant Actions read permission"),es(e.checksPermission)||t.push("grant Checks read permission"),es(e.commitStatusesPermission)||t.push("grant Commit statuses read permission"),en))e.webhookEvents.includes(r)||t.push(`subscribe to the ${r} event`);return t}function el(e){return"auto-retry"===e.actor?"AUTO_RETRY":"workflow"===e.actor?"WORKFLOW_AUTOMATION":"ACTIONS_PAGE"}class eu extends Error{statusCode;rateLimit;constructor(e,t,r){super(e),this.statusCode=t,this.rateLimit=r,this.name="GitHubRequestError"}}let ec=`
|
|
66
|
+
`}])},735255,e=>{"use strict";let t=Symbol("unattributed");function r(){return{inputTokens:0,outputTokens:0,cacheCreationTokens:0,cacheReadTokens:0,totalTokens:0,totalCost:0}}function i(e,t){e.inputTokens+=t.inputTokens,e.outputTokens+=t.outputTokens,e.cacheCreationTokens+=t.cacheCreationTokens,e.cacheReadTokens+=t.cacheReadTokens,e.totalTokens+=t.totalTokens,e.totalCost+=t.totalCost}function a(e,t){return t.totalCost-e.totalCost||t.totalTokens-e.totalTokens||(e.modelName??e.agentName??"").localeCompare(t.modelName??t.agentName??"")}function n(e){let t=e=>String(e).padStart(2,"0");return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}`}function s(e){let t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)throw Error("Usage date must be a valid date in YYYY-MM-DD format");let[,r,i,a]=t,n=Number(r),s=Number(i),o=Number(a),l=new Date(0);if(l.setHours(0,0,0,0),l.setFullYear(n,s-1,o),l.getFullYear()!==n||l.getMonth()!==s-1||l.getDate()!==o)throw Error("Usage date must be a valid date in YYYY-MM-DD format");return l}function o(e){let t=new Date(864e5*e),r=e=>String(e).padStart(2,"0");return`${t.getUTCFullYear()}-${r(t.getUTCMonth()+1)}-${r(t.getUTCDate())}`}function l(e,t){if(0===e.days.length)return null;let r=e.days.map(e=>{let t,r;return{ordinal:(t=s(e.period),(r=new Date(0)).setUTCHours(0,0,0,0),r.setUTCFullYear(t.getFullYear(),t.getMonth(),t.getDate()),Math.floor(r.getTime()/864e5)),totalCost:e.totalCost}}).sort((e,t)=>e.ordinal-t.ordinal),i=new Map(r.map(e=>[e.ordinal,e.totalCost])),a=r[0].ordinal,n=r.at(-1).ordinal,l=0,u=a,c=-1/0;for(let e=a;e<=n;e+=1)l+=i.get(e)??0,((l-=i.get(e-t)??0)>c||l===c&&e>u)&&(c=l,u=e);return{startDate:o(u-(t-1)),endDate:o(u),totalCost:c}}e.s(["aggregateUsage",0,function(e){let n=new Map,s=r();for(let{agent:a,report:o}of e)for(let e of(i(s,o.totals),o.daily)){let s=n.get(e.period);s||(s={...r(),period:e.period,models:new Map,sourceSet:new Set},n.set(e.period,s)),i(s,e),e.metadata.agents.forEach(e=>s.sourceSet.add(e));let o=0;for(let t of e.modelBreakdowns){let n={inputTokens:t.inputTokens,outputTokens:t.outputTokens,cacheCreationTokens:t.cacheCreationTokens,cacheReadTokens:t.cacheReadTokens,totalTokens:t.inputTokens+t.outputTokens+t.cacheCreationTokens+t.cacheReadTokens,totalCost:t.cost};o+=n.totalTokens;let l=s.models.get(t.modelName);l||(l={...r(),modelName:t.modelName,agents:new Map},s.models.set(t.modelName,l)),i(l,n);let u=l.agents.get(a.id);u||(u={...r(),agentId:a.id,agentName:a.name,hostname:a.hostname,sources:[],sourceSet:new Set},l.agents.set(a.id,u)),i(u,n),e.metadata.agents.forEach(e=>u.sourceSet.add(e))}!function(e,i,a,n){if(n<=0)return;let s=e.models.get(t);s||(s={...r(),modelName:"Unattributed tokens",agents:new Map,unattributed:!0},e.models.set(t,s)),s.totalTokens+=n;let o=s.agents.get(i.id);o||(o={...r(),agentId:i.id,agentName:i.name,hostname:i.hostname,sources:[],sourceSet:new Set},s.agents.set(i.id,o)),o.totalTokens+=n,a.forEach(e=>o.sourceSet.add(e))}(s,a,e.metadata.agents,e.totalTokens-o)}return{totals:s,days:[...n.values()].sort((e,t)=>t.period.localeCompare(e.period)).map(e=>({inputTokens:e.inputTokens,outputTokens:e.outputTokens,cacheCreationTokens:e.cacheCreationTokens,cacheReadTokens:e.cacheReadTokens,totalTokens:e.totalTokens,totalCost:e.totalCost,period:e.period,sources:[...e.sourceSet].sort(),models:[...e.models.values()].sort(a).map(e=>({inputTokens:e.inputTokens,outputTokens:e.outputTokens,cacheCreationTokens:e.cacheCreationTokens,cacheReadTokens:e.cacheReadTokens,totalTokens:e.totalTokens,totalCost:e.totalCost,modelName:e.modelName,...e.unattributed?{unattributed:!0}:{},agents:[...e.agents.values()].sort(a).map(e=>({inputTokens:e.inputTokens,outputTokens:e.outputTokens,cacheCreationTokens:e.cacheCreationTokens,cacheReadTokens:e.cacheReadTokens,totalTokens:e.totalTokens,totalCost:e.totalCost,agentId:e.agentId,agentName:e.agentName,hostname:e.hostname,sources:[...e.sourceSet].sort()}))}))}))}},"filterUsageByDays",0,function(e,t,a=new Date){if(null===t)return e;let o="string"==typeof a?s(a):new Date(a);o.setHours(0,0,0,0);let l=new Date(o);l.setDate(l.getDate()-(t-1));let u=n(l),c=n(o),d=e.days.filter(e=>e.period>=u&&e.period<=c),h=r();return d.forEach(e=>i(h,e)),{days:d,totals:h}},"usageSpendPeaks",0,function(e,t,a){let n,s,o=t?(n=r(),{days:e.days.flatMap(e=>{let a=new Set,s=e.models.flatMap(e=>{let n=e.agents.filter(e=>e.agentId===t);if(0===n.length)return[];let s=r();return n.forEach(e=>{i(s,e),e.sources.forEach(e=>a.add(e))}),[{...s,modelName:e.modelName,agents:n,...e.unattributed?{unattributed:!0}:{}}]});if(0===s.length)return[];let o=r();return s.forEach(e=>i(o,e)),i(n,o),[{...o,period:e.period,sources:[...a].sort(),models:s}]}),totals:n}):e,u=a?(s=r(),{days:o.days.flatMap(e=>{let t=e.models.filter(e=>!e.unattributed&&e.modelName===a);if(0===t.length)return[];let n=r(),o=new Set;return t.forEach(e=>{i(n,e),e.agents.forEach(e=>e.sources.forEach(e=>o.add(e)))}),i(s,n),[{...n,period:e.period,sources:[...o].sort(),models:t}]}),totals:s}):o;return{last7Days:l(u,7),last30Days:l(u,30)}}])},497800,248626,361617,e=>{"use strict";var t=e.i(469719),r=e.i(807055),i=e.i(184015),a=e.i(119909),n=e.i(835544),s=e.i(499162);function o(e){return{kind:"static",options:e.map(e=>({value:e,label:e.charAt(0)+e.slice(1).toLowerCase().replace(/_/g," ")}))}}function l(e){return{kind:"static",options:e}}let u={agent:"agent.id",codebase:"codebase.id",worktree:"worktree.id",githubRepository:"repo.id",githubPullRequest:"pr.number",jiraTicket:"ticket.key",agentRun:"run.id",githubWorkflowRun:"pipeline.runId"};function c(e,t){return{kind:"resource",resource:e,scopeFrom:t,sessionPath:u[e]}}let d=["literal","session","interpolation"],h=["literal","interpolation"],p=(e,t,r={})=>({key:e,label:t,control:"text",valueModes:d,...r}),m=(e,t,r={})=>p(e,t,{multiline:!0,...r}),f=(e,t,r={})=>({key:e,label:t,control:"number",valueModes:["literal","session"],...r}),g=(e,t,r={})=>({key:e,label:t,control:"boolean",...r}),y=(e,t,r,i={})=>({key:e,label:t,control:"enum",options:r,...i}),w=(e,t,r,i={})=>{let{scopeFrom:a,...n}=i;return{key:e,label:t,control:"resource",options:c(r,a),valueModes:d,...n}},b=(e,t,r,i={})=>{let{scopeFrom:a,...n}=i;return{key:e,label:t,control:"resourceMulti",options:c(r,a),valueModes:h,...n}},E=(e,t,r={})=>({key:e,label:t,control:"stringList",valueModes:h,...r}),S=e=>({key:"mcpPresetIds",label:"MCP tool presets",control:"mcpPresetMulti",presetKind:e,default:[]}),v=(e,t,r={})=>({key:e,label:t,control:"record",valueModes:h,...r}),I=(e,t,r={})=>({key:e,label:t,control:"json",valueModes:h,...r}),A=(e,t,r={})=>({key:e,label:t,control:"triggerChoices",...r}),k=l([{value:"EQ",label:"Equals"},{value:"NE",label:"Not equal"},{value:"GT",label:"Greater than"},{value:"GTE",label:"Greater or equal"},{value:"LT",label:"Less than"},{value:"LTE",label:"Less or equal"},{value:"CONTAINS",label:"Contains"},{value:"MATCHES",label:"Matches RE2"},{value:"EXISTS",label:"Exists"}]),_=o(a.WORKTREE_OPERATIONS.filter(e=>"OPEN_EDITOR"!==e)),T=()=>[p("owner","Repository owner",{placeholder:"octocat",help:"Defaults to the repository from session data."}),p("name","Repository name",{placeholder:"hello-world"})],C=e=>[w("worktreeId","Worktree","worktree"),w("jiraIssueKey","Jira issue key","jiraTicket",{placeholder:"APP-123"}),{key:"model",label:"Model",control:"model",required:!0,valueModes:["literal","session"],modelKeys:{provider:"provider",model:"model",effort:"effort",scopeFrom:"worktreeId"}},g("webSearchEnabled","Enable web search"),S(e),f("worktreeConcurrencyLimit","Worktree concurrency limit",{default:"PLAN"===e?0:"SESSION"===e?1:void 0,minimum:0,maximum:32,integer:!0,help:"PLAN"===e?"Maximum plans admitted on this worktree. Use 0 for unlimited.":"SESSION"===e?"Maximum sessions admitted on this worktree. Use 0 for unlimited.":"Maximum same-kind runs admitted on this worktree. Use 0 for unlimited; leave empty for the source kind's default."}),m("prompt","Prompt",{required:!0}),E("attachmentIds","Attachment IDs")],R={JIRA_LOAD_TICKET:{fields:[w("issueKey","Issue key","jiraTicket",{placeholder:"APP-123"}),g("force","Bypass cache")]},JIRA_TRANSITION:{fields:[w("issueKey","Issue key","jiraTicket",{placeholder:"APP-123"}),p("transitionId","Transition ID",{required:!0})]},JIRA_COMMENT:{fields:[w("issueKey","Issue key","jiraTicket",{placeholder:"APP-123"}),m("content","Comment",{required:!0}),y("format","Format",l([{value:"MARKDOWN",label:"Markdown"},{value:"JIRA_WIKI",label:"Jira wiki"}]))]},JIRA_ASSIGN:{fields:[w("issueKey","Issue key","jiraTicket",{placeholder:"APP-123"}),w("accountId","Assignee","jiraUser",{scopeFrom:"issueKey",help:"Leave empty to unassign the ticket."})]},JIRA_UPDATE_FIELDS:{fields:[w("issueKey","Issue key","jiraTicket",{placeholder:"APP-123"}),I("fields","Fields",{placeholder:'{ "labels": ["ready"] }'})]},JIRA_RESOLVE_BRANCH:{fields:[w("issueKey","Issue key","jiraTicket",{placeholder:"APP-123"}),w("codebaseId","Codebase","codebase")]},GITHUB_LOAD_PR:{fields:[...T(),f("number","Pull request number")]},GITHUB_MERGE_PR:{fields:[...T(),f("number","Pull request number"),y("method","Merge method",l([{value:"SQUASH",label:"Squash"},{value:"MERGE",label:"Merge"},{value:"REBASE",label:"Rebase"}])),p("commitHeadline","Commit headline"),m("commitBody","Commit body"),p("authorEmail","Author email")]},GITHUB_COLLECT_REVIEW_THREADS:{fields:[...T(),f("number","Pull request number")]},GITHUB_REPLY_REVIEW_THREAD:{fields:[p("threadId","Review thread ID",{required:!0}),m("body","Reply",{required:!0})]},GITHUB_SET_REVIEW_THREAD_RESOLVED:{fields:[p("threadId","Review thread ID",{required:!0}),g("resolved","Mark resolved")]},GITHUB_CREATE_PR:{fields:[...T(),p("baseRefName","Base branch"),p("headRefName","Head branch"),p("title","Title"),m("body","Body"),g("draft","Open as draft")]},GITHUB_SET_PR_LABELS:{fields:[...T(),f("number","Pull request number"),E("labels","Labels")]},GITHUB_RETRY_PIPELINE:{fields:[w("repositoryId","Repository","githubRepository"),p("checkSuiteId","Check suite ID")]},GITHUB_RETRY_JOB:{fields:[w("repositoryId","Repository","githubRepository"),p("checkSuiteId","Check suite ID",{required:!0}),p("jobId","Workflow job ID",{required:!0})]},GITHUB_CANCEL_WORKFLOW_RUN:{fields:[p("codebaseRepositoryId","Codebase repository ID"),w("workflowRunId","Workflow run","githubWorkflowRun",{scopeFrom:"codebaseRepositoryId"}),g("force","Force cancel")]},GITHUB_SAVE_AUTO_RETRY:{fields:[I("input","Auto-retry rule",{required:!0})]},GITHUB_WAIT_CHECKS:{fields:[p("repositoryId","Repository ID"),p("workflowRunId","Workflow run ID")]},GITLAB_LOAD_MR:{fields:[p("projectId","Project ID"),f("iid","Merge request IID")]},GITLAB_CREATE_MR:{fields:[p("projectId","Project ID"),p("sourceBranch","Source branch"),p("targetBranch","Target branch"),p("title","Title"),m("description","Description"),g("removeSourceBranch","Remove source branch"),g("squash","Squash commits"),E("reviewerIds","Reviewer IDs"),E("labels","Labels")]},GITLAB_UPDATE_MR:{fields:[p("projectId","Project ID"),f("iid","Merge request IID"),p("title","Title"),m("description","Description"),y("stateEvent","State",o(["CLOSE","REOPEN"])),E("reviewerIds","Reviewer IDs"),E("labels","Labels")]},GITLAB_SUBMIT_REVIEW:{fields:[p("projectId","Project ID"),f("iid","Merge request IID"),y("outcome","Review outcome",o(["APPROVE","COMMENT","REQUEST_CHANGES"])),m("body","Review body")]},GITLAB_REPLY_DISCUSSION:{fields:[p("projectId","Project ID"),f("iid","Merge request IID"),p("discussionId","Discussion ID",{required:!0}),m("body","Reply",{required:!0})]},GITLAB_SET_DISCUSSION_RESOLVED:{fields:[p("projectId","Project ID"),f("iid","Merge request IID"),p("discussionId","Discussion ID",{required:!0}),g("resolved","Mark resolved")]},GITLAB_MERGE_MR:{fields:[p("projectId","Project ID"),f("iid","Merge request IID"),g("squash","Squash commits"),g("removeSourceBranch","Remove source branch"),g("autoMerge","Enable auto-merge"),p("sha","Expected source SHA")]},GITLAB_SET_MR_LABELS:{fields:[p("projectId","Project ID"),f("iid","Merge request IID"),E("labels","Labels")]},GITLAB_REQUEST_REVIEWERS:{fields:[p("projectId","Project ID"),f("iid","Merge request IID"),E("reviewerIds","Reviewer IDs")]},GITLAB_CREATE_PIPELINE:{fields:[p("projectId","Project ID"),p("ref","Git ref"),I("variables","Pipeline variables")]},GITLAB_RETRY_PIPELINE:{fields:[p("projectId","Project ID"),p("pipelineId","Pipeline ID")]},GITLAB_RETRY_JOB:{fields:[p("projectId","Project ID"),p("jobId","Job ID")]},GITLAB_CANCEL_PIPELINE:{fields:[p("projectId","Project ID"),p("pipelineId","Pipeline ID")]},GITLAB_SAVE_AUTO_RETRY:{fields:[I("input","Auto-retry rule",{required:!0})]},GITLAB_WAIT_PIPELINE:{fields:[p("projectId","Project ID"),p("pipelineId","Pipeline ID")]},WORKTREE_CREATE:{fields:[w("codebaseId","Codebase","codebase"),y("mode","Branch mode",o(["NEW","EXISTING","TICKET"])),p("branchName","Branch name"),p("ticketKey","Ticket key",{placeholder:"APP-123"}),p("baseBranch","Base branch")]},WORKTREE_CHANGE_BRANCH:{fields:[w("worktreeId","Worktree","worktree"),y("mode","Branch mode",o(["NEW","EXISTING","TICKET"])),p("branchName","Branch name"),p("ticketKey","Ticket key",{placeholder:"APP-123"}),p("baseBranch","Base branch"),g("stashOnFailure","Stash on failure")]},WORKTREE_COMMIT:{fields:[w("worktreeId","Worktree","worktree"),m("message","Commit message",{required:!0}),g("signed","Signed commit"),g("stageAll","Stage all",{default:!0}),I("paths","Selected paths")]},WORKTREE_REFRESH_PULL_REQUEST:{fields:[w("worktreeId","Worktree","worktree")]},WORKTREE_OPERATION:{fields:[w("worktreeId","Worktree","worktree"),y("operation","Operation",_),g("forcePreparations","Force preparation conflicts",{help:"Destructively resets preparation-managed paths before Sync or Rebase, then reapplies the current rules."})]},WORKTREE_PREPARATION:{fields:[w("worktreeId","Worktree","worktree"),y("action","Action",o(a.WORKTREE_PREPARATION_ACTIONS))]},WORKTREE_SET_AUTO_SYNC:{fields:[w("worktreeId","Worktree","worktree"),y("action","Action",o(["ENABLE","RETRY","FORCE","CANCEL"])),p("conflictWorkflowId","Conflict workflow ID"),p("conflictWorkflowChoice","Conflict workflow choice")]},WORKTREE_SET_AUTO_MERGE:{fields:[w("worktreeId","Worktree","worktree"),y("action","Action",o(["ENABLE","RETRY","CANCEL"])),p("repositoryNameWithOwner","Repository",{placeholder:"owner/repository"}),f("pullRequestNumber","Pull request number"),y("method","Merge method",o(["MERGE","REBASE","SQUASH"])),p("commitHeadline","Commit headline"),m("commitBody","Commit body"),p("authorEmail","Author email"),g("deleteWorktree","Delete worktree after merge"),g("moveTicketToDone","Move Jira ticket to done")]},WORKTREE_DELETE:{fields:[w("worktreeId","Worktree","worktree"),g("deleteRemoteBranch","Delete remote branch")]},WORKTREE_MOVE:{fields:[w("worktreeId","Source worktree","worktree"),w("targetCodebaseId","Target codebase","codebase",{required:!0}),w("targetWorktreeId","Target worktree","worktree"),g("deleteSource","Delete source")]},WORKTREE_INSPECT:{fields:[w("worktreeId","Worktree","worktree")]},WORKTREE_INSPECT_GIT:{fields:[w("worktreeId","Worktree","worktree")]},WORKTREE_GIT_OPERATION:{fields:[w("worktreeId","Worktree","worktree"),y("operation","Operation",o(a.WORKTREE_GIT_OPERATIONS)),p("branch","Branch"),p("stashOid","Stash OID"),g("stashChanges","Stash changes first")]},WORKTREE_WAIT_PUSH_READY:{fields:[w("worktreeId","Worktree","worktree")]},WORKTREE_SNAPSHOT:{fields:[p("kind","Checkpoint kind",{placeholder:"STEP"})]},CODEBASE_FETCH_REFRESH:{fields:[w("codebaseId","Codebase","codebase"),y("operation","Operation",o(["FETCH","REFRESH"]))]},CODEBASE_INSPECT_GIT:{fields:[w("codebaseId","Codebase","codebase")]},CODEBASE_GIT_OPERATION:{fields:[w("codebaseId","Codebase","codebase"),y("operation","Operation",o(i.CODEBASE_GIT_OPERATIONS)),p("branch","Branch"),p("stashOid","Stash OID"),g("stashChanges","Stash changes first")]},BUILD_START:{fields:[w("worktreeId","Worktree","worktree"),p("configurationId","Build configuration ID",{required:!0}),y("action","Action",o(r.BUILD_ACTIONS)),I("destination","Destination"),b("scriptIds","Build scripts","buildScript"),I("advancedSettings","Advanced settings"),g("exportWhenComplete","Export when complete"),I("exportSettings","Export settings"),g("worktreeCoverage","Collect worktree coverage")]},BUILD_READ_TEST_RESULTS:{fields:[p("buildId","Build ID")]},BUILD_READ_COVERAGE:{fields:[p("buildId","Build ID")]},BUILD_IMPORT_COVERAGE:{fields:[w("worktreeId","Worktree","worktree"),p("buildName","Build name",{default:"{{workflow.name}}",help:"Name shown on the build and coverage pages. Defaults to the workflow name."}),p("reportPath","Coverage file",{required:!0,default:"coverage/lcov.info",help:"Path inside the worktree, written by whichever test command ran first."}),y("format","Coverage format",o(["AUTO","LCOV","ISTANBUL"]))]},BUILD_EXPORT:{fields:[p("buildId","Build ID"),I("settings","Export settings",{required:!0})]},BUILD_DEPLOY:{fields:[p("buildId","Build ID"),I("destinations","Destinations")]},BUILD_CANCEL:{fields:[p("buildId","Build ID")]},DISK_SPACE_LOAD:{fields:[w("agentId","Agent","agent")]},DISK_SPACE_REFRESH:{fields:[w("agentId","Agent","agent")]},DISK_SPACE_UPDATE_THRESHOLDS:{fields:[f("normalThresholdGiB","Normal threshold (GiB)",{required:!0}),f("pressureThresholdGiB","Pressure threshold (GiB)",{required:!0})]},DISK_SPACE_SET_MONITORING:{fields:[w("agentId","Agent","agent"),g("enabled","Monitoring enabled",{required:!0,default:!0})]},DISK_SPACE_SET_PRESSURE_MODE:{fields:[w("agentId","Agent","agent"),g("enabled","Manual pressure mode",{required:!0,default:!0})]},SKILL_APPLY:{fields:[w("groupId","Skill group","skillGroup",{help:"Leave empty to sync all skills."})]},NOTIFICATION_SEND:{fields:[p("title","Title",{required:!0}),m("body","Body",{required:!0}),p("href","Link")]},IOS_PUSH_SEND:{fields:[y("targetMode","Target mode",o(["ALL","DEVICES","BROADCAST","DIRECT"])),b("registrationIds","Registrations","apnsRegistration"),w("channelId","Broadcast channel","apnsChannel"),I("editor","Notification editor"),p("directToken","Direct device token"),y("directTokenEncoding","Token encoding",o(["HEX","BASE64"])),y("directEnvironment","Environment",o(["SANDBOX","PRODUCTION"]))]},COMMAND_RERUN:{fields:[p("commandRunId","Command run ID",{required:!0})]},COMMAND_TERMINATE:{fields:[p("commandRunId","Command run ID",{required:!0})]},COMMAND_READ_OUTPUT:{fields:[p("commandRunId","Command run ID",{required:!0}),f("first","Maximum chunks")]},WORKTREE_INSPECT_DIFF:{fields:[p("worktreeId","Worktree ID"),p("scope","Diff scope",{required:!0}),p("path","Path"),p("previousPath","Previous path"),p("commitSha","Commit SHA")]},WORKTREE_UPDATE_METADATA:{fields:[p("worktreeId","Worktree ID"),p("baseBranch","Base branch"),p("highlightColor","Highlight color")]},WORKTREE_MOVE_CONTROL:{fields:[p("moveId","Move ID",{required:!0}),y("operation","Operation",o(["RETRY_WITH_STASH","CANCEL"]))]},BUILD_REBUILD:{fields:[p("buildId","Build ID")]},BUILD_GENERATE_REPORT:{fields:[p("buildId","Build ID"),y("reportKind","Report kind",o(["TEST_RESULTS","CODE_COVERAGE"]))]},BUILD_DELETE:{fields:[E("buildIds","Build IDs")]},SKILL_PREPARE_SYNC:{fields:[y("syncKind","Sync kind",o(["ALL","GROUP"])),p("groupId","Skill group ID")]},SKILL_RESOLVE_SYNC:{fields:[p("runId","Sync run ID",{required:!0}),p("itemId","Conflict item ID",{required:!0}),y("resolution","Resolution",o(["LOCAL","REMOTE","SKIP"]))]},SKILL_SKIP_SYNC:{fields:[p("runId","Sync run ID",{required:!0})]},BUILD_DATA_REFRESH:{fields:[]},BUILD_DATA_DELETE:{fields:[p("collectionId","Collection ID",{required:!0}),E("entryIds","Entry IDs"),g("overrideProtection","Override protection")]},BUILD_DATA_SET_LOCK:{fields:[p("collectionId","Collection ID",{required:!0}),p("entryId","Entry ID",{required:!0}),g("locked","Locked")]},TAILSCALE_SERVE_INSPECT:{fields:[b("agentIds","Agents","agent")]},TAILSCALE_SERVE_UPSERT_TEMPLATE:{fields:[p("templateId","Template ID"),f("expectedRevision","Expected revision",{minimum:1,integer:!0}),p("name","Template name",{required:!0}),y("protocol","Listener protocol",o(["HTTP","HTTPS","TCP","TLS_TERMINATED_TCP"]),{required:!0,default:"HTTPS"}),f("listenPort","Incoming port",{required:!0,default:443,minimum:1,maximum:65535,integer:!0}),p("mountPath","Mount path",{default:"/"}),y("destinationProtocol","Destination protocol",o(["HTTP","HTTPS","HTTPS_INSECURE","TCP"]),{required:!0,default:"HTTP"}),f("destinationPort","Destination port",{required:!0,default:3e3,minimum:1,maximum:65535,integer:!0}),p("destinationPath","Destination path",{default:""}),g("funnel","Public Funnel"),E("appCapabilities","App capabilities"),y("proxyProtocol","PROXY protocol",o(["NONE","V1","V2"]),{required:!0,default:"NONE"}),b("agentIds","Enabled agents","agent",{required:!0})]},TAILSCALE_SERVE_SET_AGENT_ENABLED:{fields:[p("templateId","Template ID",{required:!0}),w("agentId","Agent","agent",{required:!0}),g("enabled","Enabled"),f("expectedRevision","Expected revision",{required:!0})]},TAILSCALE_SERVE_DELETE_TEMPLATE:{fields:[p("templateId","Template ID",{required:!0}),f("expectedRevision","Expected revision",{required:!0})]},SIGNING_REFRESH:{fields:[E("agentIds","Agent IDs")]},SIGNING_SYNC_PROFILE:{fields:[p("uuid","Profile UUID",{required:!0}),p("sourceAgentId","Source agent ID",{required:!0}),E("targetAgentIds","Target agent IDs")]},SIGNING_DELETE_EXPIRED:{fields:[E("agentIds","Agent IDs")]},IOS_DEVICE_REGISTER:{fields:[p("deviceId","Device ID",{required:!0})]},IOS_DEVICE_REJECT:{fields:[p("deviceId","Device ID",{required:!0})]},AGENT_RECONCILE:{fields:[E("agentIds","Agent IDs")]},AGENT_UPDATE_CADENCE:{fields:[p("agentId","Agent ID",{required:!0}),I("settings","Cadence settings")]},CCUSAGE_COLLECT:{fields:[]},MODEL_COST_REFRESH:{fields:[]},GITHUB_UPDATE_PR:{fields:[p("owner","Owner",{required:!0}),p("name","Repository",{required:!0}),f("number","Pull request number",{required:!0}),p("title","Title"),m("body","Body"),g("draft","Draft")]},GITHUB_SUBMIT_REVIEW:{fields:[p("owner","Owner",{required:!0}),p("name","Repository",{required:!0}),f("number","Pull request number",{required:!0}),y("event","Review event",o(["APPROVE","REQUEST_CHANGES","COMMENT"])),m("body","Body")]},GITHUB_REQUEST_REVIEWERS:{fields:[p("owner","Owner",{required:!0}),p("name","Repository",{required:!0}),f("number","Pull request number",{required:!0}),E("reviewers","Reviewers"),E("teamReviewers","Team reviewers")]},GITHUB_DISPATCH_WORKFLOW:{fields:[p("repositoryId","Repository ID",{required:!0}),p("workflowId","Workflow ID",{required:!0}),p("ref","Git ref",{required:!0}),v("inputs","Workflow inputs")]},JIRA_CREATE_TICKET:{fields:[p("projectKey","Project key",{required:!0}),p("issueTypeId","Issue type ID",{required:!0}),p("summary","Summary",{required:!0}),m("description","Description"),I("fields","Additional fields")]},JIRA_ADD_WORKLOG:{fields:[p("issueKey","Issue key"),f("timeSpentSeconds","Time spent (seconds)",{required:!0}),p("startedAt","Started at"),m("comment","Comment")]},JIRA_LINK_TICKETS:{fields:[p("inwardIssueKey","Inward issue key",{required:!0}),p("outwardIssueKey","Outward issue key",{required:!0}),p("linkType","Link type",{required:!0})]},MCP_CALL:{fields:[w("groupId","MCP server","mcpServer",{required:!0}),p("name","Tool name",{required:!0}),I("arguments","Arguments")]},SSE_ENDPOINT_ACTION:{fields:[y("operation","Operation",o(["CREATE","UPDATE","SET_MODE","ROTATE_TOKEN","DELETE"]),{required:!0}),p("endpointId","Endpoint ID"),I("input","Endpoint input")]},SSE_MOCK_ACTION:{fields:[y("operation","Operation",o(["SAVE_TEMPLATE","DELETE_TEMPLATE","SAVE_COMPOSITION","ACTIVATE_COMPOSITION","DELETE_COMPOSITION"]),{required:!0}),p("endpointId","Endpoint ID"),p("resourceId","Template or composition ID"),I("input","Mock input")]},SSE_STORAGE_ACTION:{fields:[y("operation","Operation",o(["SET","COMPARE_AND_SET","INCREMENT","DELETE"]),{required:!0}),p("key","Storage key",{required:!0}),I("value","JSON value"),f("expectedVersion","Expected version"),f("delta","Increment amount")]},SSE_BREAKPOINT_RESOLVE:{fields:[p("breakpointId","Breakpoint ID",{required:!0}),f("version","Version",{required:!0,integer:!0}),y("resolution","Resolution",o(["FORWARD","SAVED_MOCK","AD_HOC"]),{required:!0}),p("mockCompositionId","Mock composition ID"),I("adHocComposition","Ad hoc composition")]},SSE_HISTORY_CLEAR:{fields:[p("endpointId","Endpoint ID"),E("ids","Request IDs")]},SSE_SCRIPT_TEST:{fields:[m("source","JavaScript",{required:!0}),I("context","Script context"),f("timeoutMs","Timeout (ms)",{integer:!0}),f("memoryLimitMb","Memory limit (MiB)",{integer:!0}),f("fetchTimeoutMs","Fetch timeout (ms)",{integer:!0})]},RUN_CREATE_PLAN:{fields:C("PLAN")},RUN_CREATE_SESSION:{fields:C("SESSION")},RUN_PLAY_PLAN:{fields:[p("runId","Plan run ID"),S("SESSION"),f("worktreeConcurrencyLimit","Worktree concurrency limit",{default:1,minimum:0,maximum:32,integer:!0,help:"Maximum sessions admitted on this worktree. Use 0 for unlimited."})]},RUN_FOLLOW_UP:{fields:[p("runId","Source run ID"),...C(null),y("followUpMode","Follow-up mode",o(["RESUME","FRESH","RESEND"])),p("contextMode","Context mode")]},RUN_STEER:{fields:[p("runId","Run ID"),m("prompt","Steering prompt",{required:!0}),E("attachmentIds","Attachment IDs")]},RUN_ANSWER:{fields:[p("batchId","Question batch ID",{required:!0}),I("answers","Answers")]},RUN_PAUSE:{fields:[p("runId","Run ID")]},RUN_CONTINUE:{fields:[p("runId","Run ID")]},RUN_CANCEL:{fields:[p("runId","Run ID")]},RUN_REVISE_ANSWER:{fields:[p("batchId","Question batch ID",{required:!0}),I("answers","Answers"),g("stash","Stash before revision"),g("rollback","Roll back to the question")]},RUN_READ_RESULT:{fields:[p("runId","Run ID")]},RUN_CAPTURE_CHECKPOINT:{fields:[p("runId","Run ID")]},RUN_ARCHIVE_DELETE:{fields:[p("runId","Run ID"),g("delete","Delete permanently"),g("archived","Archive")]},HUMAN_CONFIRM:{fields:[m("prompt","Prompt")]},HUMAN_CHOICE:{fields:[m("prompt","Prompt"),g("multiSelect","Allow multiple selections"),g("allowCustom","Allow a custom answer"),((e,t,r={})=>({key:e,label:t,control:"choiceOptions",valueModes:h,...r}))("options","Buttons")]},CONTROL_IF:{fields:[((e,t,r={})=>({key:e,label:t,control:"condition",valueModes:h,...r}))("condition","Condition",{required:!0})]},CONTROL_JOIN:{fields:[y("mode","Join mode",l([{value:"ALL",label:"All — wait for every branch"},{value:"ANY",label:"Any — continue on the first branch"}]),{help:"All (default) waits until every incoming branch has finished before continuing. Any continues as soon as the first incoming branch arrives, and the remaining branches keep running on their own. Either way, branches that were skipped do not block the join, and the join itself is skipped when no branch reaches it."})]},CONTROL_DELAY:{fields:[f("seconds","Delay (seconds)",{required:!0})]},CONTROL_WAIT_UNTIL:{fields:[I("condition","Condition",{required:!0})]},CONTROL_FOR_EACH:{fields:[p("listPath","List session path",{placeholder:"pr.unresolvedThreads"}),I("items","Inline items"),y("errorMode","Error handling",l([{value:"FAIL_FAST",label:"Fail fast"},{value:"COLLECT_ERRORS",label:"Collect errors"}]))]},CONTROL_TRY:{fields:[]},CONTROL_SET_VARIABLE:{fields:[p("path","Output path",{required:!0,placeholder:"flags.ready"}),I("value","Value"),m("script","Script")]},CONTROL_SUBWORKFLOW:{fields:[p("versionId","Sub-workflow version ID",{required:!0}),I("inputMapping","Input mapping")]},SAVED_COMMAND:{fields:[w("commandId","Saved command ID","savedCommand",{required:!0}),y("completionMode","Completion",o(["WAIT_FOR_EXIT","FIRE_AND_FORGET"])),y("targetMode","Target",o(["CONTEXT","FIXED_AGENT","FIXED_WORKTREE"])),p("agentId","Fixed agent ID",{visibleWhen:{key:"targetMode",equals:"FIXED_AGENT"}}),p("worktreeId","Fixed worktree ID",{visibleWhen:{key:"targetMode",equals:"FIXED_WORKTREE"}}),p("outputPattern","Output match pattern (RE2)",{placeholder:"ready on port ([0-9]+)",help:"Optional case-sensitive regex. Requires Wait for exit and emits through the match connector while the command runs.",valueModes:["literal"]}),y("outputMatchMode","Output match behavior",o(["ONCE","EACH_MATCH"]),{default:"ONCE"})]},CUSTOM_COMMAND:{fields:[m("script","Script",{required:!0}),y("completionMode","Completion",o(["WAIT_FOR_EXIT","FIRE_AND_FORGET"])),y("targetMode","Target",o(["CONTEXT","FIXED_AGENT","FIXED_WORKTREE"])),p("agentId","Fixed agent ID",{visibleWhen:{key:"targetMode",equals:"FIXED_AGENT"}}),p("worktreeId","Fixed worktree ID",{visibleWhen:{key:"targetMode",equals:"FIXED_WORKTREE"}}),p("outputPattern","Output match pattern (RE2)",{placeholder:"ready on port ([0-9]+)",help:"Optional case-sensitive regex. Requires Wait for exit and emits through the match connector while the command runs.",valueModes:["literal"]}),y("outputMatchMode","Output match behavior",o(["ONCE","EACH_MATCH"]),{default:"ONCE"})]},TERMINAL_RUN:{fields:[m("script","Script",{required:!0}),y("interpreter","Interpreter",o(["SHELL","NODE"])),v("environment","Environment variables"),I("credentials","Credential environment",{help:"JSON array of { name, credential: { id, kind, ownerId } } entries."})]}},N=()=>f("timeoutSeconds","Timeout (seconds)",{help:"How long to keep waiting before the step fails. Leave empty to wait for as long as the work takes."});function O(e,t){for(let r of e){let e=R[r];if(!e)continue;let i=new Set(e.fields.map(({key:e})=>e));e.fields=[...e.fields,...t().filter(({key:e})=>!i.has(e))]}}function D(e=[]){return{fields:[...e,v("filters","Filters",{help:"Match when each session path equals the given value.",recordValueType:"json"})]}}O(["WORKTREE_CREATE","WORKTREE_CHANGE_BRANCH","WORKTREE_OPERATION","WORKTREE_PREPARATION","WORKTREE_SET_AUTO_SYNC","WORKTREE_DELETE","WORKTREE_GIT_OPERATION","WORKTREE_MOVE","WORKTREE_WAIT_PUSH_READY","WORKTREE_SNAPSHOT","CODEBASE_FETCH_REFRESH","CODEBASE_GIT_OPERATION","BUILD_START","BUILD_IMPORT_COVERAGE","BUILD_EXPORT","BUILD_DEPLOY","DISK_SPACE_REFRESH","TERMINAL_RUN","RUN_CREATE_PLAN","RUN_CREATE_SESSION","RUN_PLAY_PLAN","RUN_FOLLOW_UP","RUN_REVISE_ANSWER","SAVED_COMMAND","CUSTOM_COMMAND","COMMAND_RERUN","BUILD_REBUILD","BUILD_DATA_REFRESH","TAILSCALE_SERVE_INSPECT","TAILSCALE_SERVE_UPSERT_TEMPLATE","TAILSCALE_SERVE_SET_AGENT_ENABLED","TAILSCALE_SERVE_DELETE_TEMPLATE","SIGNING_REFRESH","SIGNING_SYNC_PROFILE","SIGNING_DELETE_EXPIRED","SKILL_APPLY","GITHUB_WAIT_CHECKS","GITLAB_WAIT_PIPELINE","CONTROL_SUBWORKFLOW","CONTROL_WAIT_UNTIL"],()=>[f("cadenceSeconds","Poll cadence (seconds)",{help:"How often to check whether the work has finished. Leave empty for this step's default."}),N()]),O(["HUMAN_CONFIRM","HUMAN_CHOICE"],()=>[N()]);let P=["BUILD_TEST_THRESHOLD","BUILD_COVERAGE_THRESHOLD","AGENT_DISK_THRESHOLD","CCUSAGE_THRESHOLD","RUN_USAGE_THRESHOLD","BUILD_DATA_THRESHOLD","AGENT_RESOURCE_THRESHOLD","SIGNING_ASSET_EXPIRING"],x=Object.fromEntries(["MANUAL","MANUAL_CHOICE","RESOURCE_MANUAL","RESOURCE_MANUAL_CHOICE","SCHEDULE","WORKFLOW_FINISHED","GITHUB_PR_STATE","GITHUB_REVIEW_CHANGES_REQUESTED","GITHUB_REVIEW_COMMENT","GITHUB_PR_CLOSED","GITHUB_CHECK_FAILED","GITHUB_PUSH_DEFAULT","GITHUB_WORKFLOW_SUCCEEDED","GITHUB_ISSUE_COMMAND","GITHUB_ACTIONS_RESULT","GITHUB_PR_LABEL","GITLAB_MR_STATE","GITLAB_REVIEW_CHANGES_REQUESTED","GITLAB_REVIEW_COMMENT","GITLAB_MR_CLOSED","GITLAB_PIPELINE_FAILED","GITLAB_PUSH_DEFAULT","GITLAB_PIPELINE_SUCCEEDED","GITLAB_NOTE_COMMAND","GITLAB_PIPELINE_RESULT","GITLAB_MR_LABEL","BUILD_RESULT","BUILD_TEST_THRESHOLD","BUILD_COVERAGE_THRESHOLD","BUILD_HOOK_FAILED","AGENT_CONNECTION","AGENT_JOB_FAILED","AGENT_DISK_REPORT","AGENT_DISK_THRESHOLD","AGENT_DISK_STATE_CHANGED","AGENT_DISK_CLEANUP_RESULT","CCUSAGE_THRESHOLD","WORKTREE_CREATED","WORKTREE_BEHIND","WORKTREE_CONFLICT","WORKTREE_MISSING","WORKTREE_DIVERGED","WORKTREE_DIRTY_DURATION","WORKTREE_NEW_COMMIT","CODEBASE_REMOTE_BRANCH","JIRA_STATUS","JIRA_LABEL","JIRA_ASSIGNED_SELF","JIRA_SOURCE_NEW_TICKET","JIRA_MENTION","JIRA_SPRINT_STARTED","JIRA_ISSUE_CREATED","JIRA_ISSUE_DELETED","JIRA_ISSUE_COMMAND","JIRA_ATTACHMENT_ADDED","JIRA_ISSUE_LINKED","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","COMMAND_RUN_RESULT","COMMAND_OUTPUT_MATCH","SKILL_SYNC_RESULT","SKILL_SYNC_CONFLICT","GITHUB_PIPELINE_STATUS_CHANGED","GITHUB_PR_SYNCHRONIZED","GITHUB_REVIEW_APPROVED","GITLAB_PIPELINE_STATUS_CHANGED","GITLAB_MR_SYNCHRONIZED","GITLAB_REVIEW_APPROVED","GITLAB_JOB_STATUS_CHANGED","JIRA_TICKET_UPDATED","JIRA_COMMENT_ADDED","JIRA_WORKLOG_ADDED","JIRA_SPRINT_ENDED","CODEBASE_SYNC_STATE_CHANGED","CODEBASE_OPERATION_FAILED","WORKTREE_SYNC_STATE_CHANGED","WORKTREE_AUTOMATION_RESULT","WORKTREE_CLEAN","PUSH_NOTIFICATION_RESULT","IOS_DEVICE_ENROLLED","IOS_DEVICE_REGISTRATION_RESULT","SIGNING_OPERATION_RESULT","SIGNING_ASSET_EXPIRING","BUILD_DATA_THRESHOLD","BUILD_DATA_CLEANUP_RESULT","POLLING_OPERATION_STATE","MODEL_COST_CATALOG_CHANGED","CREDENTIAL_STORE_DEGRADED","AGENT_RESOURCE_THRESHOLD","AGENT_VERSION_CHANGED","TOOL_CALL_RESULT","SSE_REQUEST_OPENED","SSE_EVENT_EMITTED","SSE_BREAKPOINT_WAITING","SSE_BREAKPOINT_RESOLVED","SSE_STREAM_COMPLETED","SSE_STREAM_FAILED"].map(e=>{if("RESOURCE_MANUAL"===e||"RESOURCE_MANUAL_CHOICE"===e)return[e,D([y("resourceKind","Resource kind",o(n.WORKFLOW_RESOURCE_KINDS),{required:!0}),..."RESOURCE_MANUAL_CHOICE"===e?[A("choices","Choices",{required:!0})]:[]])];if("MANUAL_CHOICE"===e)return[e,D([A("choices","Choices",{required:!0})])];if("SCHEDULE"===e)return[e,D([f("cadenceSeconds","Cadence (seconds)",{required:!0})])];if("GITHUB_ISSUE_COMMAND"===e||"GITLAB_NOTE_COMMAND"===e){let t="GITLAB_NOTE_COMMAND"===e;return[e,D([E(t?"allowedUsernames":"allowedLogins",t?"Allowed usernames":"Allowed logins",{placeholder:"octocat",required:!0}),p("commandPattern","Command pattern (RE2)",{placeholder:"^/deploy\\b$",required:!0,valueModes:["literal","interpolation"]})])]}return"JIRA_ISSUE_COMMAND"===e?[e,D([E("allowedAccountIds","Allowed account IDs",{placeholder:"5b10a2844c20165700ede21g",required:!0}),p("commandPattern","Command pattern (RE2)",{placeholder:"^/deploy\\b$",required:!0,valueModes:["literal","interpolation"]})])]:"COMMAND_OUTPUT_MATCH"===e?[e,D([p("outputPattern","Output pattern (RE2)",{placeholder:"error|failed",required:!0,valueModes:["literal","interpolation"]})])]:P.includes(e)?[e,D([p("thresholdPath","Threshold path",{placeholder:"build.testSummary.failed"}),y("thresholdOperator","Operator",k),I("thresholdValue","Threshold value")])]:[e,D()]}));function L(e,t){return"step"===t?R[e]:x[e]}function U(e,t,r){let i=function(e,t){let r=L(e,t);if(!r)return null;let i=new Set,a=new Set;for(let e of r.fields){for(let t of"model"===e.control&&e.modelKeys?[e.modelKeys.provider,e.modelKeys.model,e.modelKeys.effort]:[e.key])i.add(t);e.required&&a.add(e.key)}return{described:i,required:a}}(e,t);if(!i||!r||"object"!=typeof r||Array.isArray(r))return(0,s.workflowValueSessionPaths)(r);let a=new Set;for(let[e,t]of Object.entries(r))(!i.described.has(e)||i.required.has(e))&&(0,s.workflowValueSessionPaths)(t,a);return a}e.s(["getConfigDescriptor",0,L,"requiredConfigSessionPaths",0,U],248626);let B=["EQ","NE","GT","GTE","LT","LTE","CONTAINS","MATCHES","EXISTS"],M={type:"object",title:"Session binding",description:"Reads the value from run session data at `path` instead of hard-coding it.",properties:{source:{const:"SESSION"},path:{type:"string",description:"Dotted session path, e.g. `ticket.key` or `pr.number`."}},required:["source","path"],additionalProperties:!1},q={type:"object",title:"Literal wrapper",description:"An explicit constant. Equivalent to writing the value directly; the editor uses it to record that a field was pinned rather than bound.",properties:{source:{const:"LITERAL"},value:{}},required:["source"],additionalProperties:!1};function j(e,t,r){let i=r.valueModes??[],a=[i.includes("session")?"May also be a session binding.":null,i.includes("interpolation")?"Strings here — including strings nested inside the value — may carry `{{path}}` interpolation tokens, e.g. `{{worktree.baseBranch}}`.":null].filter(Boolean),n=a.length?{...t,description:[t.description,...a].filter(Boolean).join(" ")}:t;return i.includes("session")?{anyOf:[e,M,q],...n}:{...e,...n}}function $(e){let t=e.options?function(e){if("static"===e.kind){let t=e.options.filter(({label:e})=>e);return t.length?t.map(({value:e,label:t})=>`\`${e}\` — ${t}`).join("; "):null}let t=e.scopeFrom?` Scoped by the sibling \`${e.scopeFrom}\` value.`:"",r=e.sessionPath?` Usually bound to \`${e.sessionPath}\`.`:"";return`Identifier of a ${e.resource} known to the control plane.${r}${t}`}(e.options):null,r={description:[e.label,e.help,t].filter(Boolean).join(" — ")};return e.placeholder&&(r.examples=[e.placeholder]),void 0!==e.default&&(r.default=e.default),j(function(e){switch(e.control){case"number":return{type:e.integer?"integer":"number",...void 0===e.minimum?{}:{minimum:e.minimum},...void 0===e.maximum?{}:{maximum:e.maximum}};case"boolean":return{type:"boolean"};case"enum":{let t=e.options;if(t?.kind==="static")return{type:"string",enum:t.options.map(({value:e})=>e)};return{type:"string"}}case"resource":case"model":case"text":default:return{type:"string"};case"resourceMulti":case"stringList":case"mcpPresetMulti":return{type:"array",items:{type:"string"}};case"record":return{type:"object",additionalProperties:"json"===e.recordValueType?{}:{type:"string"}};case"condition":return{$ref:"#/$defs/condition"};case"choiceOptions":return{type:"array",description:"Buttons offered to the person answering.",items:{type:"object",properties:{label:{type:"string"},description:{type:"string"}},required:["label"],additionalProperties:!1}};case"triggerChoices":return{type:"array",minItems:1,description:"Options this trigger offers. Each `key` names an outgoing handle on the trigger, so edges stay attached when a label is renamed.",items:{type:"object",properties:{key:{type:"string",pattern:n.WORKFLOW_CHOICE_KEY_PATTERN.source},label:{type:"string"},description:{type:"string"}},required:["key","label"],additionalProperties:!1}};case"json":return{}}}(e),r,e)}function G(e,t){let r=L(e,t);if(!r)return{type:"object",additionalProperties:!0};let i={},a=[],n=!1;for(let e of r.fields){for(let[t,r]of("condition"===e.control&&(n=!0),"model"===e.control?function(e){let t=e.modelKeys;if(!t)return[[e.key,$(e)]];let r=(t,r)=>[t,j({type:"string"},{description:r},e)];return[r(t.provider,"AI provider that serves the model."),r(t.model,"Model identifier, as listed by the provider catalog."),r(t.effort,"Reasoning effort, when the model supports it.")]}(e):[[e.key,$(e)]]))i[t]=r;e.required&&a.push(e.key)}let s={type:"object",properties:i,additionalProperties:!0};return a.length&&(s.required=a),n&&(s.$defs={condition:{type:"object",description:"A condition tree. `ALL`/`ANY` combine nested conditions, `NOT` negates one, and the comparison operators test `left` against `right`.",anyOf:[{properties:{op:{enum:["ALL","ANY"]},conditions:{type:"array",items:{$ref:"#/$defs/condition"}}},required:["op","conditions"]},{properties:{op:{const:"NOT"},condition:{$ref:"#/$defs/condition"}},required:["op","condition"]},{properties:{op:{enum:[...B]},left:{description:"Value to test — usually a session binding. `EXISTS` needs only this side."},right:{description:"Value to compare against."}},required:["op","left"]}]}}),s}function F(e){let t=e?.outputPattern;return"string"==typeof t&&t.length?t:null}function z(e){if(!e.length)throw Error("Output pattern cannot be empty");if(e.length>1024)throw Error("Output pattern must not exceed 1024 characters")}e.s(["COMMAND_OUTPUT_MATCH_BUFFER_BYTES",0,0x1000000,"commandOutputMatchMode",0,function(e){return e?.outputMatchMode==="EACH_MATCH"?"EACH_MATCH":"ONCE"},"commandOutputPattern",0,F,"validateCommandOutputPattern",0,z],361617);let H="aide.workflow";function V(e){let t=e?.choices;if(!Array.isArray(t))return[];let r=[],i=new Set;for(let e of t)!(!e||"object"!=typeof e||Array.isArray(e))&&(!(0,n.isWorkflowChoiceKey)(e.key)||i.has(e.key)||(i.add(e.key),r.push({key:e.key,label:"string"==typeof e.label&&e.label.trim()?e.label:e.key,description:"string"==typeof e.description?e.description:""})));return r}let K={BUILD:["build.*","worktree.*","codebase.*","agent.*","repo.*","ticket.*"],CODEBASE:["codebase.*","agent.*","repo.*"],JIRA_TICKET:["ticket.*","comment.*"],AGENT_RUN:["run.*","worktree.*","codebase.*","agent.*","repo.*","ticket.*"],GITHUB_PIPELINE:["pipeline.*","repo.*","pr.*","worktree.*","codebase.*","agent.*","ticket.*"],GITHUB_JOB:["job.*","pipeline.*","repo.*","pr.*","worktree.*","codebase.*","agent.*","ticket.*"],GITLAB_MERGE_REQUEST:["pr.*","repo.*","worktree.*","ticket.*"],GITLAB_PIPELINE:["pipeline.*","repo.*","pr.*","worktree.*","ticket.*"],GITLAB_JOB:["job.*","pipeline.*","repo.*","pr.*","worktree.*","ticket.*"],PULL_REQUEST:["pr.number","repo.displayOrigin"],WORKTREE:["worktree.*","codebase.*","agent.*","repo.*","ticket.*","pr.*"],COMMAND_RUN:["command.*","agent.*","worktree.*","codebase.*","repo.*"],SKILL:["skill.*","repo.*","codebase.*"],SKILL_SYNC:["skillSync.*","skill.*","repo.*","codebase.*","worktree.*"],IOS_DEVICE:["device.*"],SIGNING_PROFILE:["signingProfile.*","device.*","agent.*"],PUSH_NOTIFICATION_BATCH:["pushBatch.*"],BUILD_DATA_COLLECTION:["buildData.*","agent.*","worktree.*","codebase.*"]};function W(e){let t=e?.resourceKind;return"string"==typeof t&&n.WORKFLOW_RESOURCE_KINDS.includes(t)?t:null}function J(e,t){if(!(0,n.isResourceTriggerKind)(e))return[];let r=W(t);return r?K[r]:[]}let Y=(e,t,r,i,a,s,o)=>({kind:e,category:t,label:r,description:o.description,details:o.details,execution:i,configSchema:G(e,"step"),capabilityFlags:[i,...o.mutatesExternal?["MUTATES_EXTERNAL"]:[],...o.mutatesWorktree?["MUTATES_WORKTREE"]:[]],requiredPaths:a,providedPaths:s,sourceHandles:(0,n.workflowStaticSourceHandles)(e),mutatesExternal:o.mutatesExternal??!1,mutatesWorktree:o.mutatesWorktree??!1}),Q=["worktree.*","codebase.*","agent.*","repo.*","ticket.*","pr.*"],Z=["codebase.*","agent.*","repo.*"],X=(e,t,r,i=[],a=["steps.<stepId>.*"],n={})=>Y(e,t,r,"SERVER",i,a,{description:`${r} using the control plane's typed service API.`,details:`${r} is a first-class action with validated configuration, audit-friendly output, resource links where available, and normal workflow failure routing.`,...n}),ee=[X("COMMAND_RERUN","Commands","Rerun command",["command.id"],["command.*"]),X("COMMAND_TERMINATE","Commands","Terminate command",["command.id"],["command.*"]),X("COMMAND_READ_OUTPUT","Commands","Read command output",["command.id"],["command.*"]),X("WORKTREE_INSPECT_DIFF","Worktrees","Inspect worktree diff",["worktree.id"],["worktree.diff.*"]),X("WORKTREE_UPDATE_METADATA","Worktrees","Update worktree metadata",["worktree.id"],Q),X("WORKTREE_MOVE_CONTROL","Worktrees","Control worktree move",[],Q,{mutatesWorktree:!0}),X("BUILD_REBUILD","Builds","Rebuild build",["build.id"],["build.*"]),X("BUILD_GENERATE_REPORT","Builds","Generate build report",["build.id"],["build.*"]),X("BUILD_DELETE","Builds","Delete builds",[],["build.*"]),X("SKILL_PREPARE_SYNC","Skills","Prepare skill sync",[],["skillSync.*"]),X("SKILL_RESOLVE_SYNC","Skills","Resolve skill sync conflict",["skillSync.id"],["skillSync.*"]),X("SKILL_SKIP_SYNC","Skills","Skip skill sync",["skillSync.id"],["skillSync.*"]),X("BUILD_DATA_REFRESH","Build Data","Refresh build data",[],["buildData.*"]),X("BUILD_DATA_DELETE","Build Data","Delete build data",["buildData.id"],["buildData.*"]),X("BUILD_DATA_SET_LOCK","Build Data","Set build-data lock",["buildData.id"],["buildData.*"]),X("TAILSCALE_SERVE_INSPECT","Tailscale","Inspect Tailscale Serve",[],["tailscale.*"],{mutatesExternal:!0}),X("TAILSCALE_SERVE_UPSERT_TEMPLATE","Tailscale","Upsert Tailscale Serve template",[],["tailscale.*"],{mutatesExternal:!0}),X("TAILSCALE_SERVE_SET_AGENT_ENABLED","Tailscale","Set Tailscale Serve agent enabled",["tailscale.templateId"],["tailscale.*"],{mutatesExternal:!0}),X("TAILSCALE_SERVE_DELETE_TEMPLATE","Tailscale","Delete Tailscale Serve template",["tailscale.templateId"],["tailscale.*"],{mutatesExternal:!0}),X("SIGNING_REFRESH","Signing","Refresh signing assets",[],["signing.*"]),X("SIGNING_SYNC_PROFILE","Signing","Sync signing profile",["signingProfile.id"],["signing.*"]),X("SIGNING_DELETE_EXPIRED","Signing","Delete expired profiles",[],["signing.*"]),X("IOS_DEVICE_REGISTER","Devices","Register iOS device",["device.id"],["device.*"],{mutatesExternal:!0}),X("IOS_DEVICE_REJECT","Devices","Reject iOS device",["device.id"],["device.*"],{mutatesExternal:!0}),X("AGENT_RECONCILE","Agents","Reconcile agents",[],["agent.*"]),X("AGENT_UPDATE_CADENCE","Agents","Update agent cadence",["agent.id"],["agent.*"]),X("CCUSAGE_COLLECT","Operations","Collect usage",[],["usage.*"]),X("MODEL_COST_REFRESH","Operations","Refresh model costs",[],["modelCosts.*"],{mutatesExternal:!0}),X("GITHUB_UPDATE_PR","GitHub","Update pull request",["pr.number","repo.*"],["pr.*"],{mutatesExternal:!0}),X("GITHUB_SUBMIT_REVIEW","GitHub","Submit pull request review",["pr.number","repo.*"],["pr.*"],{mutatesExternal:!0}),X("GITHUB_REQUEST_REVIEWERS","GitHub","Request pull request reviewers",["pr.number","repo.*"],["pr.*"],{mutatesExternal:!0}),X("GITHUB_DISPATCH_WORKFLOW","GitHub","Dispatch GitHub workflow",["repo.*"],["pipeline.*"],{mutatesExternal:!0}),...[["GITLAB_LOAD_MR","Load merge request",!1],["GITLAB_CREATE_MR","Create merge request",!0],["GITLAB_UPDATE_MR","Update merge request",!0],["GITLAB_SUBMIT_REVIEW","Submit merge request review",!0],["GITLAB_REPLY_DISCUSSION","Reply to discussion",!0],["GITLAB_SET_DISCUSSION_RESOLVED","Resolve discussion",!0],["GITLAB_MERGE_MR","Merge merge request",!0],["GITLAB_SET_MR_LABELS","Set merge request labels",!0],["GITLAB_REQUEST_REVIEWERS","Request merge request reviewers",!0],["GITLAB_CREATE_PIPELINE","Create pipeline",!0],["GITLAB_RETRY_PIPELINE","Retry pipeline",!0],["GITLAB_RETRY_JOB","Retry job",!0],["GITLAB_CANCEL_PIPELINE","Cancel pipeline",!0]].map(([e,t,r])=>X(e,"GitLab",String(t),[],String(e).includes("PIPELINE")||String(e).includes("JOB")?["pipeline.*","job.*"]:["pr.*"],{mutatesExternal:!!r})),X("GITLAB_SAVE_AUTO_RETRY","GitLab Pipelines","Install auto-retry rule",["pipeline.id"],[],{mutatesExternal:!0}),X("GITLAB_WAIT_PIPELINE","GitLab Pipelines","Wait for pipeline",["pipeline.id"],["pipeline.*"]),X("JIRA_CREATE_TICKET","Jira","Create Jira ticket",[],["ticket.*"],{mutatesExternal:!0}),X("JIRA_ADD_WORKLOG","Jira","Add Jira worklog",["ticket.key"],["ticket.*"],{mutatesExternal:!0}),X("JIRA_LINK_TICKETS","Jira","Link Jira tickets",["ticket.key"],["ticket.*"],{mutatesExternal:!0})],et=[Y("JIRA_LOAD_TICKET","Jira","Load Jira ticket","SERVER",[],["ticket.*"],{description:"Reads a Jira issue and puts its fields — key, title, type, status, assignee, labels — into session data as `ticket.*`.",details:'Needs a configured Jira credential. Leave the identifier unset to take it from session data. Results are served from cache unless "Bypass cache" is set, so a step that reads a ticket right after changing it should force a refresh. Fails when the issue does not exist or the credential cannot see it. Read-only: it changes nothing in Jira.'}),Y("JIRA_TRANSITION","Jira","Transition Jira ticket","SERVER",["ticket.key"],["ticket.*"],{description:"Moves a ticket to another status by applying one of its workflow transitions.",details:"Takes a transition id, not a status name — the ids are board-specific, so read them from the ticket's available transitions rather than hard-coding a guess. Fails when the transition is not currently available on that issue, which is what happens if an earlier step already moved it. Refreshes `ticket.*` from the response.",mutatesExternal:!0}),Y("JIRA_COMMENT","Jira","Add Jira comment","SERVER",["ticket.key"],["ticket.*"],{description:"Posts a comment on a Jira issue, written in Markdown or Jira wiki markup.",details:"The comment body is converted from Markdown by default; choose Jira wiki format to pass markup through untouched. Comments are never deduplicated, so a step that runs twice comments twice — guard it with a condition if the workflow can retry. Refreshes `ticket.*` from the response.",mutatesExternal:!0}),Y("JIRA_ASSIGN","Jira","Assign Jira ticket","SERVER",["ticket.key"],["ticket.*"],{description:"Sets the assignee of a Jira issue, or clears it when no account is given.",details:"Takes a Jira account id rather than a display name or email. Leaving the assignee empty unassigns the ticket. Fails when the account cannot be assigned on that project. Refreshes `ticket.*` from the response.",mutatesExternal:!0}),Y("JIRA_UPDATE_FIELDS","Jira","Update Jira fields","SERVER",["ticket.key"],["ticket.*"],{description:"Patches arbitrary fields on a Jira issue — labels, summary, custom fields — from a JSON object.",details:"The escape hatch for anything the dedicated Jira steps do not cover. Keys are passed to the Jira update API as given, so an unknown or screen-hidden field fails the step. Prefer the specific steps for status and assignee. Refreshes `ticket.*` from the response.",mutatesExternal:!0}),Y("JIRA_RESOLVE_BRANCH","Jira","Resolve ticket branch","SERVER",["ticket.key","ticket.title","ticket.type"],["worktree.branch","ticket.key","ticket.title","ticket.type"],{description:"Works out the branch name a ticket would get under the codebase's naming convention, without creating anything.",details:"A preview step: it writes `worktree.branch` plus the ticket key, title, and type into session data and touches neither Git nor Jira. Use it before Create worktree when you want the branch name available to earlier steps — for a worktree keyed off a ticket, Create worktree in TICKET mode derives the same name on its own."}),Y("GITHUB_LOAD_PR","GitHub","Load pull request","SERVER",[],["pr.*"],{description:"Reads a pull request and puts its state, branches, labels, checks, and review threads into session data as `pr.*`.",details:"Needs a configured GitHub credential. Owner and repository default to the repository already in session data, and the number to `pr.number`. Fails when the pull request does not exist or the credential cannot see it. Read-only."}),Y("GITHUB_MERGE_PR","GitHub","Merge pull request","SERVER",["pr.number"],["pr.state"],{description:"Merges an open pull request using squash, merge, or rebase, optionally overriding the commit message.",details:"Checks mergeability first and fails with GitHub's own blocking reason — conflicts, failing required checks, missing approvals, an already-closed pull request — rather than forcing the merge. Commit headline and body default to what GitHub would use. Squash is the default method. Irreversible, and repository policy may delete the head branch as a side effect, which strands any worktree still on it. Writes `pr.state`.",mutatesExternal:!0}),Y("GITHUB_COLLECT_REVIEW_THREADS","GitHub","Collect review comments","SERVER",["pr.number"],["pr.unresolvedThreads"],{description:"Gathers the unresolved review threads on a pull request into `pr.unresolvedThreads`.",details:"Resolved threads are filtered out. The result is a list, so it pairs with For each to work through the comments one at a time — the reply and resolve steps take a single thread id from the iteration. Read-only."}),Y("GITHUB_REPLY_REVIEW_THREAD","GitHub","Reply to review thread","SERVER",["pr.unresolvedThreads"],[],{description:"Posts a reply into an existing pull request review thread.",details:"Takes the thread id from Collect review comments, usually inside a For each. Replies are not deduplicated, so a retried step comments twice. Replying does not resolve the thread — follow with Resolve review thread when that is the intent.",mutatesExternal:!0}),Y("GITHUB_SET_REVIEW_THREAD_RESOLVED","GitHub","Resolve review thread","SERVER",["pr.unresolvedThreads"],[],{description:"Marks a pull request review thread resolved, or reopens it.",details:"Takes the thread id from Collect review comments. Resolving is the default; clear the flag to unresolve. Reviewers see this as the bot resolving their comment, so it is usually paired with a reply that explains what changed.",mutatesExternal:!0}),Y("GITHUB_CREATE_PR","GitHub","Open pull request","SERVER",["worktree.branch","worktree.baseBranch"],["pr.*"],{description:"Opens a pull request from the worktree's branch, optionally as a draft.",details:"Head branch defaults to `worktree.branch`, base to `worktree.baseBranch`, and the title to `ticket.title`. The head branch must already be pushed — put Wait for push-ready or a push operation in front of this step. Fails when a pull request is already open for the same branch pair. Writes the new pull request to `pr.*`.",mutatesExternal:!0}),Y("GITHUB_SET_PR_LABELS","GitHub","Set pull request labels","SERVER",["pr.number"],["pr.labels"],{description:"Replaces the labels on a pull request with the given list.",details:"This sets rather than adds — labels not in the list are removed, so include the ones you want to keep. Labels must already exist in the repository. Writes `pr.labels`.",mutatesExternal:!0}),Y("GITHUB_RETRY_PIPELINE","GitHub Actions","Retry failed pipeline","SERVER",["pipeline.runId"],["pipeline.status"],{description:"Re-runs the failed jobs of a check suite, leaving the jobs that passed alone.",details:"Targets a check suite rather than a single job — use Retry workflow job for that. Re-running consumes Actions minutes and re-executes whatever those jobs do, including deployments. Pair it with a Time delay and a retry limit so a permanently broken pipeline is not retried forever. Writes `pipeline.status`.",mutatesExternal:!0}),Y("GITHUB_RETRY_JOB","GitHub Actions","Retry workflow job","SERVER",["pipeline.failedJobs"],[],{description:"Re-runs one job of a GitHub Actions workflow run.",details:"Needs the repository, check suite, and job ids together — typically read out of `pipeline.failedJobs` inside a For each. Use Retry failed pipeline to re-run every failed job at once instead.",mutatesExternal:!0}),Y("GITHUB_CANCEL_WORKFLOW_RUN","GitHub Actions","Cancel workflow run","SERVER",["pipeline.runId"],["pipeline.status"],{description:"Cancels an in-progress GitHub Actions workflow run.",details:"Falls back to `repo.id` and `pipeline.runId` from session data. Force-cancel skips the graceful shutdown that lets `always()` cleanup jobs finish, so leave it off unless a run is stuck. Cancelling a run that has already finished is an error. Writes `pipeline.status`.",mutatesExternal:!0}),Y("GITHUB_SAVE_AUTO_RETRY","GitHub Actions","Install auto-retry rule","SERVER",["pipeline.runId"],[],{description:"Saves a standing rule that automatically retries matching GitHub Actions failures.",details:"Persists configuration rather than acting once — the rule keeps applying after this run ends, and stays until something removes it. Takes the rule as a JSON object. Treat it as a settings change, not a step you re-run casually.",mutatesExternal:!0}),Y("GITHUB_WAIT_CHECKS","GitHub Actions","Wait for checks","WAIT",["pipeline.runId"],["pipeline.status","pipeline.conclusion","pipeline.jobs"],{description:"Parks the run until a GitHub Actions workflow run finishes, then continues on its conclusion.",details:"Polls until the run reaches a terminal status. Anything other than success fails the step, so route the failure handle to the recovery path — or set the step's failure policy to continue and branch on `pipeline.conclusion` yourself. Also refreshes `pipeline.jobs`. Without a timeout the wait is open-ended; a hung pipeline holds the workflow run indefinitely. Falls back to `repo.id` and `pipeline.runId`."}),Y("WORKTREE_CREATE","Worktrees","Create worktree","SERVER",["codebase.id"],Q,{description:"Creates a Git worktree on the agent for a new, existing, or ticket-derived branch.",details:"Dispatches a job to the agent that owns the codebase and waits for it, so the agent must be online. Branch mode NEW cuts a branch from the base, EXISTING checks one out, and TICKET derives the name from `ticket.key`. Base branch falls back to `worktree.baseBranch` then `repo.defaultBranch`. Refreshes the created worktree, codebase, owning agent, repository, and any linked ticket. Creates real directories on disk.",mutatesWorktree:!0}),Y("WORKTREE_CHANGE_BRANCH","Worktrees","Change worktree branch","SERVER",["worktree.id"],Q,{description:"Switches an existing worktree to a different branch, creating it if needed.",details:'Same branch modes as Create worktree. Uncommitted changes block the switch unless "Stash on failure" is set, which stashes them and retries — the stash is left for a human to deal with. Refreshes the worktree and all of its related resource context.',mutatesWorktree:!0}),Y("WORKTREE_COMMIT","Worktrees","Commit worktree changes","SERVER",["worktree.id"],Q,{description:"Stages selected worktree changes and creates a Git commit on the agent.",details:"Stage all defaults on. Disable it and provide an exact list of changed paths for a partial commit; paths omitted from that list are left uncommitted. Signed commits follow effective Git configuration when the signed option is omitted. Dispatches an agent job, waits for completion, and refreshes worktree context.",mutatesWorktree:!0}),Y("WORKTREE_REFRESH_PULL_REQUEST","Worktrees","Refresh pull request","SERVER",["worktree.id"],["pr.*"],{description:"Forces exact-branch pull request discovery and refreshes the worktree's persisted pull request context.",details:"Uses the configured worktree, falling back to `worktree.id`. The step succeeds with `found: false` and clears `pr` when the branch has no open pull request.",mutatesWorktree:!0,mutatesExternal:!1}),Y("WORKTREE_OPERATION","Worktrees","Run worktree operation","SERVER",["worktree.id"],Q,{description:"Runs one of the built-in worktree maintenance operations, such as syncing with the base branch or pushing.",details:"Dispatches an agent job and waits for it. Opening an editor is rejected here — it needs a human at the machine. Sync and push touch the remote and can conflict; check `worktree.pushStatus` afterwards or follow with Inspect worktree Git state.",mutatesWorktree:!0}),Y("WORKTREE_PREPARATION","Worktrees","Run worktree preparations","SERVER",["worktree.id"],[],{description:"Inspects, applies, or undoes the repository preparation rules for one worktree.",details:"Dispatches a preparation job to the owning agent and waits for its per-file result. Apply and Undo can overwrite managed paths, while Inspect only refreshes persisted status. Unsupported, offline, and unavailable worktrees fail with the service's explicit skip reason.",mutatesWorktree:!0}),Y("WORKTREE_SET_AUTO_SYNC","Worktrees","Set worktree Auto Sync","SERVER",["worktree.id"],["worktree.autoSync"],{description:"Enables, updates, retries, or cancels persistent Auto Sync for a worktree.",details:"An enabled rule rebases on the target branch whenever it changes and force-pushes with lease. A merge-conflict quick-action workflow can be selected as the automatic recovery path; unresolved conflicts pause the rule. Force is accepted only when preparations paused Auto Sync, destructively resets managed paths, and resumes the rule after a successful sync.",mutatesWorktree:!0,mutatesExternal:!0}),Y("WORKTREE_SET_AUTO_MERGE","Worktrees","Set worktree Auto Merge","SERVER",["worktree.id"],["worktree.autoMerge"],{description:"Enables, updates, retries, or cancels GitHub-native Auto Merge for a worktree.",details:"GitHub remains the authority for required checks and reviews. Optional post-merge actions can move the linked Jira ticket to its configured done status and safely delete a clean linked worktree.",mutatesWorktree:!0,mutatesExternal:!0}),Y("WORKTREE_DELETE","Worktrees","Delete worktree","SERVER",["worktree.id"],Z,{description:"Removes a worktree from the agent, optionally deleting its remote branch too.",details:"Destroys the directory and any uncommitted work in it — there is no undo. Deleting the remote branch as well affects everyone, and closes any pull request from that branch. Do not put this before steps that still read `worktree.*`.",mutatesWorktree:!0}),Y("WORKTREE_MOVE","Worktrees","Move worktree","SERVER",["worktree.id"],Q,{description:"Moves a worktree's branch and changes into another codebase, optionally deleting the source.",details:"Waits for the move job to finish. Used when a branch was started against the wrong checkout. Deleting the source destroys the original directory; leaving it keeps both, which means two worktrees on one branch. Refreshes `worktree.*` to point at wherever the work now lives.",mutatesWorktree:!0}),Y("WORKTREE_INSPECT","Worktrees","Inspect worktree","SERVER",["worktree.id"],["worktree.commits","worktree.changes","worktree.branchChanges","worktree.commitsTruncated","worktree.changesTruncated","worktree.branchChangesTruncated"],{description:"Reads the worktree's commits and changed files into `worktree.commits` and `worktree.changes`.",details:"Read-only. Use it to give a later condition or AI prompt something concrete to work from — for example to skip opening a pull request when nothing changed. For push/dirty state use Inspect worktree Git state instead, which is cheaper."}),Y("WORKTREE_INSPECT_GIT","Worktrees","Inspect worktree Git state","SERVER",["worktree.id"],["worktree.*"],{description:"Reads the worktree's Git status — dirty flag, ahead/behind counts, push status, conflicts — into `worktree.*`.",details:"Read-only and the cheap way to branch on repository state: gate a commit on `worktree.dirty`, or a sync on the worktree being behind. Use Inspect worktree when you need the actual commits and diffs."}),Y("WORKTREE_GIT_OPERATION","Worktrees","Run worktree Git operation","SERVER",["worktree.id"],Q,{description:"Runs a specific Git operation in the worktree — pull, push, rebase, stash, and the rest.",details:'Dispatches an agent job and waits for it. Operations that rewrite history or touch the remote can fail on conflicts; "Stash changes first" clears the way for operations that need a clean tree. Prefer Run worktree operation for the higher-level sync and push flows, which handle more of the edge cases.',mutatesWorktree:!0}),Y("WORKTREE_WAIT_PUSH_READY","Worktrees","Wait for push-ready","WAIT",["worktree.id"],Q,{description:"Parks the run until the worktree's branch is pushed and tracking a remote.",details:"The step to put between an AI session that commits and Open pull request, which needs the branch to exist on the remote. Resolves as soon as the branch is push-ready; without a timeout it waits indefinitely, so set one if a human may never push. Writes `worktree.pushStatus`."}),Y("WORKTREE_SNAPSHOT","Worktrees","Snapshot Git state","AGENT",["worktree.path"],["steps.<stepId>.snapshotId"],{description:"Captures a restorable checkpoint of the worktree's Git state before a risky step.",details:"Runs on the agent, so it needs `worktree.path` and an online agent. The snapshot id it writes is what run replay restores from, which makes this the step to place before anything that rewrites the tree. Snapshots cost disk on the agent."}),Y("CODEBASE_FETCH_REFRESH","Codebases","Fetch or refresh codebase","SERVER",["codebase.id"],Z,{description:"Fetches remote refs for a codebase, or fully refreshes its cached metadata.",details:"Fetch updates remote-tracking branches; refresh re-reads the whole checkout and is slower. Runs as an agent job and waits. Fails when the agent skips the operation — usually because the codebase is missing or already busy. Put a fetch in front of steps that check whether a remote branch exists.",mutatesWorktree:!0}),Y("CODEBASE_INSPECT_GIT","Codebases","Inspect codebase Git state","SERVER",["codebase.id"],["codebase.*"],{description:"Reads the codebase checkout's Git status into `codebase.*`.",details:"Read-only. This is the primary checkout, not a worktree — use Inspect worktree Git state for per-branch work. Useful for refusing to start work when the base checkout is dirty or on an unexpected branch."}),Y("CODEBASE_GIT_OPERATION","Codebases","Run codebase Git operation","SERVER",["codebase.id"],Z,{description:"Runs a Git operation against the codebase's primary checkout.",details:'Same operations as the worktree version, aimed at the main checkout that every worktree branches from — so a bad rebase or reset here affects all of them. "Stash changes first" clears local modifications out of the way. Runs as an agent job and waits.',mutatesWorktree:!0}),Y("BUILD_START","Builds","Start build or test","SERVER",["codebase.id","worktree.id"],["build.*"],{description:"Queues an iOS build, test, or archive run on the agent and waits for it to finish.",details:"Needs a build configuration id and an online agent; the destination and build scripts are optional. The step parks until the build reaches a terminal status, so a long test suite holds the workflow run. Failing builds fail the step — route the failure handle if you want to read the results anyway. Writes `build.*`, which the read-results and coverage steps then consume.",mutatesExternal:!0}),Y("BUILD_READ_TEST_RESULTS","Builds","Read test results","SERVER",["build.id"],["build.testSummary","build.tests"],{description:"Reads a finished build's test report into `build.testSummary` and `build.tests`.",details:"Fails outright when the report is not ready, so it belongs after Start build or test rather than in parallel with it. The summary carries the passed/failed counts a condition can branch on; the per-test list is the detail an AI prompt can be pointed at. Read-only."}),Y("BUILD_READ_COVERAGE","Builds","Read code coverage","SERVER",["build.id"],["build.coverageSummary","build.coverageFiles","build.changedCoverageFiles"],{description:"Reads a finished build's coverage report into `build.coverageSummary` and the per-file breakdowns.",details:'Fails when the coverage report is not ready — the build must have been run with coverage collection on. Also writes the changed-files breakdown, which is what a "coverage on this branch\'s changes" gate should read rather than the whole-project number. Read-only.'}),Y("BUILD_IMPORT_COVERAGE","Builds","Import coverage report","SERVER",["worktree.id"],["build.id","build.coverageSummary"],{description:"Reads a coverage file a test command wrote in the worktree and records it as a coverage report.",details:"Pair it with a Terminal command step that runs the test suite first: this step only reads what that run left behind, at the path given in `Coverage file`. The build name defaults to the workflow name and can be overridden. LCOV and Istanbul (`coverage-final.json`) are both understood, and AUTO tells them apart by the file itself. Runs as an agent job and waits. The report is attached to a new build record of its own, so it shows up on that build's coverage page and in the coverage picker on Changes; changed-line coverage is measured against the worktree's base branch, and is left out when that branch cannot be resolved. Writes the totals to `build.coverageSummary` and the new id to `build.id` — follow with Read code coverage for the per-file breakdown. Fails when the file is missing, unreadable, or describes no files."}),Y("BUILD_EXPORT","Builds","Export archive","SERVER",["build.id"],["build.exportId",...Q],{description:"Exports a finished archive build into a distributable package on the agent.",details:"Needs export settings and an archive-action build. Runs as an agent job and waits. Writes files to the agent's disk and may talk to Apple's servers for signing, so it can fail on expired certificates or provisioning profiles.",mutatesExternal:!0}),Y("BUILD_DEPLOY","Builds","Deploy build","SERVER",["build.id"],Q,{description:"Installs and launches an existing build on its destinations without rebuilding.",details:"Reuses the artifacts from a previous build, so it is much faster than building again. Destinations default to the ones the build already targeted. Waits for the deployment job. This puts the app on real or simulated devices — treat it as an external effect.",mutatesExternal:!0}),Y("BUILD_CANCEL","Builds","Cancel build","SERVER",["build.id"],["build.id","build.status"],{description:"Cancels a queued or running build.",details:"Aimed at a different build from the one this run started — Start build or test already waits for its own. Cancelling an already-finished build is a no-op rather than an error. Writes `build.status`.",mutatesExternal:!0}),Y("DISK_SPACE_LOAD","Disk space","Load disk-space monitor","SERVER",[],["agent.*","disk.*"],{description:"Loads the current Derived Data disk-space monitor snapshot for an agent.",details:"Targets the configured agent, then falls back to `agent.id` or `codebase.agentId`. The least-free monitored Derived Data volume supplies `disk.freeBytes`, `disk.freeGiB`, and the percentage fields; root and base-repository volumes remain in `disk.volumes` for context only. Read-only and does not request a new report."}),Y("DISK_SPACE_REFRESH","Disk space","Refresh disk-space monitor","WAIT",[],["agent.*","disk.*"],{description:"Requests an immediate disk report from an agent and waits for fresh telemetry.",details:"Targets the configured agent, then falls back to `agent.id` or `codebase.agentId`. Monitoring must be enabled. The step waits until `lastReportedAt` advances, then refreshes `agent.*` and `disk.*`; by default it polls every two seconds and times out after 180 seconds."}),Y("DISK_SPACE_UPDATE_THRESHOLDS","Disk space","Update disk thresholds","SERVER",[],["disk.normalThresholdGiB","disk.pressureThresholdGiB","disk.pollIntervalSeconds","disk.staleAfterSeconds"],{description:"Updates the global normal and pressure free-space thresholds.",details:"Changes the thresholds used for every monitored agent, automatic cleanup, and admission control. The pressure threshold must be positive and lower than the normal threshold. Writes the resulting global settings into `disk.*`."}),Y("DISK_SPACE_SET_MONITORING","Disk space","Set agent disk monitoring","SERVER",[],["agent.*","disk.*"],{description:"Enables or disables Derived Data disk-space monitoring for an agent.",details:"Targets the configured agent, then falls back to `agent.id` or `codebase.agentId`. Disabling monitoring also clears manual and automatic pressure mode and releases cleanup leases that have not started a job. Refreshes `agent.*` and `disk.*`."}),Y("DISK_SPACE_SET_PRESSURE_MODE","Disk space","Set disk pressure mode","SERVER",[],["agent.*","disk.*"],{description:"Enables or clears manual disk pressure mode for an agent.",details:"Targets the configured agent, then falls back to `agent.id` or `codebase.agentId`. Manual pressure mode uses the lower pressure threshold; automatic pressure mode remains controlled by cleanup availability. Refreshes `agent.*` and `disk.*`."}),Y("SKILL_APPLY","Skills","Apply skill group","SERVER",["worktree.id","repo.id"],["steps.<stepId>.status"],{description:"Syncs a skill group's files into the target checkout, or every skill when no group is chosen.",details:"Starts a skill sync run and waits for it. Writes skill files into the repository, which shows up as uncommitted changes — commit or discard them before a step that needs a clean tree. Leave the group empty to sync everything.",mutatesWorktree:!0}),Y("RUN_CREATE_PLAN","AI runs","Create plan and wait","SERVER",["worktree.id"],["run.<stepId>.*"],{description:"Starts an AI planning run against the worktree and waits for the plan to be produced.",details:"Requires a worktree, a provider/model, and a prompt. Plans use a separate FIFO worktree queue and allow unlimited concurrent plans by default; set the worktree concurrency limit to 1–32 to cap them, or 0 for unlimited. Planning inspects the code but does not change it — use Run AI session and wait to actually make edits, or follow with Run completed plan. If the run asks a question it parks until someone answers, so pair long workflows with a question-needed trigger. Writes the run under `run.<stepId>.*`, which later steps reference by this step's id."}),Y("RUN_CREATE_SESSION","AI runs","Run AI session and wait","SERVER",["worktree.id"],["run.<stepId>.*"],{description:"Starts an AI coding session against the worktree and waits for it to finish.",details:"The workhorse step: the agent edits files in the worktree, so the tree is dirty afterwards and the changes still need committing and pushing. Sessions use a separate FIFO worktree queue with one active session by default; set the worktree concurrency limit to 2–32 for parallel sessions or 0 for unlimited. Requires a worktree, a provider/model, and a prompt; attachments and web search are optional. Parks on questions until answered. Writes `run.<stepId>.*`.",mutatesWorktree:!0}),Y("RUN_PLAY_PLAN","AI runs","Run completed plan","SERVER",[],["run.<stepId>.*"],{description:"Executes a plan that has already been produced, turning it into real code changes.",details:"Takes the plan's run id — usually `run.<planStepId>.id` from an earlier Create plan step. The plan must have completed. The resulting Session joins the worktree's FIFO Session queue, which allows one active Session by default; use 0 for unlimited or 2–32 for a larger limit. This is the half of the plan/execute split that touches the worktree. Writes a new run under `run.<stepId>.*`.",mutatesWorktree:!0}),Y("RUN_FOLLOW_UP","AI runs","Follow up run","SERVER",[],["run.<stepId>.*"],{description:"Starts a new AI run that continues from an existing one, resuming its context or starting fresh.",details:'RESUME keeps the previous conversation, FRESH starts over in the same worktree, and RESEND replays the original prompt. The new run joins the source kind\'s separate FIFO worktree queue and defaults to unlimited concurrency for Plans or one active run for Sessions; use 0 for unlimited or 1–32 for a finite limit. Needs the source run id plus a new prompt. The natural step for "fix the review comments" loops after a first session. Writes `run.<stepId>.*`.'}),Y("RUN_STEER","AI runs","Steer active run","SERVER",[],["run.<stepId>.*"],{description:"Sends extra instructions into a run that is already in progress.",details:"Only affects a run that is still going — it does not restart a finished one, which is what Follow up run is for. Because the steps in this workflow that start runs also wait for them, steering usually targets a run started elsewhere, reached through a run trigger."}),Y("RUN_ANSWER","AI runs","Answer run question","SERVER",[],["run.<stepId>.*"],{description:"Answers a question an AI run is blocked on so it can carry on.",details:"Needs the question batch id, typically from `run.questions` seeded by a run-needs-an-answer trigger, and answers keyed by question id. This answers questions asked by an AI run — the Request confirmation and Ask user to choose steps ask questions of a human about the workflow itself."}),Y("RUN_PAUSE","AI runs","Pause run","SERVER",[],["run.<stepId>.*"],{description:"Pauses an in-progress AI run.",details:"The run stops at its next checkpoint and stays paused until something continues it. Falls back to `run.id`. Pausing an already-finished run fails."}),Y("RUN_CONTINUE","AI runs","Continue run","SERVER",[],["run.<stepId>.*"],{description:"Resumes a paused AI run.",details:"The counterpart to Pause run. Fails when the run is not paused. Falls back to `run.id`."}),Y("RUN_CANCEL","AI runs","Cancel run","SERVER",[],["run.<stepId>.*"],{description:"Cancels an AI run, stopping its work.",details:"Whatever the run already wrote to the worktree stays — cancelling stops further work, it does not roll anything back. Falls back to `run.id`."}),Y("RUN_REVISE_ANSWER","AI runs","Revise answer and rewind","SERVER",[],["run.<stepId>.*"],{description:"Rewinds a run to an earlier question, replaces the answer, and replays from there.",details:"Two-phase: the step prepares the revision, parks, and applies it once the run is ready. Rolling back restores the worktree to the checkpoint at that question, discarding work done since — stash first if that work matters. The heavy way to correct a wrong answer; Follow up run is usually enough.",mutatesWorktree:!0}),Y("RUN_READ_RESULT","AI runs","Read run result","SERVER",[],["run.<stepId>.*"],{description:"Loads a finished run's events, questions, token usage, and linked items into session data.",details:"Read-only. Gives later steps the run's actual output to work from — a summary to put in a Jira comment, usage figures to threshold on, or the linked pull request. Falls back to `run.id`."}),Y("RUN_CAPTURE_CHECKPOINT","AI runs","Capture run checkpoint","SERVER",[],["steps.<stepId>.snapshotId"],{description:"Records the run's most recent checkpoint so a later replay can restore from it.",details:"Reads an existing checkpoint rather than creating one, and fails when the run has none. Use Snapshot Git state to capture a fresh checkpoint of the worktree instead. Writes the checkpoint id to `steps.<stepId>.snapshotId`."}),Y("RUN_ARCHIVE_DELETE","AI runs","Archive or delete run","SERVER",[],[],{description:"Archives a run out of the active list, or permanently deletes it.",details:"Archiving is reversible; deleting removes the run and its history for good. Delete wins when both flags are set. Housekeeping for workflows that generate many short-lived runs.",mutatesExternal:!0}),Y("NOTIFICATION_SEND","Human loop","Send notification","SERVER",[],[],{description:"Posts a notification into the app's notification list with a title, body, and link.",details:"Deduplicated per run, step, and generation, so a retried attempt does not notify twice. The link defaults to this workflow run. Fire-and-forget: it tells a human something happened but does not wait — use Request confirmation when the workflow needs an answer.",mutatesExternal:!0}),Y("IOS_PUSH_SEND","Human loop","Push to iOS device","SERVER",[],[],{description:"Sends an Apple push notification to registered devices, a broadcast channel, or one raw device token.",details:"Needs APNs credentials. Target mode picks between all registrations, a chosen few, a broadcast channel, or a direct token — the direct mode also needs the token's encoding and whether it is a sandbox or production token. Leaves the device once delivered; nothing about the run waits on it.",mutatesExternal:!0}),Y("HUMAN_CONFIRM","Human loop","Request confirmation","WAIT",[],["steps.<stepId>.answer"],{description:"Parks the run and asks a human to confirm before continuing.",details:"The approval gate to put in front of anything irreversible. Without a timeout the run waits indefinitely; with one it fails when nobody answers in time, which the failure handle can route to a safe default. The answer lands in `steps.<stepId>.answer`."}),Y("HUMAN_CHOICE","Human loop","Ask user to choose","WAIT",[],["steps.<stepId>.answer"],{description:"Parks the run and asks a human to pick from a set of options, optionally allowing several or a free-text answer.",details:"Like Request confirmation but with named buttons — branch on `steps.<stepId>.answer` with an If step afterwards. Multi-select returns a list. Allowing a custom answer means the value may be anything the person typed, so handle the unexpected case."}),Y("CONTROL_IF","Control flow","If / else","CONTROL",[],[],{description:"Evaluates a condition and sends the run down its `true` or `false` branch.",details:"Exactly one branch is taken; steps on the other are skipped, and a skipped branch does not block a downstream join. Conditions compare session values with the usual operators and combine with ALL/ANY/NOT. Both branches may be left unconnected, which simply ends that path."}),Y("CONTROL_JOIN","Control flow","Join branches","CONTROL",[],[],{description:"Brings parallel branches back together, waiting for all of them or continuing on the first.",details:"Required wherever more than one branch reaches the same step — the validator rejects a plain step with several incoming edges. ALL waits for every branch, ANY continues on the first and lets the others keep running. Skipped branches never block it, and the join is skipped when no branch reaches it. A join that closes a For each also reports the iteration failures."}),Y("CONTROL_DELAY","Control flow","Time delay","WAIT",[],[],{description:"Pauses the run for a fixed number of seconds.",details:"Accepts up to a year. The run is parked rather than held open, so a long delay costs nothing while it waits. Use it to space out polling or to give an external system time to settle; use Wait until when you are waiting for a condition rather than a duration."}),Y("CONTROL_WAIT_UNTIL","Control flow","Wait until","WAIT",[],[],{description:"Parks the run until a condition over session data becomes true, re-checking on a cadence.",details:"Evaluates immediately and continues at once if the condition already holds. Session data only changes when a step writes it, so the condition must be able to become true through some other branch — otherwise the wait never resolves. Default cadence is 15 seconds; set a timeout to bound it."}),Y("CONTROL_FOR_EACH","Control flow","For each","CONTROL",[],["steps.<stepId>.items"],{description:"Runs its `body` branch once per item in a list, or takes the `empty` branch when there is nothing to iterate.",details:"Reads the list from a session path or from inline items, and caps at 1,000. Iterations run in parallel and each sees its own item. Fail-fast stops the whole run on the first failing iteration; collect-errors lets them all finish and reports failures at the closing join. Writes the items to `steps.<stepId>.items`."}),Y("CONTROL_TRY","Control flow","Try / catch","CONTROL",[],[],{description:"Marks the start of a protected region whose failures route out of the `catch` handle.",details:"Takes no config — the recovery path is drawn in the graph. Steps on the `success` branch run normally; when one of them fails, the run continues from `catch` instead of failing outright. Use a step's own failure handle for a single fallible step; reach for this when a whole sequence shares one recovery path."}),Y("CONTROL_SET_VARIABLE","Control flow","Set or compute variable","CONTROL",[],[],{description:"Writes a value into session data at a chosen path, either a constant or the result of a small script.",details:"The script runs in a sandboxed JavaScript interpreter with the session data available and no network or filesystem access; its return value is what gets written. Without a script the literal value is used. The path may be any dotted path — write under a namespace of your own to avoid colliding with what steps produce. Because the path comes from config, the catalog cannot advertise it: list it in this step's own `providedPaths` too, or a later step that binds it fails to publish with REQUIREMENT_UNSATISFIED."}),Y("CONTROL_SUBWORKFLOW","Control flow","Call sub-workflow","SERVER",[],[],{description:"Runs another published workflow as a child and waits for it to finish.",details:"Must pin a specific published version — the validator rejects an unpinned reference, so a sub-workflow cannot change under a caller. The input mapping seeds the child's session data. The child appears as a nested run; its failure fails this step."}),Y("SAVED_COMMAND","Extensibility","Run saved command","AGENT",[],["steps.<stepId>.*"],{description:"Starts a saved command on an eligible agent home or worktree target.",details:"Uses the saved command snapshot, target rules, output log, and restart policy. Wait for exit fails the workflow when the command ultimately fails or is cancelled; fire and forget succeeds after durable dispatch and remains independent if the workflow is later cancelled. An optional RE2 output pattern emits the match connector before exit and records captures in session data; matching requires wait for exit. Always-restart commands can only use fire and forget.",mutatesWorktree:!0}),Y("CUSTOM_COMMAND","Extensibility","Run custom command","AGENT",[],["steps.<stepId>.*"],{description:"Runs a one-off shell command on an agent home or worktree and records it in Commands run history.",details:"The script is retained only in the immutable command-run snapshot, not as a reusable saved command. Context targeting prefers the current worktree, then the current agent. Wait for exit fails the workflow when the command fails or is cancelled; fire and forget succeeds after durable dispatch. An optional RE2 output pattern emits the match connector before exit and records captures in session data; matching requires wait for exit.",mutatesWorktree:!0}),...ee,Y("TERMINAL_RUN","Extensibility","Run terminal script","AGENT",["worktree.path"],["steps.<stepId>.*"],{description:"Runs a shell or Node script on the agent inside the worktree, capturing its output.",details:"Needs `worktree.path` and an online agent. A non-zero exit fails the step. Named credentials can be injected as environment variables so secrets never sit in the definition — the validator rejects secret-looking literals in config. Arbitrary code on the agent's machine: it can change anything the agent user can reach. Writes stdout, stderr, and the exit code under `steps.<stepId>.*`; to publish anything else the script produces into a named path, declare it in this step's own `providedPaths`.",mutatesWorktree:!0}),Y("MCP_CALL","Extensibility","Call MCP tool","SERVER",[],["steps.<stepId>.output"],{description:"Calls a tool on a configured MCP server — built-in or external — with a JSON argument object.",details:"The general escape hatch to anything reachable over MCP. Needs the server (tool group) and the exact tool name; arguments must match that tool's own schema. What it does depends entirely on the tool, so treat it as externally mutating. The result lands in `steps.<stepId>.output`.",mutatesExternal:!0}),...[["SSE_ENDPOINT_ACTION","Manage SSE endpoint"],["SSE_MOCK_ACTION","Manage SSE mock"],["SSE_STORAGE_ACTION","Manage SSE storage"],["SSE_BREAKPOINT_RESOLVE","Resolve SSE breakpoint"],["SSE_HISTORY_CLEAR","Clear SSE history"],["SSE_SCRIPT_TEST","Test SSE script"]].map(([e,t])=>X(e,"SSE",t,[],["sse.*","steps.<stepId>.output"],{mutatesExternal:!1}))],er=new Map(et.map(e=>[e.kind,e])),ei=["run.*","worktree.*","codebase.*","agent.*","repo.*","ticket.*"],ea=["build.*","worktree.*","codebase.*","agent.*","repo.*","ticket.*"],en=["worktree.*","codebase.*","agent.*","repo.*","ticket.*","pr.*"],es=["ticket.*","comment.*","changelog.*"],eo=["repo.*","pr.*","ticket.*","worktree.*","codebase.*","agent.*"],el=[...eo,"comment.*"],eu=["repo.*","pr.*","ticket.*","worktree.*","codebase.*","agent.*"],ec="Filters narrow it further: each session path must equal the given value, or be one of a list of values.",ed="Set a threshold path, operator, and value to fire only on the crossing: it fires when the comparison first becomes true and stays quiet until it goes false again, so a metric hovering over the line does not fire repeatedly.",eh=(e,t,r,i,a)=>({kind:e,category:t,label:r,description:a.description,details:a.details,configSchema:G(e,"trigger"),capabilityFlags:["DURABLE","DEDUPLICATED"],seedPaths:i,sourceHandles:(0,n.workflowStaticSourceHandles)(e)}),ep=(e,t,r,i)=>eh(e,t,r,i,{description:`${r} emits a normalized, filterable workflow event.`,details:`${r} uses the canonical domain event and deduplicates deliveries by subject and revision. ${ec}`}),em=[ep("COMMAND_RUN_RESULT","Commands","Command run result",["command.*","agent.*","worktree.*"]),ep("COMMAND_OUTPUT_MATCH","Commands","Command output match",["command.*","output.*"]),ep("SKILL_SYNC_RESULT","Skills","Skill sync result",["skillSync.*","skill.*","repo.*"]),ep("SKILL_SYNC_CONFLICT","Skills","Skill sync conflict",["skillSync.*","skill.*","repo.*"]),ep("GITHUB_PIPELINE_STATUS_CHANGED","GitHub","Pipeline status changed",["pipeline.*","repo.*","pr.*","worktree.*","codebase.*","agent.*","ticket.*"]),ep("GITHUB_PR_SYNCHRONIZED","GitHub","Pull request synchronized",eo),ep("GITHUB_REVIEW_APPROVED","GitHub","Pull request review approved",eo),...[["GITLAB_MR_STATE","Merge request opened or ready",eu],["GITLAB_REVIEW_CHANGES_REQUESTED","Changes requested",eu],["GITLAB_REVIEW_COMMENT","Review comment created",[...eu,"comment.*"]],["GITLAB_MR_CLOSED","Merge request merged or closed",eu],["GITLAB_PIPELINE_FAILED","Pipeline failed",["pipeline.*","repo.*","pr.*"]],["GITLAB_PUSH_DEFAULT","Push to default branch",["repo.*","push.*"]],["GITLAB_PIPELINE_SUCCEEDED","Pipeline succeeded",["pipeline.*","repo.*","pr.*"]],["GITLAB_NOTE_COMMAND","Note command",[...eu,"comment.*"]],["GITLAB_PIPELINE_RESULT","Pipeline result",["pipeline.*","repo.*","pr.*"]],["GITLAB_MR_LABEL","Merge request label set",eu],["GITLAB_PIPELINE_STATUS_CHANGED","Pipeline status changed",["pipeline.*","repo.*","pr.*"]],["GITLAB_MR_SYNCHRONIZED","Merge request synchronized",eu],["GITLAB_REVIEW_APPROVED","Merge request approved",eu],["GITLAB_JOB_STATUS_CHANGED","Job status changed",["job.*","pipeline.*","repo.*"]]].map(([e,t,r])=>ep(String(e),"GitLab",String(t),r)),ep("JIRA_TICKET_UPDATED","Jira","Jira ticket updated",es),ep("JIRA_COMMENT_ADDED","Jira","Jira comment added",es),ep("JIRA_WORKLOG_ADDED","Jira","Jira worklog added",es),ep("JIRA_SPRINT_ENDED","Jira","Jira sprint ended",es),ep("CODEBASE_SYNC_STATE_CHANGED","Codebases","Codebase sync state changed",["codebase.*","agent.*","repo.*"]),ep("CODEBASE_OPERATION_FAILED","Codebases","Codebase operation failed",["codebase.*","agent.*","repo.*","operation.*"]),ep("WORKTREE_SYNC_STATE_CHANGED","Worktrees","Worktree sync state changed",en),ep("WORKTREE_AUTOMATION_RESULT","Worktrees","Worktree automation result",[...en,"automation.*"]),ep("WORKTREE_CLEAN","Worktrees","Worktree became clean",en),ep("PUSH_NOTIFICATION_RESULT","Notifications","Push notification result",["pushBatch.*"]),ep("IOS_DEVICE_ENROLLED","Devices","iOS device enrolled",["device.*"]),ep("IOS_DEVICE_REGISTRATION_RESULT","Devices","iOS device registration result",["device.*"]),ep("SIGNING_OPERATION_RESULT","Signing","Signing operation result",["signing.*","signingProfile.*","agent.*"]),ep("SIGNING_ASSET_EXPIRING","Signing","Signing asset expiring",["signing.*","signingProfile.*","agent.*"]),ep("BUILD_DATA_THRESHOLD","Build Data","Build-data threshold",["buildData.*","agent.*","worktree.*"]),ep("BUILD_DATA_CLEANUP_RESULT","Build Data","Build-data cleanup result",["buildData.*","cleanup.*","agent.*"]),ep("POLLING_OPERATION_STATE","Operations","Polling operation state",["polling.*"]),ep("MODEL_COST_CATALOG_CHANGED","Operations","Model-cost catalog changed",["modelCosts.*"]),ep("CREDENTIAL_STORE_DEGRADED","Operations","Credential store degraded",["credentials.*"]),ep("AGENT_RESOURCE_THRESHOLD","Agents","Agent resource threshold",["agent.*"]),ep("AGENT_VERSION_CHANGED","Agents","Agent version changed",["agent.*"]),ep("TOOL_CALL_RESULT","Tools","Tool call result",["toolCall.*"]),ep("SSE_REQUEST_OPENED","SSE","SSE request opened",["sse.*","endpoint.*","request.*"]),ep("SSE_EVENT_EMITTED","SSE","SSE event emitted",["sse.*","endpoint.*","request.*","event.*"]),ep("SSE_BREAKPOINT_WAITING","SSE","SSE breakpoint waiting",["sse.*","endpoint.*","request.*","breakpoint.*"]),ep("SSE_BREAKPOINT_RESOLVED","SSE","SSE breakpoint resolved",["sse.*","endpoint.*","request.*","breakpoint.*"]),ep("SSE_STREAM_COMPLETED","SSE","SSE stream completed",["sse.*","endpoint.*","request.*"]),ep("SSE_STREAM_FAILED","SSE","SSE stream failed",["sse.*","endpoint.*","request.*"])],ef=[eh("MANUAL","Manual","Manual run",[],{description:"Fires when someone presses Run on the workflow. The default entry point.",details:"Seeds nothing beyond `workflow.*`, so steps hanging off it can only bind to values that later steps produce. A caller may still pass session data explicitly when starting the run. A workflow that has only a choice trigger refuses a plain run."}),eh("MANUAL_CHOICE","Manual","Manual run with a choice",[],{description:"Fires when someone picks an option from the menu under the run button, and routes the run out of that option's own handle.",details:"Declare at least one option, each with a unique key — the key names the outgoing handle, so renaming a label leaves edges attached. One workflow can fan out into several entry paths without a step in front of them. Every edge must leave a handle that still exists, or publishing fails."}),eh("RESOURCE_MANUAL","Manual","Run from a resource",[],{description:"Fires when someone starts the workflow from a specific resource page — a worktree, pull request, build, codebase, ticket, or run.",details:"Must target exactly one resource kind; add a second trigger to accept another. The page seeds that resource's namespace into session data, so a worktree-launched run gets its worktree, codebase, owning agent, repository, and any linked ticket. Those seeds are an optimistic contract — an optional link that is absent resolves to nothing at run time. A worktree does not seed `pr.*`; use a pull-request trigger or Load pull request to bring one into session data. This is also what makes the workflow show up on that resource's page."}),eh("RESOURCE_MANUAL_CHOICE","Manual","Run from a resource with a choice",[],{description:"Fires from a resource page after the person picks an option, routing out of that option's handle.",details:"The resource and choice triggers combined: pick a resource kind and declare keyed options. Same rules as both — one resource kind per trigger, unique option keys, and every edge on a live handle."}),eh("SCHEDULE","Schedule","On a schedule",[],{description:"Fires repeatedly on a fixed cadence measured in seconds.",details:'A cadence, not a cron expression — there is no way to say "weekdays at 9am". The clock runs while the workflow is enabled, and pausing the workflow stops it. Seeds nothing, so scheduled workflows normally start by loading whatever they operate on. Mind the overlap policy: a cadence shorter than the run takes will queue or coalesce.'}),eh("WORKFLOW_FINISHED","Workflows","Another workflow finished",["workflow.*"],{description:"Fires when a different workflow run reaches a terminal state.",details:`Chains workflows without making one a sub-workflow of the other, so the two stay independently runnable. Filter on \`workflow.id\` to watch a specific one and on the finishing status to react only to failures. ${ec}`}),eh("GITHUB_PR_STATE","GitHub","Pull request opened or ready",eo,{description:"Fires when a pull request is opened, or when a draft is marked ready for review.",details:`Needs GitHub polling configured for the repository. Seeds \`pr.*\` and \`repo.*\`, so steps can act on the pull request straight away. ${ec} Filter on \`pr.isDraft\` or the base branch to avoid firing on every pull request in the repository.`}),eh("GITHUB_REVIEW_CHANGES_REQUESTED","GitHub","Changes requested",eo,{description:"Fires when a reviewer submits a review requesting changes.",details:`The entry point for an automated "address the review" loop: pair it with Collect review comments and an AI session. Approvals and plain comments do not fire it. ${ec}`}),eh("GITHUB_REVIEW_COMMENT","GitHub","Review comment created",el,{description:"Fires when a new review comment is posted on a pull request.",details:`Fires per comment rather than per review, so a reviewer leaving five comments fires it five times — take care with steps that start AI runs. Use Changes requested when you want one event per review. ${ec}`}),eh("GITHUB_PR_CLOSED","GitHub","Pull request merged or closed",eo,{description:"Fires when a pull request is merged or closed without merging.",details:`Both outcomes fire it; branch on \`pr.state\` to tell them apart. The natural place to hang cleanup — deleting the worktree, moving the ticket on. ${ec}`}),eh("GITHUB_CHECK_FAILED","GitHub","Check suite or run failed",["repo.*","pipeline.*","worktree.*","codebase.*","agent.*","pr.*","ticket.*"],{description:"Fires when a check suite or check run reports a failure.",details:`Seeds \`pipeline.*\`, including the ids the retry and cancel steps need. Flaky suites fire this often, so gate an automatic retry on a count or a delay rather than retrying unconditionally. ${ec}`}),eh("GITHUB_PUSH_DEFAULT","GitHub","Push to default branch",["repo.*","push.*","ticket.*"],{description:"Fires when a commit lands on the repository's default branch.",details:`Seeds \`repo.*\` and \`push.*\`, plus a ticket key when the pushed branch contains one. There is no pull request or worktree in scope, so a workflow hanging off it usually starts by creating one. Fires on merges too, since a merge is a push. ${ec}`}),eh("GITHUB_WORKFLOW_SUCCEEDED","GitHub","Workflow run succeeded",["repo.*","pipeline.*","worktree.*","codebase.*","agent.*","pr.*","ticket.*"],{description:"Fires when a GitHub Actions workflow run completes successfully.",details:`The success counterpart to the failure triggers — useful for gating a deploy or a merge on a green pipeline. Filter on the workflow name so every unrelated Actions run does not start this workflow. ${ec}`}),eh("GITHUB_ISSUE_COMMAND","GitHub","Issue comment command",["repo.*","pr.*","ticket.*","comment.*"],{description:"Fires when a comment from an allow-listed GitHub user matches a command pattern, such as `/deploy`.",details:`The only trigger that lets outside text start a workflow, so it is deliberately strict: an explicit list of GitHub logins is required, and the pattern must be anchored with \`^\` and \`$\` — publishing fails otherwise. Both checks must pass. Keep the allow-list tight, since anyone on it can start whatever the workflow does. ${ec}`}),eh("GITHUB_ACTIONS_RESULT","GitHub Actions","Workflow result",["repo.*","pipeline.*","worktree.*","codebase.*","agent.*","pr.*","ticket.*"],{description:"Fires when a tracked GitHub Actions run finishes, whatever its conclusion.",details:`The richest of the Actions triggers: it correlates the run back to its worktree, owning agent, pull request, and ticket when those links exist. Branch on the conclusion rather than adding separate success and failure triggers. ${ec}`}),eh("GITHUB_PR_LABEL","GitHub","Pull request label set",eo,{description:"Fires when a label is applied to a pull request.",details:`Turns a label into a manual switch — label a pull request \`automerge\` and let a workflow take it from there. Filter on the label name, or every label change in the repository starts the workflow. ${ec}`}),eh("BUILD_RESULT","Builds","Build result",ea,{description:"Fires when a build finishes, succeeded or failed.",details:`Seeds \`build.*\` along with the worktree it ran in, so the read-results and coverage steps can follow directly. Branch on \`build.status\` to separate the outcomes. ${ec}`}),eh("BUILD_TEST_THRESHOLD","Builds","Test failure threshold",ea,{description:"Fires when a build's failing-test count crosses a threshold you set.",details:`Point the threshold path at \`build.testSummary.failed\` and pick an operator and value. ${ed} ${ec}`}),eh("BUILD_COVERAGE_THRESHOLD","Builds","Coverage threshold",ea,{description:"Fires when a build's code coverage crosses a threshold you set.",details:`Point the threshold path at the coverage summary — usually the changed-files percentage rather than the whole-project number — and compare with a less-than operator. ${ed} ${ec}`}),eh("BUILD_HOOK_FAILED","Builds","Build hook failed",ea,{description:"Fires when one of a build's pre- or post-build scripts fails.",details:`Distinguishes a broken build script from a genuine compile or test failure, which is what Build result reports. Seeds \`build.*\`. ${ec}`}),eh("AGENT_CONNECTION","Agents","Agent connection changed",["agent.*","codebase.agentId"],{description:"Fires when an agent comes online or goes offline.",details:`Seeds the agent id, name, connection state, and capacity metrics. A workflow hanging off it is usually about notifying a human rather than doing repository work — an offline agent cannot run agent steps anyway. Filter on the connection status to react to one direction only. ${ec}`}),eh("AGENT_JOB_FAILED","Agents","Agent job failed",["steps.trigger.*","agent.*","codebase.*","worktree.*","repo.*","ticket.*"],{description:"Fires when a job dispatched to an agent fails — a build, a Git operation, a terminal script.",details:`The failing job is seeded under \`steps.trigger.*\`, including its kind and error. When it targeted a worktree, the owning agent, codebase, repository, and ticket are included too. Catches infrastructure failures that a workflow's own failure handles never see, because the job belonged to a different run. ${ec}`}),eh("AGENT_DISK_REPORT","Agents","Agent disk report",["agent.*","codebase.agentId","disk.*"],{description:"Fires whenever the Derived Data monitor accepts a new agent disk report.",details:`Seeds the complete monitor snapshot under \`disk.*\`, while \`agent.diskFreeBytes\` remains the legacy root-disk inventory value. This can fire at the agent poll cadence; use filters when every report is not needed. ${ec}`}),eh("AGENT_DISK_THRESHOLD","Agents","Agent disk threshold",["agent.*","codebase.agentId","disk.*"],{description:"Fires when monitored Derived Data free space crosses a threshold you set.",details:`Use \`disk.freeGiB\`, \`disk.freeBytes\`, or \`disk.freePercent\` to evaluate the least-free monitored Derived Data volume. \`agent.diskFreeBytes\` remains available for older root-disk workflows. ${ed} ${ec}`}),eh("AGENT_DISK_STATE_CHANGED","Agents","Agent disk state changed",["agent.*","codebase.agentId","disk.*"],{description:"Fires when an agent's disk monitor changes status, pressure mode, health, or monitored volume.",details:`Filter on \`disk.status\`, \`disk.pressureMode\`, \`disk.enabled\`, or errors and warnings to react to a specific transition. Cleanup start appears as \`DELETING\`; recovery can be selected with \`IDLE\`. Repeated reports in the same state stay quiet. ${ec}`}),eh("AGENT_DISK_CLEANUP_RESULT","Agents","Automatic disk cleanup result",["agent.*","codebase.agentId","disk.*","cleanup.*"],{description:"Fires whenever a monitor-managed automatic Derived Data cleanup finishes.",details:`Seeds the terminal agent job under \`cleanup.*\`, including status, error, targets, and deleted entries. Every cleanup job is independent, so two successive successes both fire. Manual Build Data deletions remain outside this trigger. ${ec}`}),eh("CCUSAGE_THRESHOLD","Agents","Usage threshold",["run.usage.*","agent.*"],{description:"Fires when aggregate AI usage crosses a threshold you set.",details:`Watches usage across runs rather than one run's spend — Run usage threshold does that. The cost guardrail: notify, or pause workflows that start AI runs. ${ed} ${ec}`}),eh("WORKTREE_CREATED","Worktrees","Worktree created",en,{description:"Fires after a new worktree is successfully created.",details:`Fires once after the created worktree is projected into the control plane. Seeds the worktree, repository, codebase, and owning agent, plus a linked pull request and Jira ticket when the branch resolves to them. ${ec}`}),eh("WORKTREE_BEHIND","Worktrees","Worktree behind base",en,{description:"Fires when a worktree's branch falls behind the branch it was cut from.",details:`Pairs with a sync operation to keep long-lived branches current. Fires again as the base moves on, so a workflow that reacts should either sync or be filtered narrowly. ${ec}`}),eh("WORKTREE_CONFLICT","Worktrees","Worktree has conflicts",en,{description:"Fires when a worktree is left with Git conflicts after a merge or rebase.",details:`Only fires when the worktree is genuinely marked conflicted. Conflicts need resolving before most other worktree steps will work, so this usually leads to a notification or an AI session pointed at the conflict. ${ec}`}),eh("WORKTREE_MISSING","Worktrees","Worktree missing",en,{description:"Fires when a worktree the control plane knows about is no longer on disk.",details:`Only fires once the worktree is actually recorded as missing — usually someone deleted the directory by hand, or the agent's disk was cleaned. Steps that need the worktree will fail, so react by recreating it or clearing the record. ${ec}`}),eh("WORKTREE_DIVERGED","Worktrees","Worktree diverged",en,{description:"Fires when a worktree's branch and its remote have both moved on independently.",details:`Only fires when the push status is genuinely diverged. Resolving it means a rebase, a merge, or a force push — all destructive enough that this usually routes to a human rather than to an automatic fix. ${ec}`}),eh("WORKTREE_DIRTY_DURATION","Worktrees","Worktree dirty too long",en,{description:"Fires when a worktree has had uncommitted changes for longer than expected.",details:`Catches work that stalled — an AI session that edited files and was never followed up, or a human who wandered off. Usually a nudge rather than an automatic commit. ${ec}`}),eh("WORKTREE_NEW_COMMIT","Worktrees","New worktree commit",en,{description:"Fires when a new commit lands in a worktree.",details:`Fires per commit, so a rebase or a batch of commits fires it repeatedly — keep the reaction cheap, or filter to one branch. Useful for kicking off a build or lint pass as work lands. ${ec}`}),eh("CODEBASE_REMOTE_BRANCH","Codebases","Matching remote branch",["codebase.*","agent.*","repo.*"],{description:"Fires when a remote branch matching the codebase's conventions appears.",details:`Lets a branch pushed from elsewhere pull work into this system — creating a worktree for it, or opening a pull request. Needs a fetch to have run for the branch to be visible. ${ec}`}),eh("JIRA_STATUS","Jira","Ticket status changed",es,{description:"Fires when a Jira ticket moves to another status.",details:`Needs Jira polling configured. Seeds \`ticket.*\`. Filter on \`ticket.status\` to react to one column only — without a filter, every transition on every polled ticket starts the workflow. ${ec}`}),eh("JIRA_LABEL","Jira","Jira label set",es,{description:"Fires when a label is applied to a Jira ticket.",details:`The Jira counterpart to the pull request label trigger: a label becomes a manual switch for automation. Filter on the label name. ${ec}`}),eh("JIRA_ASSIGNED_SELF","Jira","Ticket assigned to me",es,{description:"Fires when a ticket is assigned to the account behind the configured Jira credential.",details:`"Me" is whoever the Jira credential authenticates as, not whoever is looking at the screen. The usual start of a "pick up my next ticket" workflow — create a worktree, start a plan. ${ec}`}),eh("JIRA_SOURCE_NEW_TICKET","Jira","New ticket in source",es,{description:"Fires when a ticket appears in a configured Jira source — a saved JQL query or board.",details:`Fires on tickets newly matching the source, which includes existing tickets edited into range, not only freshly created ones. The source itself does the filtering, so keep its JQL tight. Seeds \`ticket.*\`. ${ec}`}),eh("JIRA_MENTION","Jira","Jira comment mention",es,{description:"Fires when the configured Jira account is mentioned in a ticket comment.",details:`Lets someone pull automation into a conversation by mentioning the bot. The comment is seeded under \`comment.*\`, so an AI step can read what was actually asked — treat that text as untrusted input rather than instructions. ${ec}`}),eh("JIRA_SPRINT_STARTED","Jira","Sprint started",es,{description:"Fires when a Jira sprint is started.",details:`Fires per ticket in the sprint, so a sprint of thirty tickets starts thirty runs — mind the workflow's concurrency settings. Good for sprint-opening bookkeeping. ${ec}`}),eh("JIRA_ISSUE_CREATED","Jira","Ticket created",es,{description:"Fires when a Jira ticket is created.",details:`Needs the Jira webhook configured in Settings — the polled Jira triggers only observe tickets something already fetched, so they cannot see a brand-new one. Scope the webhook's JQL filter to the projects you care about, since every created ticket otherwise starts a run. ${ec}`}),eh("JIRA_ISSUE_DELETED","Jira","Ticket deleted",es,{description:"Fires when a Jira ticket is deleted.",details:`Needs the Jira webhook. The ticket is gone by the time this runs, so only the payload's \`ticket.*\` snapshot is available — a step that loads the ticket will fail. Use it for cleanup: close the worktree, cancel the run, archive the branch. ${ec}`}),eh("JIRA_ISSUE_COMMAND","Jira","Ticket comment command",es,{description:"Fires when a comment from an allow-listed Jira account matches a command pattern, such as `/deploy`.",details:`The Jira counterpart to the GitHub issue comment command, and just as strict: an explicit list of Jira account IDs is required, and the pattern must be anchored with \`^\` and \`$\` — publishing fails otherwise. Jira identifies people by opaque account ID, not display name, so copy the ID from the user's Jira profile URL. Treat the comment body as untrusted input rather than instructions. Needs the Jira webhook. ${ec}`}),eh("JIRA_ATTACHMENT_ADDED","Jira","Attachment added",[...es,"attachment.*"],{description:"Fires when a file is attached to a Jira ticket.",details:`Needs the Jira webhook. Seeds \`attachment.*\` with the filename, MIME type, and author. Filter on \`attachment.mimeType\` to react to one kind of upload — a crash log, a design export. ${ec}`}),eh("JIRA_ISSUE_LINKED","Jira","Ticket linked",[...es,"link.*"],{description:"Fires when a Jira issue link is created.",details:`Needs the Jira webhook. Seeds \`link.*\` with the link type and both issue IDs. Filter on \`link.type\` to react to one relationship — "blocks", "duplicates" — rather than every link. ${ec}`}),eh("RUN_STARTED","Plans and sessions","Run started",ei,{description:"Fires when an AI plan or session run begins.",details:`Every run trigger seeds the same shape — \`run.*\` plus the worktree, codebase, repository, and ticket it is attached to. Filter on \`run.kind\` to separate plans from sessions. ${ec}`}),eh("RUN_COMPLETED","Plans and sessions","Run completed",ei,{description:"Fires when an AI run finishes successfully.",details:`The place to hang everything that happens after the agent is done — committing, pushing, opening a pull request, moving the ticket. Filter on \`run.kind\` to react only to plans or only to sessions. ${ec}`}),eh("RUN_QUESTION_NEEDED","Plans and sessions","Run needs an answer",ei,{description:"Fires when an AI run pauses to ask a question, with the pending questions in session data.",details:`The questions arrive under \`run.questions\`, so the Answer run question step can respond without a human — the basis for unattended runs. Answer carefully: an automatic answer to a question the agent should have asked a person is how unwanted changes get made. ${ec}`}),eh("RUN_QUESTION_ANSWERED","Plans and sessions","Run question answered",ei,{description:"Fires when a pending question on an AI run is answered.",details:`Fires however the answer arrived — from a person or from another workflow. Use it to record decisions, or to resume work that was gated on the answer. ${ec}`}),eh("RUN_PAUSED","Plans and sessions","Run paused",ei,{description:"Fires when an AI run is paused.",details:`Covers pauses from any source, including a run that paused itself. A run needing an answer reports separately through Run needs an answer. ${ec}`}),eh("RUN_CONTINUED","Plans and sessions","Run continued",ei,{description:"Fires when a paused AI run resumes.",details:`The counterpart to Run paused. Fires on each resume, so a run that stops and starts repeatedly fires it repeatedly. ${ec}`}),eh("RUN_FAILED","Plans and sessions","Run failed",ei,{description:"Fires when an AI run ends in failure.",details:`The error is in the seeded run data, so a follow-up run can be pointed at what went wrong. Beware of loops — a workflow that reacts by starting another run that fails the same way will keep going. ${ec}`}),eh("RUN_CANCELLED","Plans and sessions","Run cancelled",ei,{description:"Fires when an AI run is cancelled.",details:`Cancellation leaves whatever the run already wrote in the worktree, so cleanup usually means inspecting or reverting rather than assuming nothing happened. ${ec}`}),eh("RUN_PLAN_PLAYED","Plans and sessions","Plan played",ei,{description:"Fires when a run is created by executing a previously completed plan.",details:`Distinguishes plan execution from an ordinary session, which Run started cannot. Lets a workflow treat planned work differently from ad-hoc work. ${ec}`}),eh("RUN_FOLLOW_UP","Plans and sessions","Run follow-up created",ei,{description:"Fires when a run is created as a follow-up to another run.",details:`Does not fire for plan execution, which reports through Plan played. The parent run is in the seeded data, so a workflow can count how deep a follow-up chain has gone and stop it. ${ec}`}),eh("RUN_IMPORTED","Plans and sessions","Provider run imported",ei,{description:"Fires when a run started outside this system is imported from a provider.",details:`Lets work begun in another tool pick up the same automation — labelling, ticket updates, pull requests. The run did not originate here, so its worktree and ticket links may be incomplete. ${ec}`}),eh("RUN_USAGE_THRESHOLD","Plans and sessions","Run usage threshold",ei,{description:"Fires when a single run's token or cost usage crosses a threshold you set.",details:`Scoped to one run, unlike the aggregate Usage threshold. Point the threshold path at the usage figure you care about — a runaway session can then be cancelled automatically. ${ed} ${ec}`}),eh("RUN_EVENT_MATCH","Plans and sessions","Run event or tool matched",ei,{description:"Fires on individual events inside an AI run, including each tool call it makes.",details:`The finest-grained run trigger, and by far the most talkative — a single run produces hundreds of events, and every one is a candidate. Always filter, on the event type or the tool name. Useful for reacting to a specific tool being used; a poor choice for anything expensive. ${ec}`}),...em],eg=new Map(ef.map(e=>[e.kind,e])),ey=t.z.string().min(1).max(128).regex(/^[A-Za-z0-9][A-Za-z0-9_-]*$/),ew=t.z.string().min(1).max(256).regex(/^[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_*\[\]-]+)*$/),eb=t.z.record(t.z.string(),t.z.unknown()).default({}),eE=t.z.object({id:ey,kind:t.z.enum(n.WORKFLOW_TRIGGER_KINDS),name:t.z.string().min(1).max(200).optional(),position:t.z.object({x:t.z.number().finite(),y:t.z.number().finite()}),config:eb}),eS=t.z.object({id:ey,kind:t.z.enum(n.WORKFLOW_STEP_KINDS),name:t.z.string().min(1).max(200).optional(),position:t.z.object({x:t.z.number().finite(),y:t.z.number().finite()}),config:eb,requiredPaths:t.z.array(ew).max(100).default([]),providedPaths:t.z.array(ew).max(100).default([]),retry:t.z.object({maxAttempts:t.z.number().int().min(1).max(20).default(1),strategy:t.z.enum(["FIXED","EXPONENTIAL"]).default("EXPONENTIAL"),delaySeconds:t.z.number().int().min(1).max(86400).default(5)}).default({maxAttempts:1,strategy:"EXPONENTIAL",delaySeconds:5}),failurePolicy:t.z.enum(["FAIL","CONTINUE"]).default("FAIL")}),ev=t.z.object({id:ey,source:ey,target:ey,sourceHandle:t.z.string().min(1).max(100).default("success"),targetHandle:t.z.string().min(1).max(100).default("input")}),eI=t.z.object({format:t.z.literal(H),schemaVersion:t.z.literal(1),name:t.z.string().min(1).max(200),description:t.z.string().max(2e3).default(""),triggers:t.z.array(eE).max(100).default([]),nodes:t.z.array(eS).max(1e3).default([]),edges:t.z.array(ev).max(5e3).default([]),editor:t.z.object({viewport:t.z.object({x:t.z.number(),y:t.z.number(),zoom:t.z.number().positive()}).optional(),handleLayout:t.z.enum(["SIDES","TOP_BOTTOM"]).default("SIDES"),displayLayout:t.z.enum(["REGULAR","BASIC"]).default("REGULAR")}).default({handleLayout:"SIDES",displayLayout:"REGULAR"})});function eA(e){return{...e,nodes:e.nodes.map(e=>{if(("RUN_CREATE_PLAN"===e.kind||"RUN_CREATE_SESSION"===e.kind)&&Object.hasOwn(e.config,"jiraSummary")){let t={...e.config};return delete t.jiraSummary,{...e,config:t}}return e})}}function ek(e,t){return t.map(t=>t.replaceAll("<stepId>",e.id))}function e_(e,t){return e===t||"*"===e||e.endsWith(".*")&&t.startsWith(e.slice(0,-1))}function eT(e){return e.length?new Set([...e[0]].filter(t=>e.every(e=>e.has(t)))):new Set}function eC(e,t){return[...e].some(e=>e_(e,t))}let eR={stepPaths(e){let t=er.get(e);return{requiredPaths:t?.requiredPaths??[],providedPaths:t?.providedPaths??[]}},triggerSeedPaths:e=>eg.get(e)?.seedPaths??[]};function eN(e,t=eR){let r=new Set(e.nodes.map(({id:e})=>e)),i=new Map(e.nodes.map(e=>[e.id,e])),a=new Map,n=new Map;for(let t of e.edges)a.set(t.source,[...a.get(t.source)??[],t.target]),n.set(t.target,[...n.get(t.target)??[],t.source]);let s=new Map(e.nodes.map(e=>[e.id,0]));for(let t of e.edges)r.has(t.source)&&r.has(t.target)&&s.set(t.target,(s.get(t.target)??0)+1);let o=[...s].filter(([,e])=>0===e).map(([e])=>e),l=[];for(;o.length;){let e=o.shift();for(let t of(l.push(e),a.get(e)??[])){if(!r.has(t))continue;let e=(s.get(t)??0)-1;s.set(t,e),0===e&&o.push(t)}}let u=e=>{let t=new Set,r=[...a.get(e)??[]];for(;r.length;){let e=r.shift();t.has(e)||(t.add(e),r.push(...a.get(e)??[]))}return t},c=new Map;for(let t of[...e.triggers,...e.nodes])c.set(t.id,u(t.id));let d=new Map;for(let r of e.nodes){let e=t.stepPaths(r.kind);d.set(r.id,[...ek(r,e.providedPaths),...r.providedPaths,`steps.${r.id}.*`])}let h=new Map,p=[];for(let r of e.triggers){let e=new Set(["workflow.*"]);for(let i of t.triggerSeedPaths(r.kind))e.add(i);for(let t of J(r.kind,r.config))e.add(t);let a=new Map;for(let s of l){if(!c.get(r.id)?.has(s))continue;let o=i.get(s),l=(n.get(s)??[]).filter(e=>e===r.id||a.has(e));if(!l.length)continue;let u=eT(l.map(t=>t===r.id?e:a.get(t))),m=h.get(s);h.set(s,m?eT([m,u]):new Set(u));let f=new Set(d.get(s)??[]),g=[...U(o.kind,"step",o.config)].filter(e=>!eC(f,e));for(let e of new Set([...ek(o,t.stepPaths(o.kind).requiredPaths),...o.requiredPaths,...g]))eC(u,e)||p.push({nodeId:o.id,triggerId:r.id,triggerName:r.name??r.kind,path:e});let y=new Set(u);for(let e of d.get(s)??[])y.add(e);a.set(s,y)}}return{availableBefore:new Map([...h].map(([e,t])=>[e,[...t]])),provides:d,requirementViolations:p}}function eO(e,t=""){return Array.isArray(e)?e.some(e=>eO(e,t)):e&&"object"==typeof e?Object.entries(e).some(([e,t])=>eO(t,e)):"string"==typeof e&&/(token|secret|password|passwd|private.?key|api.?key|authorization)/i.test(t)&&!/(credential.?id|credential.?ids)$/i.test(t)}function eD(e){return Array.isArray(e)?e.some(eD):!!e&&"object"==typeof e&&("UNRESOLVED"===e.referenceStatus||Object.values(e).some(eD))}e.s(["WORKFLOW_SCHEMA_VERSION",0,1,"WORKFLOW_STEP_BY_KIND",0,er,"WORKFLOW_STEP_CATALOG",0,et,"WORKFLOW_TRIGGER_CATALOG",0,ef,"computeWorkflowPathAvailability",0,eN,"emptyWorkflowDefinition",0,function(e="Untitled workflow"){return eI.parse({format:H,schemaVersion:1,name:e,description:"",triggers:[{id:"manual",kind:"MANUAL",position:{x:0,y:100},config:{}}],nodes:[],edges:[],editor:{}})},"hasWorkflowErrors",0,function(e){return e.some(({severity:e})=>"ERROR"===e)},"parseWorkflowDefinition",0,function(e){return eA(eI.parse(e))},"resourceManualSeedPaths",0,J,"sanitizeWorkflowExportDefinition",0,function(e){let t=(e,r="")=>Array.isArray(e)?e.map(e=>t(e,r)):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,r])=>[e,t(r,e)])):"string"==typeof e&&/(token|secret|password|passwd|private.?key|api.?key|authorization)/i.test(r)&&!/(credential.?id|credential.?ids)$/i.test(r)||"string"==typeof e&&/^(?:\/|[A-Za-z]:[\\/]|\\\\)/.test(e)&&/^(?:cwd|folder|path|directory)$/i.test(r)?null:e;return eI.parse(t(e))},"validateWorkflowDefinition",0,function(e){let t=eI.safeParse(e);if(!t.success)return{definition:null,diagnostics:t.error.issues.map(e=>({severity:"ERROR",code:"SCHEMA_INVALID",message:e.message,path:e.path.join(".")}))};let r=eA(t.data),i=[],a=new Set;for(let e of[...r.triggers,...r.nodes])a.has(e.id)&&i.push({severity:"ERROR",code:"DUPLICATE_NODE_ID",message:`Duplicate graph id ${e.id}`,nodeId:e.id}),a.add(e.id);let o=new Set;for(let e of r.edges)o.has(e.id)&&i.push({severity:"ERROR",code:"DUPLICATE_EDGE_ID",message:`Duplicate edge id ${e.id}`}),o.add(e.id),a.has(e.source)&&a.has(e.target)||i.push({severity:"ERROR",code:"EDGE_ENDPOINT_MISSING",message:`Edge ${e.id} references a missing endpoint`}),r.triggers.some(({id:t})=>t===e.target)&&i.push({severity:"ERROR",code:"TRIGGER_HAS_INPUT",message:"Triggers cannot have incoming edges",triggerId:e.target});r.triggers.length||i.push({severity:"ERROR",code:"TRIGGER_REQUIRED",message:"At least one trigger is required"}),r.nodes.length||i.push({severity:"ERROR",code:"STEP_REQUIRED",message:"At least one step is required"});let l=new Set(r.nodes.map(({id:e})=>e)),u=new Map,c=new Map;for(let e of r.edges)u.set(e.source,[...u.get(e.source)??[],e.target]),c.set(e.target,[...c.get(e.target)??[],e.source]);for(let e of r.nodes)(c.get(e.id)??[]).filter(e=>l.has(e)).length>1&&"CONTROL_JOIN"!==e.kind&&i.push({severity:"ERROR",code:"EXPLICIT_JOIN_REQUIRED",message:"Nodes with multiple incoming branches must be explicit join nodes",nodeId:e.id});let d=new Map(r.nodes.map(e=>[e.id,0]));for(let e of r.edges)l.has(e.source)&&l.has(e.target)&&d.set(e.target,(d.get(e.target)??0)+1);let h=[...d].filter(([,e])=>0===e).map(([e])=>e),p=[];for(;h.length;){let e=h.shift();for(let t of(p.push(e),u.get(e)??[])){if(!l.has(t))continue;let e=(d.get(t)??0)-1;d.set(t,e),0===e&&h.push(t)}}p.length!==r.nodes.length&&i.push({severity:"ERROR",code:"DAG_CYCLE",message:"Workflow graphs cannot contain free-form cycles"});let m=new Map,f=e=>{let t=new Set,r=[...u.get(e)??[]];for(;r.length;){let e=r.shift();t.has(e)||(t.add(e),r.push(...u.get(e)??[]))}return t};for(let e of[...r.triggers,...r.nodes])m.set(e.id,f(e.id));for(let e of r.nodes){for(let t of(r.triggers.some(t=>m.get(t.id)?.has(e.id))||i.push({severity:"ERROR",code:"UNREACHABLE_STEP",message:"Step is not reachable from a trigger",nodeId:e.id}),eO(e.config)&&i.push({severity:"ERROR",code:"SECRET_LITERAL",message:"Store secrets as credential references, not workflow literals",nodeId:e.id}),eD(e.config)&&i.push({severity:"ERROR",code:"UNRESOLVED_REFERENCE",message:"Resolve imported references before publishing",nodeId:e.id}),new Set((0,s.invalidWorkflowValueBindings)(e.config))))i.push({severity:"ERROR",code:"SESSION_BINDING_INVALID",message:t,nodeId:e.id});if("CONTROL_SUBWORKFLOW"===e.kind&&"string"!=typeof e.config.versionId&&i.push({severity:"ERROR",code:"SUBWORKFLOW_VERSION_REQUIRED",message:"Sub-workflows must pin a published version",nodeId:e.id}),"SAVED_COMMAND"===e.kind||"CUSTOM_COMMAND"===e.kind){let t=F(e.config);if(r.edges.some(t=>t.source===e.id&&"match"===t.sourceHandle)&&!t&&i.push({severity:"ERROR",code:"COMMAND_MATCH_PATTERN_REQUIRED",message:"The match connector requires an output pattern",nodeId:e.id}),t){void 0!==e.config.outputMatchMode&&"ONCE"!==e.config.outputMatchMode&&"EACH_MATCH"!==e.config.outputMatchMode&&i.push({severity:"ERROR",code:"COMMAND_MATCH_MODE_INVALID",message:"Output match behavior must be Once or Each match",nodeId:e.id}),"FIRE_AND_FORGET"===e.config.completionMode&&i.push({severity:"ERROR",code:"COMMAND_MATCH_REQUIRES_WAIT",message:"Output matching requires Wait for exit completion",nodeId:e.id});try{z(t)}catch(t){i.push({severity:"ERROR",code:"COMMAND_MATCH_PATTERN_INVALID",message:t instanceof Error?t.message:String(t),nodeId:e.id})}let a=t=>r.edges.filter(r=>r.source===e.id&&r.sourceHandle===t).map(({target:e})=>e),n=e=>{let t=new Set,i=[...e];for(;i.length;){let e=i.shift();t.has(e)||(t.add(e),i.push(...r.edges.filter(t=>t.source===e).map(({target:e})=>e)))}return t},s=n(a("match")),o=n([...a("success"),...a("failure")]);[...s].some(e=>o.has(e))&&i.push({severity:"ERROR",code:"COMMAND_MATCH_BRANCH_RECONVERGES",message:"A command match branch cannot reconverge with its success or failure branch",nodeId:e.id})}}}for(let e of r.triggers){for(let t of((u.get(e.id)??[]).length||i.push({severity:"ERROR",code:"TRIGGER_DISCONNECTED",message:"Trigger is not connected to a step",triggerId:e.id}),eO(e.config)&&i.push({severity:"ERROR",code:"SECRET_LITERAL",message:"Store secrets as credential references, not trigger literals",triggerId:e.id}),eD(e.config)&&i.push({severity:"ERROR",code:"UNRESOLVED_REFERENCE",message:"Resolve imported references before publishing",triggerId:e.id}),new Set((0,s.invalidWorkflowValueBindings)(e.config))))i.push({severity:"ERROR",code:"SESSION_BINDING_INVALID",message:t,triggerId:e.id});if((0,n.isResourceTriggerKind)(e.kind)&&!W(e.config)&&i.push({severity:"ERROR",code:"RESOURCE_KIND_REQUIRED",message:"Resource triggers must target a single resource kind; add one trigger per kind",triggerId:e.id}),(0,n.isChoiceTriggerKind)(e.kind)){let t=V(e.config),a=Array.isArray(e.config.choices)?e.config.choices.length:0;t.length&&t.length===a||i.push({severity:"ERROR",code:"TRIGGER_CHOICES_REQUIRED",message:"Choice triggers need at least one option, each with a unique key",triggerId:e.id});let n=new Set(t.map(({key:e})=>e));for(let t of r.edges)t.source===e.id&&(n.has(t.sourceHandle)||i.push({severity:"ERROR",code:"TRIGGER_CHOICE_HANDLE_UNKNOWN",message:`Connection ${t.id} leaves an option that no longer exists`,triggerId:e.id}))}if("GITHUB_ISSUE_COMMAND"===e.kind||"JIRA_ISSUE_COMMAND"===e.kind||"GITLAB_NOTE_COMMAND"===e.kind){let t="JIRA_ISSUE_COMMAND"===e.kind,r="GITLAB_NOTE_COMMAND"===e.kind,a=t?e.config.allowedAccountIds:r?e.config.allowedUsernames:e.config.allowedLogins,n=e.config.commandPattern;(!Array.isArray(a)||!a.length||a.some(e=>"string"!=typeof e||!e.trim()))&&i.push({severity:"ERROR",code:"ISSUE_COMMAND_ALLOWLIST_REQUIRED",message:t?"Issue command triggers require an explicit Jira account ID allow-list":r?"Note command triggers require an explicit GitLab username allow-list":"Issue command triggers require an explicit GitHub login allow-list",triggerId:e.id}),"string"==typeof n&&n.startsWith("^")&&n.endsWith("$")||i.push({severity:"ERROR",code:"ISSUE_COMMAND_PATTERN_ANCHORED",message:"Issue command patterns must be anchored with ^ and $",triggerId:e.id})}}for(let e of eN(r).requirementViolations)i.push({severity:"ERROR",code:"REQUIREMENT_UNSATISFIED",message:`${e.path} is not guaranteed on the path from ${e.triggerName}`,nodeId:e.nodeId,triggerId:e.triggerId,path:e.path});for(let e=0;e<r.nodes.length;e+=1){let t=r.nodes[e],a=[...ek(t,er.get(t.kind).providedPaths),...t.providedPaths].filter(e=>!e.startsWith(`steps.${t.id}.`));for(let n=e+1;n<r.nodes.length;n+=1){let e=r.nodes[n];if(m.get(t.id)?.has(e.id)||m.get(e.id)?.has(t.id))continue;let s=[...ek(e,er.get(e.kind).providedPaths),...e.providedPaths].filter(t=>!t.startsWith(`steps.${e.id}.`));a.some(e=>s.some(t=>e_(e,t)||e_(t,e)))&&i.push({severity:"ERROR",code:"PARALLEL_WRITE_CONFLICT",message:`Parallel steps ${t.name??t.id} and ${e.name??e.id} can write the same session-data path`,nodeId:e.id})}}return{definition:r,diagnostics:i}},"workflowResourceKind",0,W,"workflowTriggerChoices",0,V],497800)},337951,e=>{"use strict";var t=e.i(497800),r=e.i(835544);function i(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 a(e,t){return e.nodes.find(e=>e.id===t)??e.triggers.find(e=>e.id===t)}function n(e){return(0,r.isChoiceTriggerKind)(e.kind)?(0,t.workflowTriggerChoices)(e.config).map(({key:e})=>e):(0,r.workflowStaticSourceHandles)(e.kind)}function s(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 o(e,t){let r=a(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=n(r),s=t.sourceHandle??i[0];if(!s)throw Error(`${t.source} offers no connectors yet — a choice trigger needs its options set first`);if(!i.includes(s))throw Error(`${t.source} has no ${s} connector; it offers ${i.join(", ")}`);let o=t.targetHandle??"input",l=e.edges.find(e=>e.source===t.source&&e.target===t.target&&e.sourceHandle===s);if(l)return{definition:e,edgeId:l.id};let u=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:u,source:t.source,target:t.target,sourceHandle:s,targetHandle:o}]},edgeId:u}}e.s(["addWorkflowStep",0,function(e,t){let r=i(e,"node"),n={id:r,kind:t.kind,name:t.name??void 0,position:t.position??function(e,t){let r=t?a(e,t):void 0,i=r?r.position.x+320:320,n=r?r.position.y:120,s=[...e.nodes,...e.triggers].filter(e=>160>Math.abs(e.position.x-i)).map(e=>e.position.y),o=n;for(;s.some(e=>80>Math.abs(e-o));)o+=160;return{x:i,y:o}}(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"},s={...e,nodes:[...e.nodes,n]};if(!t.connectFrom)return{definition:s,nodeId:r,edgeId:null};let l=o(s,{source:t.connectFrom.from,target:r,sourceHandle:t.connectFrom.sourceHandle??null});return{definition:l.definition,nodeId:r,edgeId:l.edgeId}},"addWorkflowTrigger",0,function(e,t){let r=i(e,"trigger"),a={id:r,kind:t.kind,name:t.name??void 0,config:t.config??{},position:t.position??{x:0,y:100+140*e.triggers.length}};return{definition:{...e,triggers:[...e.triggers,a]},triggerId:r}},"availableSourceHandles",0,n,"connectWorkflowNodes",0,o,"disconnectWorkflowNodes",0,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]}},"layoutWorkflowDefinition",0,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),u=e.nodes.map(o);return{...e,triggers:l,nodes:u}},"removeWorkflowGraphNode",0,function(e,t,r={}){if(!a(e,t))throw Error(`${t} is not in this workflow`);let i=e.edges.filter(e=>e.target===t),n=e.edges.filter(e=>e.source===t),s=e.edges.filter(e=>e.source!==t&&e.target!==t),l={...e,nodes:e.nodes.filter(e=>e.id!==t),triggers:e.triggers.filter(e=>e.id!==t),edges:s};if(!r.reconnect)return l;for(let e of i)for(let t of n)l=o(l,{source:e.source,sourceHandle:e.sourceHandle,target:t.target,targetHandle:t.targetHandle}).definition;return l},"updateWorkflowStep",0,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:s(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)}},"updateWorkflowTrigger",0,function(e,t){let i=e.triggers.find(({id:e})=>e===t.triggerId);if(!i)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 a={...i,name:t.name??i.name,config:s(i.config,t),position:t.position??i.position},o=new Set(n(a)),l=(0,r.isChoiceTriggerKind)(a.kind)?e.edges.filter(e=>e.source!==a.id||o.has(e.sourceHandle)):e.edges;return{...e,triggers:e.triggers.map(e=>e.id===a.id?a:e),edges:l}}])},887802,e=>{"use strict";let t={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"}],tailscale:[{name:"operationId",description:"Tailscale Serve operation id"},{name:"status",description:"Fleet operation status"},{name:"templateId",description:"Tailscale Serve template id"},{name:"operation",description:"Durable operation and per-agent progress"},{name:"overview",description:"Fleet templates and agent Tailscale identity"}],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"}]},r=new Map(Object.entries(t).flatMap(([e,t])=>t.map(t=>[`${e}.${t.name}`,t.description])));function i(e){return e.split(".")[0]??e}e.s(["expandSessionPaths",0,function(e){let a=new Map,n=e=>{a.has(e.path)||a.set(e.path,e)};for(let a of e){let e=a.trim();if(e&&"*"!==e){if(e.endsWith(".*")){let r=e.slice(0,-2),a=t[i(r)];if(a)for(let e of a)n({path:`${r}.${e.name}`,description:e.description});else n({path:e});continue}n({path:e,description:function(e){let t=e.split(".");if(t.length<2)return;let a=t[t.length-1];return r.get(`${i(e)}.${a}`)}(e)})}}return[...a.values()].sort((e,t)=>e.path.localeCompare(t.path))}])},835544,e=>{"use strict";let t=new Set(["MANUAL_CHOICE","RESOURCE_MANUAL_CHOICE"]),r=new Set(["RESOURCE_MANUAL","RESOURCE_MANUAL_CHOICE"]);function i(e){return t.has(e)}let a=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;e.s(["WORKFLOW_CHOICE_KEY_PATTERN",0,a,"WORKFLOW_QUICK_ACTION_KINDS",0,["STANDARD","MERGE_CONFLICT","GITHUB_ACTIONS","GITLAB_PIPELINES","NONE"],"WORKFLOW_RESOURCE_KINDS",0,["BUILD","CODEBASE","JIRA_TICKET","AGENT_RUN","GITHUB_PIPELINE","GITHUB_JOB","GITLAB_MERGE_REQUEST","GITLAB_PIPELINE","GITLAB_JOB","PULL_REQUEST","WORKTREE","COMMAND_RUN","SKILL","SKILL_SYNC","IOS_DEVICE","SIGNING_PROFILE","PUSH_NOTIFICATION_BATCH","BUILD_DATA_COLLECTION"],"WORKFLOW_STEP_KINDS",0,["JIRA_LOAD_TICKET","JIRA_TRANSITION","JIRA_COMMENT","JIRA_ASSIGN","JIRA_UPDATE_FIELDS","JIRA_RESOLVE_BRANCH","GITHUB_LOAD_PR","GITHUB_MERGE_PR","GITHUB_COLLECT_REVIEW_THREADS","GITHUB_REPLY_REVIEW_THREAD","GITHUB_SET_REVIEW_THREAD_RESOLVED","GITHUB_CREATE_PR","GITHUB_SET_PR_LABELS","GITHUB_RETRY_PIPELINE","GITHUB_RETRY_JOB","GITHUB_CANCEL_WORKFLOW_RUN","GITHUB_SAVE_AUTO_RETRY","GITHUB_WAIT_CHECKS","WORKTREE_CREATE","WORKTREE_CHANGE_BRANCH","WORKTREE_COMMIT","WORKTREE_REFRESH_PULL_REQUEST","WORKTREE_OPERATION","WORKTREE_PREPARATION","WORKTREE_SET_AUTO_SYNC","WORKTREE_SET_AUTO_MERGE","WORKTREE_DELETE","WORKTREE_MOVE","WORKTREE_INSPECT","WORKTREE_INSPECT_GIT","WORKTREE_GIT_OPERATION","WORKTREE_WAIT_PUSH_READY","WORKTREE_SNAPSHOT","CODEBASE_FETCH_REFRESH","CODEBASE_INSPECT_GIT","CODEBASE_GIT_OPERATION","BUILD_START","BUILD_READ_TEST_RESULTS","BUILD_READ_COVERAGE","BUILD_IMPORT_COVERAGE","BUILD_EXPORT","BUILD_DEPLOY","BUILD_CANCEL","DISK_SPACE_LOAD","DISK_SPACE_REFRESH","DISK_SPACE_UPDATE_THRESHOLDS","DISK_SPACE_SET_MONITORING","DISK_SPACE_SET_PRESSURE_MODE","SKILL_APPLY","RUN_CREATE_PLAN","RUN_CREATE_SESSION","RUN_PLAY_PLAN","RUN_FOLLOW_UP","RUN_STEER","RUN_ANSWER","RUN_PAUSE","RUN_CONTINUE","RUN_CANCEL","RUN_REVISE_ANSWER","RUN_READ_RESULT","RUN_CAPTURE_CHECKPOINT","RUN_ARCHIVE_DELETE","NOTIFICATION_SEND","IOS_PUSH_SEND","HUMAN_CONFIRM","HUMAN_CHOICE","CONTROL_IF","CONTROL_JOIN","CONTROL_DELAY","CONTROL_WAIT_UNTIL","CONTROL_FOR_EACH","CONTROL_TRY","CONTROL_SET_VARIABLE","CONTROL_SUBWORKFLOW","SAVED_COMMAND","CUSTOM_COMMAND","COMMAND_RERUN","COMMAND_TERMINATE","COMMAND_READ_OUTPUT","WORKTREE_INSPECT_DIFF","WORKTREE_UPDATE_METADATA","WORKTREE_MOVE_CONTROL","BUILD_REBUILD","BUILD_GENERATE_REPORT","BUILD_DELETE","SKILL_PREPARE_SYNC","SKILL_RESOLVE_SYNC","SKILL_SKIP_SYNC","BUILD_DATA_REFRESH","BUILD_DATA_DELETE","BUILD_DATA_SET_LOCK","TAILSCALE_SERVE_INSPECT","TAILSCALE_SERVE_UPSERT_TEMPLATE","TAILSCALE_SERVE_SET_AGENT_ENABLED","TAILSCALE_SERVE_DELETE_TEMPLATE","SIGNING_REFRESH","SIGNING_SYNC_PROFILE","SIGNING_DELETE_EXPIRED","IOS_DEVICE_REGISTER","IOS_DEVICE_REJECT","AGENT_RECONCILE","AGENT_UPDATE_CADENCE","CCUSAGE_COLLECT","MODEL_COST_REFRESH","GITHUB_UPDATE_PR","GITHUB_SUBMIT_REVIEW","GITHUB_REQUEST_REVIEWERS","GITHUB_DISPATCH_WORKFLOW","GITLAB_LOAD_MR","GITLAB_CREATE_MR","GITLAB_UPDATE_MR","GITLAB_SUBMIT_REVIEW","GITLAB_REPLY_DISCUSSION","GITLAB_SET_DISCUSSION_RESOLVED","GITLAB_MERGE_MR","GITLAB_SET_MR_LABELS","GITLAB_REQUEST_REVIEWERS","GITLAB_CREATE_PIPELINE","GITLAB_RETRY_PIPELINE","GITLAB_RETRY_JOB","GITLAB_CANCEL_PIPELINE","GITLAB_SAVE_AUTO_RETRY","GITLAB_WAIT_PIPELINE","JIRA_CREATE_TICKET","JIRA_ADD_WORKLOG","JIRA_LINK_TICKETS","TERMINAL_RUN","MCP_CALL","SSE_ENDPOINT_ACTION","SSE_MOCK_ACTION","SSE_STORAGE_ACTION","SSE_BREAKPOINT_RESOLVE","SSE_HISTORY_CLEAR","SSE_SCRIPT_TEST"],"WORKFLOW_TRIGGER_KINDS",0,["MANUAL","MANUAL_CHOICE","RESOURCE_MANUAL","RESOURCE_MANUAL_CHOICE","SCHEDULE","WORKFLOW_FINISHED","GITHUB_PR_STATE","GITHUB_REVIEW_CHANGES_REQUESTED","GITHUB_REVIEW_COMMENT","GITHUB_PR_CLOSED","GITHUB_CHECK_FAILED","GITHUB_PUSH_DEFAULT","GITHUB_WORKFLOW_SUCCEEDED","GITHUB_ISSUE_COMMAND","GITHUB_ACTIONS_RESULT","GITHUB_PR_LABEL","BUILD_RESULT","BUILD_TEST_THRESHOLD","BUILD_COVERAGE_THRESHOLD","BUILD_HOOK_FAILED","AGENT_CONNECTION","AGENT_JOB_FAILED","AGENT_DISK_REPORT","AGENT_DISK_THRESHOLD","AGENT_DISK_STATE_CHANGED","AGENT_DISK_CLEANUP_RESULT","CCUSAGE_THRESHOLD","WORKTREE_CREATED","WORKTREE_BEHIND","WORKTREE_CONFLICT","WORKTREE_MISSING","WORKTREE_DIVERGED","WORKTREE_DIRTY_DURATION","WORKTREE_NEW_COMMIT","CODEBASE_REMOTE_BRANCH","JIRA_STATUS","JIRA_LABEL","JIRA_ASSIGNED_SELF","JIRA_SOURCE_NEW_TICKET","JIRA_MENTION","JIRA_SPRINT_STARTED","JIRA_ISSUE_CREATED","JIRA_ISSUE_DELETED","JIRA_ISSUE_COMMAND","JIRA_ATTACHMENT_ADDED","JIRA_ISSUE_LINKED","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","COMMAND_RUN_RESULT","COMMAND_OUTPUT_MATCH","SKILL_SYNC_RESULT","SKILL_SYNC_CONFLICT","GITHUB_PIPELINE_STATUS_CHANGED","GITHUB_PR_SYNCHRONIZED","GITHUB_REVIEW_APPROVED","GITLAB_MR_STATE","GITLAB_REVIEW_CHANGES_REQUESTED","GITLAB_REVIEW_COMMENT","GITLAB_MR_CLOSED","GITLAB_PIPELINE_FAILED","GITLAB_PUSH_DEFAULT","GITLAB_PIPELINE_SUCCEEDED","GITLAB_NOTE_COMMAND","GITLAB_PIPELINE_RESULT","GITLAB_MR_LABEL","GITLAB_PIPELINE_STATUS_CHANGED","GITLAB_MR_SYNCHRONIZED","GITLAB_REVIEW_APPROVED","GITLAB_JOB_STATUS_CHANGED","JIRA_TICKET_UPDATED","JIRA_COMMENT_ADDED","JIRA_WORKLOG_ADDED","JIRA_SPRINT_ENDED","CODEBASE_SYNC_STATE_CHANGED","CODEBASE_OPERATION_FAILED","WORKTREE_SYNC_STATE_CHANGED","WORKTREE_AUTOMATION_RESULT","WORKTREE_CLEAN","PUSH_NOTIFICATION_RESULT","IOS_DEVICE_ENROLLED","IOS_DEVICE_REGISTRATION_RESULT","SIGNING_OPERATION_RESULT","SIGNING_ASSET_EXPIRING","BUILD_DATA_THRESHOLD","BUILD_DATA_CLEANUP_RESULT","POLLING_OPERATION_STATE","MODEL_COST_CATALOG_CHANGED","CREDENTIAL_STORE_DEGRADED","AGENT_RESOURCE_THRESHOLD","AGENT_VERSION_CHANGED","TOOL_CALL_RESULT","SSE_REQUEST_OPENED","SSE_EVENT_EMITTED","SSE_BREAKPOINT_WAITING","SSE_BREAKPOINT_RESOLVED","SSE_STREAM_COMPLETED","SSE_STREAM_FAILED"],"isChoiceTriggerKind",0,i,"isResourceTriggerKind",0,function(e){return r.has(e)},"isWorkflowChoiceKey",0,function(e){return"string"==typeof e&&a.test(e)},"workflowStaticSourceHandles",0,function(e){return i(e)?[]:"CONTROL_IF"===e?["true","false"]:"CONTROL_FOR_EACH"===e?["body","empty"]:"CONTROL_TRY"===e?["success","catch"]:"SAVED_COMMAND"===e||"CUSTOM_COMMAND"===e?["success","failure","match"]:["success","failure"]}])},296581,330223,142118,e=>{"use strict";e.i(497800);var t=e.i(835544);function r(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 i(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}function a(e,t,r){return i(e[t])[r]}function n(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 s=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"]),o=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"]),l=new Set(["BUILD_RESULT","BUILD_TEST_THRESHOLD","BUILD_COVERAGE_THRESHOLD","BUILD_HOOK_FAILED"]),u=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"]),c=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"]),d=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"]);e.s(["pullRequestResourceId",0,r,"workflowTriggerResourceLink",0,function(e,h){let p=e.trim().toUpperCase(),m=i(h.sessionData);if((0,t.isResourceTriggerKind)(p)){let e=h.resourceKind,t="string"==typeof e?e.toUpperCase():null,r="GITHUB_JOB"===t?a(m,"job","url"):"GITLAB_JOB"===t?a(m,"job","webUrl"):"GITHUB_PIPELINE"===t?a(m,"pipeline","url"):"GITLAB_PIPELINE"===t?a(m,"pipeline","webUrl"):"GITLAB_MERGE_REQUEST"===t?a(m,"pr","webUrl"):null;return"string"==typeof e?n(e.toUpperCase(),h.resourceId,{url:"string"==typeof r?r:null,metadata:"AGENT_RUN"===e.toUpperCase()?{runKind:a(m,"run","kind")}:null}):null}if(s.has(p))return n("JIRA_TICKET",a(m,"ticket","key"));if(o.has(p))return n("AGENT_RUN",a(m,"run","id"),{metadata:{runKind:a(m,"run","kind")}});if(l.has(p))return n("BUILD",a(m,"build","id"));if(u.has(p))return n("WORKTREE",a(m,"worktree","id"));if("CODEBASE_REMOTE_BRANCH"===p||"CODEBASE_SYNC_STATE_CHANGED"===p||"CODEBASE_OPERATION_FAILED"===p)return n("CODEBASE",a(m,"codebase","id"));if("COMMAND_RUN_RESULT"===p||"COMMAND_OUTPUT_MATCH"===p)return n("COMMAND_RUN",a(m,"command","id"));if("SKILL_SYNC_RESULT"===p||"SKILL_SYNC_CONFLICT"===p)return n("SKILL_SYNC",a(m,"skillSync","id"));if("IOS_DEVICE_ENROLLED"===p||"IOS_DEVICE_REGISTRATION_RESULT"===p)return n("IOS_DEVICE",a(m,"device","id"));if("SIGNING_OPERATION_RESULT"===p||"SIGNING_ASSET_EXPIRING"===p)return n("SIGNING_PROFILE",a(m,"signingProfile","id"));if("PUSH_NOTIFICATION_RESULT"===p)return n("PUSH_NOTIFICATION_BATCH",a(m,"pushBatch","id"));if("BUILD_DATA_THRESHOLD"===p||"BUILD_DATA_CLEANUP_RESULT"===p)return n("BUILD_DATA_COLLECTION",a(m,"buildData","id"));if(p.startsWith("SSE_")){let e=i(m.sse),t=a(e,"request","id");return n("SSE_EVENT_EMITTED"===p?"SSE_EVENT":"SSE_REQUEST","SSE_EVENT_EMITTED"===p?a(e,"event","id"):t,{url:`/sse/history?requestId=${encodeURIComponent(String(t??""))}`})}if("AGENT_JOB_FAILED"===p)return n("AGENT_JOB",a(i(m.steps),"trigger","id"));if("AGENT_CONNECTION"===p||"AGENT_DISK_REPORT"===p||"AGENT_DISK_THRESHOLD"===p||"AGENT_DISK_STATE_CHANGED"===p||"AGENT_DISK_CLEANUP_RESULT"===p||"CCUSAGE_THRESHOLD"===p)return n("AGENT",a(m,"agent","id")??a(m,"codebase","agentId"));if("WORKFLOW_FINISHED"===p)return n("WORKFLOW_RUN",a(h,"run","id"));if(c.has(p)){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}(a(m,"repo","displayOrigin")),t=Number(a(m,"pr","number"));return e&&Number.isInteger(t)&&t>0?n("PULL_REQUEST",r(e.owner,e.repository,t)):null}if(d.has(p)){let e=a(m,"pipeline","url");return n("GITHUB_WORKFLOW_RUN",a(m,"pipeline","runId"),{url:"string"==typeof e?e:null})}return"GITHUB_PUSH_DEFAULT"===p?n("CODEBASE_REPOSITORY",a(m,"repo","id")):null}],296581);var h=e.i(483291),p=e.i(361617);let m=["","aa"," ","a a","a\na"," a","a "];function f(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 g(e,t){return f(e.cadenceSeconds,1)??Math.max(1,t)}e.s(["compileCommandOutputPattern",0,function(e,t=!1){(0,p.validateCommandOutputPattern)(e);try{let r=(0,h.compileRe2)(e,{flags:t?"g":"",label:"Output pattern"});for(let t of m){let r=(0,h.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)}`)}}],330223),e.s(["waitCadenceSeconds",0,g,"waitElapsedText",0,function(e){let t=Math.max(0,Math.round(e/1e3)),r=Math.floor(t/3600),i=Math.floor(t%3600/60);return r?`${r}h ${i}m`:i?`${i}m ${t%60}s`:`${t}s`},"waitKindText",0,function(e){return e.toLowerCase().replaceAll("_"," ")},"waitResumeAfter",0,function(e,t=1){return new Date(Date.now()+1e3*g(e,t))},"waitTimeoutAt",0,function(e,t=null){let r=f(e.timeoutSeconds,10)??(null===t?null:f(t,10));return null===r?null:new Date(Date.now()+1e3*r)}],142118)},366367,e=>{"use strict";var t=e.i(807055),r=e.i(184015),i=e.i(119909),a=e.i(243783),n=e.i(296581),s=e.i(499162),o=e.i(361617),l=e.i(330223),u=e.i(142118);let c=(e,t)=>{if(!e||"object"!=typeof e||Array.isArray(e))throw Error(`${t} must be an object`);return e},d=(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()},h=(e,t=2e4)=>null==e||""===e?null:d(e,"Value",t),p=(e,t,r,i)=>d(e.node.config[t]??(0,s.getSessionValue)(e.sessionData,r),i,500),m=(e,t="operation")=>`${e.run.id}:${e.attempt.id}:${t}`,f=(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:(0,u.waitResumeAfter)(e.node.config),timeoutAt:(0,u.waitTimeoutAt)(e.node.config)}:void 0}),g=(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:(0,u.waitResumeAfter)(e.node.config),timeoutAt:(0,u.waitTimeoutAt)(e.node.config,t.timeoutSeconds??3600)}}),y=(e,t,r,i,a)=>({kind:e,resourceId:t,label:r,url:i,metadata:a}),w=(e,t)=>y("JIRA_TICKET",e,t??e);function b(e,t,r){let i=A(e);return y("PULL_REQUEST",(0,n.pullRequestResourceId)(i.owner,i.name,R(e)),t??"Pull request",r)}function E(e){let t=I(e),r=C(e);return t&&r?y("PULL_REQUEST",(0,n.pullRequestResourceId)(t.owner,t.name,r),"Pull request"):null}function S(e){let t=e.node.config.workflowRunId??(0,s.getSessionValue)(e.sessionData,"pipeline.runId"),r=(0,s.getSessionValue)(e.sessionData,"pipeline.url");return("string"==typeof t||"number"==typeof t)&&"string"==typeof r&&r?y("GITHUB_WORKFLOW_RUN",String(t),"Workflow run",r):null}function v(e){let t=(0,s.getSessionValue)(e.sessionData,"run.kind");if("PLAN"!==t&&"SESSION"!==t)return null;let r=function(e){try{return L(e)}catch{return null}}(e);return r?y("AGENT_RUN",r,t,`/${"PLAN"===t?"plans":"sessions"}/${r}`,{runKind:t}):null}function I(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 A(e){let t=I(e);if(!t)throw Error("GitHub owner and repository are required");return t}function k(e){let t=c(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 _(e){let t=c(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 T(e){return d(e.node.config.issueKey??(0,s.getSessionValue)(e.sessionData,"ticket.key"),"Jira issue key",100)}function C(e){let t=e.node.config.number??(0,s.getSessionValue)(e.sessionData,"pr.number"),r="string"==typeof t?Number(t):t;return"number"==typeof r&&Number.isInteger(r)&&r>=1?r:null}function R(e){let t=C(e);if(!t)throw Error("Pull request number is required");return t}function N(e){return p(e,"worktreeId","worktree.id","Worktree ID")}function O(e){return p(e,"codebaseId","codebase.id","Codebase ID")}function D(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:h(e.node.config.branchName??(0,s.getSessionValue)(e.sessionData,"worktree.branch"),500),ticketKey:"TICKET"===t?h(e.node.config.ticketKey??(0,s.getSessionValue)(e.sessionData,"ticket.key"),100):null,baseBranch:d(e.node.config.baseBranch??(0,s.getSessionValue)(e.sessionData,"worktree.baseBranch")??(0,s.getSessionValue)(e.sessionData,"repo.defaultBranch"),"Base branch",500)}}function P(e){return p(e,"buildId","build.id","Build ID")}function x(e){return d(e.node.config.agentId??(0,s.getSessionValue)(e.sessionData,"agent.id")??(0,s.getSessionValue)(e.sessionData,"codebase.agentId"),"Agent ID",500)}function L(e){let t=e.node.config.runId;if("string"==typeof t&&t)return t;let r=e.node.config.sourceStepId;return"string"==typeof r?d((0,s.getSessionValue)(e.sessionData,`run.${r}.id`),"Agent run ID",500):d((0,s.getSessionValue)(e.sessionData,"run.id"),"Agent run ID",500)}function U(e,t){let r,i,a=e.node.config.worktreeConcurrencyLimit;return{kind:t,worktreeId:(r=e.node.config.worktreeId,i=(0,s.getSessionValue)(e.sessionData,"worktree.id"),"string"==typeof r&&r===e.run.workflowId&&"string"==typeof i&&i!==r?d(i,"Worktree ID",500):N(e)),jiraIssueKey:h(e.node.config.jiraIssueKey??(0,s.getSessionValue)(e.sessionData,"ticket.key"),100),provider:d(e.node.config.provider??"CODEX","Provider",50),model:d(e.node.config.model,"Model",200),effort:h(e.node.config.effort,50),webSearchEnabled:!0===e.node.config.webSearchEnabled,prompt:d(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}}e.s(["registerWorkflowAdapters",0,function(e,I,C){var B,M,q,j,$,G,F,z,H,V,K,W,J,Y,Q,Z;let X,ee;B=e,M=C,B.registerWaitPoller("AGENT_JOB",async e=>{let t=await M.agentControl.getJob(e);return t?new Set(["QUEUED","RUNNING"]).has(t.status)?{pending:!0,pollAfterSeconds:2}:{pending:!1,result:t.resultJson?{...c(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"}}),B.registerWaitPoller("AGENT_JOBS",async e=>{let t=c(JSON.parse(e),"Agent jobs wait"),r=Array.isArray(t.ids)?t.ids.map(e=>d(e,"Agent job ID",500)):[];if(!r.length)return{pending:!1,result:{jobs:[]}};let i=await Promise.all(r.map(e=>M.agentControl.getJob(e)));if(i.some(e=>!e))return{pending:!1,error:"Agent job disappeared"};let a=i.filter(e=>!!e);if(a.some(e=>new Set(["QUEUED","RUNNING"]).has(e.status)))return{pending:!0,pollAfterSeconds:2};let n=a.map(e=>({id:e.id,status:e.status,error:e.error})),s=n.filter(({status:e})=>"SUCCEEDED"!==e);return{pending:!1,result:{jobs:n,sessionPatch:{signing:{jobs:n}}},error:s.length?s.map(({id:e,status:t,error:r})=>r?`${e}: ${r}`:`${e}: ${t.toLowerCase()}`).join("; "):null}}),B.registerWaitPoller("AGENT_RUN",async e=>{let t=await M.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"}}),B.registerWaitPoller("COMMAND_RUN",async e=>{let t=await M.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"}}),B.registerWaitPoller("BUILD",async e=>{let t=await M.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"}}),B.registerWaitPoller("BUILD_DATA_COLLECTION",async e=>{let t=await M.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"}}),B.registerWaitPoller("TAILSCALE_SERVE_OPERATION",async e=>{let t=await M.tailscale.operation(e);return t?["SUCCEEDED","FAILED","PARTIAL_FAILED"].includes(t.status)?{pending:!1,result:{...t,sessionPatch:{tailscale:{operation:t,operationId:t.id,status:t.status,templateId:t.templateId}}},error:"SUCCEEDED"===t.status?null:`Tailscale Serve operation ${t.status.toLowerCase().replaceAll("_"," ")}`}:{pending:!0,pollAfterSeconds:2}:{pending:!1,error:"Tailscale Serve operation disappeared"}}),B.registerWaitPoller("SIGNING_OPERATIONS",async e=>{let t=c(JSON.parse(e),"Signing operations wait"),r=Array.isArray(t.ids)?t.ids.map(e=>d(e,"Signing operation ID",500)):[];if(!r.length)return{pending:!1,result:{operations:[]}};let i=(await M.signingAssets.operations(200)).filter(({id:e})=>r.includes(e));if(i.length!==r.length)return{pending:!1,error:"Signing operation disappeared"};let a=new Set(["SUCCEEDED","FAILED","CANCELLED","TIMED_OUT"]);if(i.some(({status:e})=>!a.has(e)))return{pending:!0,pollAfterSeconds:2};let n=i.filter(({status:e})=>"SUCCEEDED"!==e);return{pending:!1,result:{operations:i,sessionPatch:{signing:{operations:i}}},error:n.length?n.map(({id:e,error:t,status:r})=>t?`${e}: ${t}`:`${e}: ${r.toLowerCase()}`).join("; "):null}}),B.registerWaitPoller("SKILL_RUN",async e=>{let t=await M.skills.getRun(e);return t?("READY"===t.status&&(t=await M.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"}}),B.registerWaitPoller("WORKTREE_MOVE",async e=>{let t=await M.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 r=t.targetWorktreeId?await M.worktrees.workflowSessionDataForWorktree(t.targetWorktreeId,{includeMissing:!0}):{};return{pending:!1,result:{id:t.id,status:t.status,targetWorktreeId:t.targetWorktreeId,sessionPatch:r},error:"SUCCEEDED"===t.status?null:t.error||`Worktree move ${t.status.toLowerCase()}`}}),B.registerWaitPoller("WORKTREE_PUSH_READY",async e=>{let t=await (0,a.getPrismaClient)(),r=await t.worktree.findUnique({where:{id:e}});if(!r)return{pending:!1,error:"Worktree disappeared"};if("READY"!==r.pushStatus)return{pending:!0,pollAfterSeconds:5};let i=await M.worktrees.workflowSessionDataForWorktree(r.id,{includeMissing:!0});return{pending:!1,result:{id:r.id,pushStatus:r.pushStatus,sessionPatch:i}}}),B.registerWaitPoller("WORKFLOW_RUN",async e=>{let t=await B.run(e);return t?new Set(["SUCCEEDED","FAILED","CANCELLED"]).has(t.status)?{pending:!1,result:{id:t.id,status:t.status,sessionData:JSON.parse(t.sessionDataJson)},error:"SUCCEEDED"===t.status?null:t.error||`Sub-workflow ${t.status.toLowerCase()}`}:{pending:!0,pollAfterSeconds:3}:{pending:!1,error:"Sub-workflow disappeared"}}),B.registerWaitPoller("RUN_ANSWER_REVISION",async e=>{let t=c(JSON.parse(e),"Answer revision wait"),r=d(t.batchId,"Question batch ID",500),i=await M.runs.questionBatch(r);if(!i)return{pending:!1,error:"Question batch disappeared"};if(!i.revisionPreparedAt)return{pending:!0,pollAfterSeconds:2};let a=await M.runs.reviseAnswer(r,t.answers??{},!0===t.stash,!1!==t.rollback);return a?{pending:!1,result:{id:a.id,kind:a.kind,status:a.status,phase:a.phase,parentRunId:a.parentRunId,followUpMode:a.followUpMode}}:{pending:!1,error:"Answer revision failed"}}),B.registerWaitPoller("GITHUB_CHECKS",async e=>{let t=c(JSON.parse(e),"GitHub checks wait"),r=await M.github.autoRetryRun(d(t.repositoryId,"Repository ID"),d(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(r.status)?{pending:!1,result:{runId:r.id,status:r.status,jobs:r.jobs,sessionPatch:{pipeline:{runId:r.id,status:r.status,conclusion:r.status,jobs:r.jobs}}},error:"SUCCESS"===r.status?null:`GitHub checks concluded ${r.status.toLowerCase()}`}:{pending:!0,pollAfterSeconds:10}}),B.registerWaitPoller("GITLAB_PIPELINE",async e=>{let t=c(JSON.parse(e),"GitLab pipeline wait"),r=await M.gitlab.pipeline(d(t.projectId,"GitLab project ID",500),d(t.pipelineId,"GitLab pipeline ID",500));return new Set(["SUCCESS","FAILED","CANCELED","SKIPPED","MANUAL"]).has(r.status)?{pending:!1,result:{id:r.id,projectId:r.projectId,status:r.status,webUrl:r.webUrl,sessionPatch:{pipeline:{id:r.id,projectId:r.projectId,status:r.status,webUrl:r.webUrl}}},error:"SUCCESS"===r.status?null:`GitLab pipeline concluded ${r.status.toLowerCase()}`}:{pending:!0,pollAfterSeconds:10}}),B.registerWaitPoller("DISK_SPACE_REPORT",async e=>{let t=c(JSON.parse(e),"Disk-space report wait"),r=d(t.agentId,"Agent ID",500),i=await M.diskSpace.snapshot(r);if(!i.disk.enabled)return{pending:!1,error:"Disk-space monitoring was disabled while awaiting a report"};let a=i.disk.lastReportedAt,n="string"==typeof t.previousReportedAt?t.previousReportedAt:null;return(d(t.requestedAt,"Requested timestamp",100),a&&(!n||Date.parse(a)>Date.parse(n)))?{pending:!1,result:{...i,sessionPatch:i}}:{pending:!0,pollAfterSeconds:2}}),q=I,j=C,q.register("JIRA_LOAD_TICKET",async e=>{let t=k(await j.jira.ticket(T(e),!0===e.node.config.force));return{output:t,sessionPatch:{ticket:t},links:[w(String(t.key),String(t.title??t.key))]}}),q.register("JIRA_TRANSITION",async e=>{let t=k(await j.jira.transitionTicket(T(e),d(e.node.config.transitionId,"Jira transition ID",200)));return{output:t,sessionPatch:{ticket:t},links:[w(String(t.key),String(t.title??t.key))]}}),q.register("JIRA_COMMENT",async e=>{let t=k(await j.jira.addComment(T(e),{value:d(e.node.config.content,"Jira comment",1e5),format:"JIRA_WIKI"===e.node.config.format?"JIRA_WIKI":"MARKDOWN"}));return{output:t,sessionPatch:{ticket:t},links:[w(String(t.key),String(t.title??t.key))]}}),q.register("JIRA_ASSIGN",async e=>{let t=null===e.node.config.accountId?null:d(e.node.config.accountId,"Jira account ID",500),r=k(await j.jira.assignTicket(T(e),t));return{output:r,sessionPatch:{ticket:r},links:[w(String(r.key),String(r.title??r.key))]}}),q.register("JIRA_UPDATE_FIELDS",async e=>{let t=c(e.node.config.fields??{},"Jira fields"),r=k(await j.jira.updateTicket({issueKey:T(e),...t}));return{output:r,sessionPatch:{ticket:r},links:[w(String(r.key),String(r.title??r.key))]}}),q.register("JIRA_RESOLVE_BRANCH",async e=>{let t=await j.worktrees.previewTicketBranch({codebaseId:d(e.node.config.codebaseId??(0,s.getSessionValue)(e.sessionData,"codebase.id"),"Codebase ID",200),worktreeId:"string"==typeof(0,s.getSessionValue)(e.sessionData,"worktree.id")?String((0,s.getSessionValue)(e.sessionData,"worktree.id")):null,ticketKey:T(e)});return{output:t,sessionPatch:{worktree:{branch:t.branchName},ticket:{key:t.ticketKey,title:t.ticketTitle,type:t.ticketType}},links:[w(t.ticketKey,t.ticketTitle)]}}),$=I,G=C,$.register("GITHUB_LOAD_PR",async e=>{let t=A(e),r=await G.github.pullRequest(t.owner,t.name,R(e),"WORKFLOW_AUTOMATION");if(!r)throw Error("Pull request was not found");let i=_(r);return{output:i,sessionPatch:{pr:i},links:[y("PULL_REQUEST",(0,n.pullRequestResourceId)(t.owner,t.name,r.number),r.title,r.url)]}}),$.register("GITHUB_MERGE_PR",async e=>{let t=A(e),r=R(e),i=await G.github.pullRequestMergeOptions(t.owner,t.name,r,"WORKFLOW_AUTOMATION");if(!i.canMerge)throw Error(i.blockedReason||"Pull request cannot be merged");let a=await G.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:[b(e)]}}),$.register("GITHUB_COLLECT_REVIEW_THREADS",async e=>{let t=A(e),r=await G.github.pullRequest(t.owner,t.name,R(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:[b(e,r.title,r.url)]}}),$.register("GITHUB_REPLY_REVIEW_THREAD",async e=>{let t=await G.github.replyToReviewThread(d(e.node.config.threadId,"Review thread ID",500),d(e.node.config.body,"Review reply",1e5),"WORKFLOW_AUTOMATION"),r=E(e);return{output:t,links:r?[r]:void 0}}),$.register("GITHUB_SET_REVIEW_THREAD_RESOLVED",async e=>{let t=await G.github.setReviewThreadResolved(d(e.node.config.threadId,"Review thread ID",500),!1!==e.node.config.resolved,"WORKFLOW_AUTOMATION"),r=E(e);return{output:t,links:r?[r]:void 0}}),$.register("GITHUB_CREATE_PR",async e=>{let t=A(e),r=await G.github.createPullRequest({...t,baseRefName:d(e.node.config.baseRefName??(0,s.getSessionValue)(e.sessionData,"worktree.baseBranch"),"Base branch",500),headRefName:d(e.node.config.headRefName??(0,s.getSessionValue)(e.sessionData,"worktree.branch"),"Head branch",500),title:d(e.node.config.title??(0,s.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 G.worktrees.attachPullRequestForBranch(`github.com/${t.owner}/${t.name}`,r.headRefName,r);let i=_(r);return{output:i,sessionPatch:{pr:i},links:[y("PULL_REQUEST",(0,n.pullRequestResourceId)(t.owner,t.name,r.number),r.title,r.url)]}}),$.register("GITHUB_SET_PR_LABELS",async e=>{let t=A(e),r=Array.isArray(e.node.config.labels)?e.node.config.labels.map(String):[],i=await G.github.setPullRequestLabels({...t,number:R(e),labels:r});return{output:i.labels,sessionPatch:{pr:{labels:i.labels}},links:[b(e)]}}),$.register("GITHUB_RETRY_PIPELINE",async e=>{let t=await G.github.retryPipeline(d(e.node.config.repositoryId??(0,s.getSessionValue)(e.sessionData,"pr.repositoryGithubId"),"GitHub repository ID",500),d(e.node.config.checkSuiteId??(0,s.getSessionValue)(e.sessionData,"pipeline.checkSuiteId"),"Check suite ID",500),"WORKFLOW_AUTOMATION",{actor:"workflow",ipAddress:null}),r=S(e);return{output:t,sessionPatch:{pipeline:{status:t.status}},links:r?[r]:void 0}}),$.register("GITHUB_RETRY_JOB",async e=>{let t=await G.github.retryWorkflowJob(d(e.node.config.repositoryId,"GitHub repository ID",500),d(e.node.config.checkSuiteId,"Check suite ID",500),d(e.node.config.jobId,"Workflow job ID",500),"WORKFLOW_AUTOMATION",{actor:"workflow",ipAddress:null}),r=S(e);return{output:t,links:r?[r]:void 0}}),$.register("GITHUB_CANCEL_WORKFLOW_RUN",async e=>{let t=await G.github.cancelActionsWorkflowRun(d(e.node.config.codebaseRepositoryId??(0,s.getSessionValue)(e.sessionData,"repo.id"),"Codebase repository ID",500),d(e.node.config.workflowRunId??(0,s.getSessionValue)(e.sessionData,"pipeline.runId"),"Workflow run ID",500),!0===e.node.config.force,"WORKFLOW_AUTOMATION",{actor:"workflow",ipAddress:null}),r=S(e);return{output:t,sessionPatch:{pipeline:{status:"CANCELLED"}},links:r?[r]:void 0}}),$.register("GITHUB_SAVE_AUTO_RETRY",async e=>({output:await G.github.saveAutoRetryRule(c(e.node.config.input,"Auto-retry rule"))})),$.register("GITHUB_WAIT_CHECKS",async e=>{let t=d(e.node.config.repositoryId??(0,s.getSessionValue)(e.sessionData,"repo.id"),"Repository ID",500),r=d(e.node.config.workflowRunId??(0,s.getSessionValue)(e.sessionData,"pipeline.runId"),"Workflow run ID",500),i=S(e);return{links:i?[i]:void 0,wait:{kind:"GITHUB_CHECKS",externalKey:JSON.stringify({repositoryId:t,workflowRunId:r}),resumeAfter:(0,u.waitResumeAfter)(e.node.config),timeoutAt:(0,u.waitTimeoutAt)(e.node.config)}}}),F=I,z=C,F.register("WORKTREE_CREATE",async e=>{let t=D(e),r=await z.worktrees.createWorktree({codebaseId:O(e),selection:t,requestId:m(e,"create")});return g(e,r,{worktree:{branch:t.branchName,baseBranch:t.baseBranch}})}),F.register("WORKTREE_CHANGE_BRANCH",async e=>{let t=N(e),r=D(e),i=await z.worktrees.changeWorktreeBranch({worktreeId:t,selection:r,requestId:m(e,"change-branch"),stashOnFailure:!0===e.node.config.stashOnFailure});return g(e,i,{worktree:{branch:r.branchName,baseBranch:r.baseBranch}},[y("WORKTREE",t,"Worktree")])}),F.register("WORKTREE_COMMIT",async e=>{let t=N(e),r=!1!==e.node.config.stageAll,i=e.node.config.paths,a=Array.isArray(i)?i.map(e=>d(e,"Selected path",2e3)):[],n=await z.worktrees.commitWorktree({worktreeId:t,message:d(e.node.config.message,"Commit message",5e4),signed:"boolean"==typeof e.node.config.signed?e.node.config.signed:null,stageAll:r,paths:a,requestId:m(e,"commit")});return g(e,n,void 0,[y("WORKTREE",t,"Worktree")])}),F.register("WORKTREE_REFRESH_PULL_REQUEST",async e=>{let t=N(e),r=(await z.worktrees.refreshPullRequest(t)).pullRequest,i=r?_(r):null,a=[y("WORKTREE",t,"Worktree")];if(r){let[e,t]=r.repositoryNameWithOwner.split("/");e&&t&&a.push(y("PULL_REQUEST",(0,n.pullRequestResourceId)(e,t,r.number),r.title,r.url))}return{output:{found:!!r,pullRequest:r},sessionPatch:{pr:i},links:a}}),F.register("WORKTREE_OPERATION",async e=>{let t=String(e.node.config.operation??"SYNC").toUpperCase();if("OPEN_EDITOR"===t||!i.WORKTREE_OPERATIONS.includes(t))throw Error("Worktree operation is invalid for workflow execution");let r=N(e),a=await z.worktrees.runOperation(r,t,m(e,t.toLowerCase()),!0===e.node.config.forcePreparations);return g(e,a,void 0,[y("WORKTREE",r,"Worktree")])}),F.register("WORKTREE_PREPARATION",async e=>{let t=N(e),r=String(e.node.config.action??"INSPECT").toUpperCase();if(!i.WORKTREE_PREPARATION_ACTIONS.includes(r))throw Error("Worktree preparation action is invalid");let a=await z.worktrees.runPreparations([t],r,m(e,`preparation-${r.toLowerCase()}`)),n=a.jobs[0];if(!n)throw Error(a.skipped[0]?.reason??"Worktree preparation was not dispatched");return g(e,n,void 0,[y("WORKTREE",t,"Worktree")])}),F.register("WORKTREE_SET_AUTO_SYNC",async e=>{let t=N(e),r=String(e.node.config.action??"ENABLE").toUpperCase();if("FORCE"===r){let r=await z.worktreeAutomations.forceAutoSync(t,m(e,"force-auto-sync"));return g(e,r,void 0,[y("WORKTREE",t,"Worktree")])}let i="CANCEL"===r?{cancelled:await z.worktreeAutomations.cancelAutoSync(t)}:"RETRY"===r?await z.worktreeAutomations.retryAutoSync(t):"ENABLE"===r?await z.worktreeAutomations.configureAutoSync({worktreeId:t,conflictWorkflowId:h(e.node.config.conflictWorkflowId,500),conflictWorkflowChoice:h(e.node.config.conflictWorkflowChoice,500)}):null;if(!i)throw Error("Unknown Auto Sync action");return{output:i,sessionPatch:{worktree:{autoSync:i}},links:[y("WORKTREE",t,"Worktree")]}}),F.register("WORKTREE_SET_AUTO_MERGE",async e=>{let t,r=N(e),i=String(e.node.config.action??"ENABLE").toUpperCase();if("CANCEL"===i)t={cancelled:await z.worktreeAutomations.cancelAutoMerge(r)};else if("RETRY"===i)t=await z.worktreeAutomations.retryAutoMerge(r);else if("ENABLE"===i){let i=Number(e.node.config.pullRequestNumber??(0,s.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 z.worktreeAutomations.configureAutoMerge({worktreeId:r,repositoryNameWithOwner:d(e.node.config.repositoryNameWithOwner??(0,s.getSessionValue)(e.sessionData,"repo.nameWithOwner"),"Repository",500),pullRequestNumber:i,method:a,commitHeadline:d(e.node.config.commitHeadline??(0,s.getSessionValue)(e.sessionData,"pr.title"),"Commit headline",1e3),commitBody:String(e.node.config.commitBody??""),authorEmail:h(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:[y("WORKTREE",r,"Worktree")]}}),F.register("WORKTREE_DELETE",async e=>{let t=await z.worktrees.deleteWorktree({worktreeId:N(e),deleteRemoteBranch:!0===e.node.config.deleteRemoteBranch,requestId:m(e,"delete")});return g(e,t)}),F.register("WORKTREE_MOVE",async e=>{let t=await z.worktrees.moveWorktree({sourceWorktreeId:N(e),targetCodebaseId:d(e.node.config.targetCodebaseId,"Target codebase ID",500),targetWorktreeId:h(e.node.config.targetWorktreeId,500),deleteSource:!0===e.node.config.deleteSource,requestId:m(e,"move")}),r=t.targetWorktreeId??(!0===e.node.config.deleteSource?null:N(e));return{output:t,links:[...r?[y("WORKTREE",r,"Worktree")]:[],{kind:"WORKTREE_MOVE",resourceId:t.id,label:"Worktree move"}],wait:{kind:"WORKTREE_MOVE",externalKey:t.id,resumeAfter:(0,u.waitResumeAfter)(e.node.config),timeoutAt:(0,u.waitTimeoutAt)(e.node.config)}}}),F.register("WORKTREE_INSPECT",async e=>{let t=N(e),r=await z.worktrees.inspect(t,m(e,"inspect"));return{output:r,sessionPatch:{worktree:{commits:r.commits,changes:r.changes,branchChanges:r.branchChanges}},links:[y("WORKTREE",t,"Worktree")]}}),F.register("WORKTREE_INSPECT_GIT",async e=>{let t=N(e),r=await z.worktrees.inspectGitState(t,m(e,"inspect-git"));return{output:r,sessionPatch:{worktree:{...r}},links:[y("WORKTREE",t,"Worktree")]}}),F.register("WORKTREE_GIT_OPERATION",async e=>{let t=String(e.node.config.operation??"PULL_BRANCH").toUpperCase();if(!i.WORKTREE_GIT_OPERATIONS.includes(t))throw Error("Worktree Git operation is invalid");let r=N(e),a=await z.worktrees.runGitOperation({worktreeId:r,operation:t,branch:h(e.node.config.branch,500),stashOid:h(e.node.config.stashOid,200),stashChanges:!0===e.node.config.stashChanges,requestId:m(e,t.toLowerCase())});return g(e,a,void 0,[y("WORKTREE",r,"Worktree")])}),F.register("WORKTREE_WAIT_PUSH_READY",async e=>{let t=N(e);return{links:[y("WORKTREE",t,"Worktree")],wait:{kind:"WORKTREE_PUSH_READY",externalKey:t,resumeAfter:(0,u.waitResumeAfter)(e.node.config),timeoutAt:(0,u.waitTimeoutAt)(e.node.config)}}}),H=I,V=C,H.register("CODEBASE_FETCH_REFRESH",async e=>{let t=O(e),i="REFRESH"===e.node.config.operation?r.CODEBASE_REFRESH_JOB_KIND:r.CODEBASE_FETCH_JOB_KIND,a=await V.codebases.runOperation(i,[t],m(e,i)),n=a.jobs[0];if(!n)throw Error(a.skipped[0]?.reason??"Codebase operation was skipped");return g(e,n,void 0,[y("CODEBASE",t,"Codebase")])}),H.register("CODEBASE_INSPECT_GIT",async e=>{let t=O(e),r=await V.codebases.inspectGitState(t,m(e,"inspect-git"));return{output:r,sessionPatch:{codebase:{...r}},links:[y("CODEBASE",t,"Codebase")]}}),H.register("CODEBASE_GIT_OPERATION",async e=>{let t=String(e.node.config.operation??"PULL_BRANCH").toUpperCase();if(!r.CODEBASE_GIT_OPERATIONS.includes(t))throw Error("Codebase Git operation is invalid");let i=O(e),a=await V.codebases.runGitOperation({codebaseId:i,operation:t,branch:h(e.node.config.branch,500),stashOid:h(e.node.config.stashOid,200),stashChanges:!0===e.node.config.stashChanges,requestId:m(e,t.toLowerCase())});return g(e,a,void 0,[y("CODEBASE",i,"Codebase")])}),K=I,W=C,K.register("BUILD_START",async e=>{let r=String(e.node.config.action??"BUILD").toUpperCase();if(!t.BUILD_ACTIONS.includes(r))throw Error("Build action is invalid");let i=await W.builds.startBuild({worktreeId:N(e),configurationId:d(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:r,advancedSettings:e.node.config.advancedSettings,exportWhenComplete:!0===e.node.config.exportWhenComplete,exportSettings:e.node.config.exportSettings,worktreeCoverage:!0===e.node.config.worktreeCoverage,requestId:m(e,"build"),telemetryRequestOrigin:"workflow"});return{output:i,sessionPatch:{build:{id:i.id,status:i.status,action:i.action}},links:[{kind:"BUILD",resourceId:i.id,label:`${i.action} build`,url:`/builds/${i.id}`}],wait:{kind:"BUILD",externalKey:i.id,resumeAfter:(0,u.waitResumeAfter)(e.node.config),timeoutAt:(0,u.waitTimeoutAt)(e.node.config)}}}),K.register("BUILD_READ_TEST_RESULTS",async e=>{let t=P(e),r=(await W.builds.reportsForBuild(t)).filter(({kind:e,status:t})=>"TEST_RESULTS"===e&&"READY"===t).at(-1);if(!r)throw Error("Test results are not ready");let i=c(JSON.parse(r.summaryJson),"Test summary"),a=c(JSON.parse(r.dataJson),"Test results");return{output:{summary:i,tests:a.tests??[]},sessionPatch:{build:{testSummary:i,tests:a.tests??[]}},links:[y("BUILD",t,"Build",void 0)]}}),K.register("BUILD_READ_COVERAGE",async e=>{let t=P(e),r=(await W.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=c(JSON.parse(r.summaryJson),"Coverage summary"),a=c(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:[y("BUILD",t,"Build",`/builds/${t}/coverage`)]}}),K.register("BUILD_IMPORT_COVERAGE",async e=>{let t=N(e),r=await W.builds.importCoverageReport({worktreeId:t,buildName:h(e.node.config.buildName,200)??h((0,s.getSessionValue)(e.sessionData,"workflow.name"),200)??"Coverage report",reportPath:d(e.node.config.reportPath??"coverage/lcov.info","Coverage file",4e3),format:h(e.node.config.format)??"AUTO",requestId:m(e,"coverage-import")}),i=[y("WORKTREE",t,"Worktree"),y("BUILD",r.id,"Build",`/builds/${r.id}`)];return"jobId"in r&&"string"==typeof r.jobId?g(e,{id:r.jobId,timeoutSeconds:300},{build:{id:r.id}},i):{output:r,sessionPatch:{build:{id:r.id}},links:i}}),K.register("BUILD_EXPORT",async e=>{let t=P(e),r=await W.builds.exportArchive({buildId:t,requestId:m(e,"export"),settings:c(e.node.config.settings,"Export settings")});return r.jobId?g(e,{id:r.jobId,timeoutSeconds:3600},{build:{exportId:r.id}},[y("BUILD",t,"Build",void 0)]):{output:r,links:[y("BUILD",t,"Build",void 0)]}}),K.register("BUILD_DEPLOY",async e=>{let t=P(e),r=await W.builds.runBuild({buildId:t,destinations:Array.isArray(e.node.config.destinations)?e.node.config.destinations:[],requestId:m(e,"deploy")}),i=r.find(({jobId:e})=>!!e)?.jobId;return i?g(e,{id:i,timeoutSeconds:3600},void 0,[y("BUILD",t,"Build",void 0)]):{output:r,links:[y("BUILD",t,"Build",void 0)]}}),K.register("BUILD_CANCEL",async e=>{let t=P(e),r=await W.builds.cancelBuild(t);return{output:r,sessionPatch:{build:{id:r?.id,status:r?.status}},links:[y("BUILD",t,"Build",void 0)]}}),J=I,Y=C,X=async e=>{let t=await Y.diskSpace.snapshot(e);return{output:t,sessionPatch:t,links:[y("AGENT",e,t.agent.name,`/agents/${encodeURIComponent(e)}`)]}},J.register("DISK_SPACE_LOAD",async e=>X(x(e))),J.register("DISK_SPACE_REFRESH",async e=>{let t=x(e),r=await Y.diskSpace.requestRefresh(t);return{output:r,links:[y("AGENT",t,"Agent",`/agents/${encodeURIComponent(t)}`)],wait:{kind:"DISK_SPACE_REPORT",externalKey:JSON.stringify(r),resumeAfter:(0,u.waitResumeAfter)(e.node.config,2),timeoutAt:(0,u.waitTimeoutAt)(e.node.config,180)}}}),J.register("DISK_SPACE_UPDATE_THRESHOLDS",async e=>{let t=await Y.diskSpace.updateSettings({normalThresholdGiB:Number(e.node.config.normalThresholdGiB),pressureThresholdGiB:Number(e.node.config.pressureThresholdGiB)});return{output:t,sessionPatch:{disk:t}}}),J.register("DISK_SPACE_SET_MONITORING",async e=>{let t=x(e);return await Y.diskSpace.setMonitoring(t,!0===e.node.config.enabled),X(t)}),J.register("DISK_SPACE_SET_PRESSURE_MODE",async e=>{let t=x(e);return await Y.diskSpace.setManualPressureMode(t,!0===e.node.config.enabled),X(t)}),function(e,t){for(let[r,i]of(e.register("RUN_CREATE_PLAN",async e=>{let r=await t.runs.create(U(e,"PLAN"));if(!r)throw Error("Plan could not be created");return f(e,r,!0)}),e.register("RUN_CREATE_SESSION",async e=>{let r=await t.runs.create(U(e,"SESSION"));if(!r)throw Error("Session could not be created");return f(e,r,!0)}),e.register("RUN_PLAY_PLAN",async e=>{let r=e.node.config.worktreeConcurrencyLimit,i=await t.runs.playPlan(L(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 f(e,i,!0)}),e.register("RUN_FOLLOW_UP",async e=>{let r=U(e,"SESSION"),i=await t.runs.followUp(L(e),{...r,followUpMode:d(e.node.config.followUpMode??"RESUME","Follow-up mode",50),contextMode:h(e.node.config.contextMode,50)});if(!i)throw Error("Follow-up could not be created");return f(e,i,!0)}),e.register("RUN_STEER",async e=>{let r=await t.runs.steer(L(e),d(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 f(e,r)}),e.register("RUN_ANSWER",async e=>{let r=await t.runs.answerQuestion(d(e.node.config.batchId,"Question batch ID",500),e.node.config.answers??{});if(!r)throw Error("Question could not be answered");return f(e,r)}),[["RUN_PAUSE","PAUSE"],["RUN_CONTINUE","CONTINUE"],["RUN_CANCEL","CANCEL"]]))e.register(r,async e=>{let r=await t.runs.lifecycle(L(e),i);if(!r)throw Error("Run lifecycle operation failed");return f(e,r)});e.register("RUN_REVISE_ANSWER",async e=>{let r=d(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 f(e,i)}await t.runs.prepareAnswerRevision(r);let a=v(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:(0,u.waitResumeAfter)(e.node.config),timeoutAt:(0,u.waitTimeoutAt)(e.node.config)}}}),e.register("RUN_READ_RESULT",async e=>{let r=await t.runs.get(L(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 f(e,{...r,events:i,questions:a,usage:n,links:s})}),e.register("RUN_CAPTURE_CHECKPOINT",async e=>{let t=await (0,a.getPrismaClient)(),r=await t.runCheckpoint.findFirst({where:{runId:L(e)},orderBy:{createdAt:"desc"}});if(!r)throw Error("Run has no captured checkpoint");let i=v(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=L(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:v(e);return{output:{id:r,affected:a},links:n?[n]:void 0}})}(I,C),Q=I,Z=C,Q.register("SAVED_COMMAND",async e=>{let t=d(e.node.config.commandId,"Saved command",500),r=await Z.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",n=(0,o.commandOutputPattern)(e.node.config),c=(0,o.commandOutputMatchMode)(e.node.config),h=Array.isArray((0,s.getSessionValue)(e.sessionData,`steps.${e.node.id}.matches`))?(0,s.getSessionValue)(e.sessionData,`steps.${e.node.id}.matches`):[];if(n&&((0,l.compileCommandOutputPattern)(n),"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 p=String(e.node.config.targetMode??"CONTEXT"),m=null,f=null,g=new Set(["ANY_AGENT_HOME","SPECIFIC_AGENT_HOME"]).has(r.targetKind);if("FIXED_AGENT"===p)m=d(e.node.config.agentId,"Fixed agent",500);else if("FIXED_WORKTREE"===p)f=d(e.node.config.worktreeId,"Fixed worktree",500);else if(g){let t=(0,s.getSessionValue)(e.sessionData,"agent.id")??(0,s.getSessionValue)(e.sessionData,"codebase.agentId");if("string"==typeof t&&(m=t),!m){let t=(0,s.getSessionValue)(e.sessionData,"worktree.id");if("string"==typeof t){let e=await (0,a.getPrismaClient)(),r=await e.worktree.findUnique({where:{id:t},select:{codebase:{select:{agentId:!0}}}});m=r?.codebase.agentId??null}}}else{let t=(0,s.getSessionValue)(e.sessionData,"worktree.id");"string"==typeof t&&(f=t)}let y=await Z.commands.startRun({commandId:t,agentId:m,worktreeId:f,origin:"WORKFLOW",idempotencyKey:e.attempt.idempotencyKey,blocksGitOperations:e.run.blocksGitOperations});if(!y)throw Error("Command run could not be created");return{output:{id:y.id,displayNumber:y.displayNumber,status:y.status},sessionPatch:{steps:{[e.node.id]:{commandRunId:y.id,displayNumber:y.displayNumber,matches:h,latestMatch:h.at(-1)??null}}},links:[{kind:"COMMAND_RUN",resourceId:y.id,label:`Command #${y.displayNumber}`,url:`/commands/runs/${y.id}`}],wait:"WAIT_FOR_EXIT"===i?{kind:"COMMAND_RUN",externalKey:y.id,predicate:n?{outputMatch:{pattern:n,mode:c,matchCount:h.length,matched:"ONCE"===c&&h.length>0,scanAttempt:1,scanCharacterOffset:0,observedAttempt:0,observedSequence:-1}}:void 0,resumeAfter:(0,u.waitResumeAfter)(e.node.config),timeoutAt:(0,u.waitTimeoutAt)(e.node.config)}:void 0}}),Q.register("CUSTOM_COMMAND",async e=>{let t=d(e.node.config.script,"Custom command",1e6),r="FIRE_AND_FORGET"===e.node.config.completionMode?"FIRE_AND_FORGET":"WAIT_FOR_EXIT",i=(0,o.commandOutputPattern)(e.node.config),a=(0,o.commandOutputMatchMode)(e.node.config),n=Array.isArray((0,s.getSessionValue)(e.sessionData,`steps.${e.node.id}.matches`))?(0,s.getSessionValue)(e.sessionData,`steps.${e.node.id}.matches`):[];if(i&&((0,l.compileCommandOutputPattern)(i),"WAIT_FOR_EXIT"!==r))throw Error("Output matching requires Wait for exit completion");let c=String(e.node.config.targetMode??"CONTEXT"),h=null,p=null;if("FIXED_AGENT"===c)h=d(e.node.config.agentId,"Fixed agent",500);else if("FIXED_WORKTREE"===c)p=d(e.node.config.worktreeId,"Fixed worktree",500);else{let t=(0,s.getSessionValue)(e.sessionData,"worktree.id");if("string"==typeof t)p=t;else{let t=(0,s.getSessionValue)(e.sessionData,"agent.id")??(0,s.getSessionValue)(e.sessionData,"codebase.agentId");"string"==typeof t&&(h=t)}}if(!h&&!p)throw Error("Custom command context has no agent or worktree target");let m=await Z.commands.startCustomRun({script:t,agentId:h,worktreeId:p,origin:"WORKFLOW",idempotencyKey:e.attempt.idempotencyKey,blocksGitOperations:e.run.blocksGitOperations});if(!m)throw Error("Custom command run could not be created");return{output:{id:m.id,displayNumber:m.displayNumber,status:m.status},sessionPatch:{steps:{[e.node.id]:{commandRunId:m.id,displayNumber:m.displayNumber,matches:n,latestMatch:n.at(-1)??null}}},links:[{kind:"COMMAND_RUN",resourceId:m.id,label:`Command #${m.displayNumber}`,url:`/commands/runs/${m.id}`}],wait:"WAIT_FOR_EXIT"===r?{kind:"COMMAND_RUN",externalKey:m.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:(0,u.waitResumeAfter)(e.node.config),timeoutAt:(0,u.waitTimeoutAt)(e.node.config)}:void 0}}),Q.register("SKILL_APPLY",async e=>{let t=await Z.skills.prepareSync(e.node.config.groupId?"GROUP":"ALL",h(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:(0,u.waitResumeAfter)(e.node.config),timeoutAt:(0,u.waitTimeoutAt)(e.node.config)}}}),Q.register("NOTIFICATION_SEND",async e=>{let t=await (0,a.getPrismaClient)(),r=await t.$transaction(t=>Z.notifications.recordInTransaction(t,{dedupeKey:`${e.run.id}:${e.node.id}:${e.attempt.generation}`,typeKey:"WORKFLOW_MESSAGE",title:d(e.node.config.title,"Notification title",240),body:d(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,s.getSessionValue)(e.sessionData,"worktree.id")?String((0,s.getSessionValue)(e.sessionData,"worktree.id")):null}));return Z.notifications.created(r),{output:r}}),Q.register("IOS_PUSH_SEND",async e=>({output:await Z.pushNotifications.send({requestId:m(e,"ios-push"),editor:e.node.config.editor,targetMode:d(e.node.config.targetMode??"ALL","Push target mode",50),registrationIds:Array.isArray(e.node.config.registrationIds)?e.node.config.registrationIds.map(String):[],channelId:h(e.node.config.channelId,500),directToken:h(e.node.config.directToken,2e4),directTokenEncoding:"BASE64"===e.node.config.directTokenEncoding?"BASE64":"HEX",directEnvironment:"PRODUCTION"===e.node.config.directEnvironment?"PRODUCTION":"SANDBOX"})})),ee=async(e,t,r)=>{let i=await Z.tools.callTool({groupId:"builtin:sse",name:t,arguments:r},{caller:`workflow:${e.run.id}`,correlationId:e.attempt.id,source:"WORKFLOW"});return{output:i,sessionPatch:{sse:{action:i},steps:{[e.node.id]:{output:i}}}}},Q.register("SSE_ENDPOINT_ACTION",async e=>{let t=d(e.node.config.operation,"SSE endpoint operation",50),r=h(e.node.config.endpointId,500),i=c(e.node.config.input??{},"SSE endpoint input"),a={CREATE:{name:"sse_endpoint_create",arguments:i},UPDATE:{name:"sse_endpoint_update",arguments:{id:r,endpoint:i}},SET_MODE:{name:"sse_endpoint_set_mode",arguments:{id:r,mode:i.mode}},ROTATE_TOKEN:{name:"sse_endpoint_rotate_token",arguments:{id:r}},DELETE:{name:"sse_endpoint_delete",arguments:{id:r}}}[t];if(!a)throw Error("Unsupported SSE endpoint workflow operation");if("CREATE"!==t&&!r)throw Error("SSE endpoint ID is required");return ee(e,a.name,a.arguments)}),Q.register("SSE_MOCK_ACTION",async e=>{let t=d(e.node.config.operation,"SSE mock operation",50),r=h(e.node.config.endpointId,500),i=h(e.node.config.resourceId,500),a=c(e.node.config.input??{},"SSE mock input"),n={SAVE_TEMPLATE:{name:"sse_mock_template_save",arguments:{endpointId:r,id:i,...a}},DELETE_TEMPLATE:{name:"sse_mock_template_delete",arguments:{id:i}},SAVE_COMPOSITION:{name:"sse_mock_composition_save",arguments:{endpointId:r,id:i,composition:a}},ACTIVATE_COMPOSITION:{name:"sse_mock_composition_activate",arguments:{endpointId:r,compositionId:i}},DELETE_COMPOSITION:{name:"sse_mock_composition_delete",arguments:{id:i}}}[t];if(!n)throw Error("Unsupported SSE mock workflow operation");return ee(e,n.name,n.arguments)}),Q.register("SSE_STORAGE_ACTION",async e=>{let t=d(e.node.config.operation,"SSE storage operation",50),r=d(e.node.config.key,"SSE storage key",256),i={SET:{name:"sse_storage_set",arguments:{key:r,value:e.node.config.value}},COMPARE_AND_SET:{name:"sse_storage_compare_and_set",arguments:{key:r,expectedVersion:e.node.config.expectedVersion??null,value:e.node.config.value}},INCREMENT:{name:"sse_storage_increment",arguments:{key:r,delta:e.node.config.delta??1}},DELETE:{name:"sse_storage_delete",arguments:{key:r}}}[t];if(!i)throw Error("Unsupported SSE storage workflow operation");return ee(e,i.name,i.arguments)}),Q.register("SSE_BREAKPOINT_RESOLVE",async e=>ee(e,"sse_breakpoint_resolve",{id:d(e.node.config.breakpointId,"SSE breakpoint ID",500),version:e.node.config.version,resolution:e.node.config.resolution,mockCompositionId:e.node.config.mockCompositionId??null,adHocComposition:e.node.config.adHocComposition??null})),Q.register("SSE_HISTORY_CLEAR",async e=>ee(e,"sse_history_clear",{endpointId:e.node.config.endpointId??null,ids:e.node.config.ids??null})),Q.register("SSE_SCRIPT_TEST",async e=>ee(e,"sse_script_test",{source:d(e.node.config.source,"SSE script",1e5),context:e.node.config.context??{},timeoutMs:e.node.config.timeoutMs,memoryLimitMb:e.node.config.memoryLimitMb,fetchTimeoutMs:e.node.config.fetchTimeoutMs})),Q.register("MCP_CALL",async e=>{let t=await Z.tools.callTool({groupId:d(e.node.config.groupId,"MCP tool group",500),name:d(e.node.config.name,"MCP tool name",500),arguments:c(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=c(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=c(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:(0,u.waitResumeAfter)(e.node.config),timeoutAt:(0,u.waitTimeoutAt)(e.node.config,i)}),a=(e,t,r,i)=>p(e,t,r,i),n=e=>({projectId:a(e,"projectId","pr.projectId","GitLab project ID"),iid:Number(e.node.config.iid??(0,s.getSessionValue)(e.sessionData,"pr.iid")??(0,s.getSessionValue)(e.sessionData,"pr.number"))}),o=e=>({pr:c(e.mergeRequest,"GitLab merge request output")});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:c(e.run,"Command run output")}),wait:t=>i(e,"COMMAND_RUN",d(c(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:c(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:d(e.node.config.scope,"Diff scope",100),path:e.node.config.path,previousPath:e.node.config.previousPath,commitSha:e.node.config.commitSha,requestId:m(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,s.mergeSessionData)(await t.worktrees.workflowSessionDataForWorktree(i,{includeMissing:!0}),{worktree:c(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:d(e.node.config.moveId,"Move ID",500)},{sessionPatch:async e=>{let r=c(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,s.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:m(e,"rebuild")},{sessionPatch:e=>({build:c(e.build,"Build output")}),wait:t=>i(e,"BUILD",d(c(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:m(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:c(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:d(e.node.config.itemId,"Conflict item ID",500),resolution:String(e.node.config.resolution??"SKIP")}},{sessionPatch:e=>({skillSync:c(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:c(e.run,"Skill sync output")})})),e.register("BUILD_DATA_REFRESH",e=>r(e,"builtin:build-data","refresh_build_data",{requestId:m(e,"build-data")},{sessionPatch:e=>({buildData:c(e.collection,"Build-data collection output")}),wait:t=>{let r=c(t.collection,"Build-data collection output");return"COMPLETED"===r.status?void 0:i(e,"BUILD_DATA_COLLECTION",d(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:m(e,"build-data-delete"),overrideProtection:!0===e.node.config.overrideProtection},{sessionPatch:e=>({buildData:c(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:d(e.node.config.entryId,"Entry ID",500),locked:!0===e.node.config.locked},{sessionPatch:e=>({buildData:{id:t,entry:e.entry}})})});let l=async(e,t,a)=>{let n=await r(e,"builtin:tailscale",t,a,{sessionPatch:e=>{let t=c(e.operation,"Tailscale operation output");return{tailscale:{operation:t,operationId:t.id,status:t.status,templateId:t.templateId}}},wait:t=>{let r=c(t.operation,"Tailscale operation output");return["SUCCEEDED","FAILED","PARTIAL_FAILED"].includes(String(r.status))?void 0:i(e,"TAILSCALE_SERVE_OPERATION",d(r.id,"Tailscale operation ID",500),604800)}}),s=c(c(n.output,"Tailscale tool output").operation,"Tailscale operation output");return{...n,links:[{kind:"TAILSCALE_SERVE_OPERATION",resourceId:d(s.id,"Tailscale operation ID",500),label:"Tailscale Serve",url:"/tailscale"}]}};for(let[u,p]of(e.register("TAILSCALE_SERVE_INSPECT",e=>l(e,"inspect_tailscale_serve",{agentIds:Array.isArray(e.node.config.agentIds)?e.node.config.agentIds.map(String):[],requestId:m(e,"tailscale-inspect")})),e.register("TAILSCALE_SERVE_UPSERT_TEMPLATE",e=>{let t=h(e.node.config.templateId,500),r=Number(e.node.config.expectedRevision),i=Array.isArray(e.node.config.agentIds)?e.node.config.agentIds.map(e=>d(e,"Agent ID",500)):[];return l(e,"upsert_tailscale_serve_template",{input:{...t?{id:t,expectedRevision:r}:{},name:d(e.node.config.name,"Template name",200),protocol:d(e.node.config.protocol??"HTTPS","Listener protocol",50),listenPort:Number(e.node.config.listenPort),mountPath:String(e.node.config.mountPath??"/"),destinationProtocol:d(e.node.config.destinationProtocol??"HTTP","Destination protocol",50),destinationPort:Number(e.node.config.destinationPort),destinationPath:String(e.node.config.destinationPath??""),funnel:!0===e.node.config.funnel,appCapabilities:Array.isArray(e.node.config.appCapabilities)?e.node.config.appCapabilities.map(e=>d(e,"App capability",500)):[],proxyProtocol:d(e.node.config.proxyProtocol??"NONE","PROXY protocol",20),assignments:i.map(e=>({agentId:e,enabled:!0}))},requestId:m(e,"tailscale-upsert")})}),e.register("TAILSCALE_SERVE_SET_AGENT_ENABLED",e=>l(e,"set_tailscale_serve_agent_enabled",{templateId:a(e,"templateId","tailscale.templateId","Tailscale template ID"),agentId:d(e.node.config.agentId,"Agent ID",500),enabled:!0===e.node.config.enabled,expectedRevision:Number(e.node.config.expectedRevision),requestId:m(e,"tailscale-assignment")})),e.register("TAILSCALE_SERVE_DELETE_TEMPLATE",e=>l(e,"delete_tailscale_serve_template",{id:a(e,"templateId","tailscale.templateId","Tailscale template ID"),expectedRevision:Number(e.node.config.expectedRevision),requestId:m(e,"tailscale-delete")})),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:d(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:[d(c(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:c(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:c(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"),c(e.node.config.settings,"Cadence settings"));return{output:r,sessionPatch:{agent:c(r,"Agent output")}}}),e.register("CCUSAGE_COLLECT",async e=>{let r=await t.ccusage.collect(m(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:o})),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:d(e.node.config.title??(0,s.getSessionValue)(e.sessionData,"ticket.title"),"Merge request title",500),description:h(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:o})),e.register("GITLAB_UPDATE_MR",e=>r(e,"builtin:gitlab","gitlab_update_merge_request",{...n(e),title:h(e.node.config.title),description:h(e.node.config.description),stateEvent:h(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:o})),e.register("GITLAB_SUBMIT_REVIEW",e=>r(e,"builtin:gitlab","gitlab_submit_review",{...n(e),outcome:String(e.node.config.outcome??"COMMENT"),body:h(e.node.config.body)})),e.register("GITLAB_REPLY_DISCUSSION",e=>r(e,"builtin:gitlab","gitlab_reply_discussion",{...n(e),discussionId:d(e.node.config.discussionId,"Discussion ID",500),body:d(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:d(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:h(e.node.config.sha)},{sessionPatch:o})),[["GITLAB_SET_MR_LABELS","labels"],["GITLAB_REQUEST_REVIEWERS","reviewerIds"]]))e.register(u,e=>r(e,"builtin:gitlab","gitlab_update_merge_request",{...n(e),[p]:Array.isArray(e.node.config[p])?e.node.config[p].map(String):[]},{sessionPatch:o}));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",c(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:(0,u.waitResumeAfter)(e.node.config),timeoutAt:(0,u.waitTimeoutAt)(e.node.config)}}));let f=async(e,t,i)=>{let a=await r(e,"builtin:github",t,i),n=c(a.output,"GitHub tool output"),s=_(c(n.pullRequest,"Pull request output"));return{...a,sessionPatch:{...a.sessionPatch,pr:s}}},g=e=>({owner:d(e.node.config.owner??(0,s.getSessionValue)(e.sessionData,"repo.owner"),"Repository owner",200),name:d(e.node.config.name??(0,s.getSessionValue)(e.sessionData,"repo.name"),"Repository name",200),number:Number(e.node.config.number??(0,s.getSessionValue)(e.sessionData,"pr.number"))});e.register("GITHUB_UPDATE_PR",e=>f(e,"update_pull_request",{...g(e),title:h(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=>f(e,"submit_pull_request_review",{...g(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=>f(e,"request_pull_request_reviewers",{...g(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:d(e.node.config.workflowId,"Workflow ID",500),ref:d(e.node.config.ref,"Git ref",500),inputs:e.node.config.inputs?c(e.node.config.inputs,"Workflow inputs"):void 0},{sessionPatch:e=>({pipeline:e})}));let y=async(e,t,i)=>{let a=await r(e,"builtin:jira",t,i),n=c(a.output,"Jira tool output"),s=k(c(n.ticket,"Jira ticket output"));return{...a,sessionPatch:{...a.sessionPatch,ticket:s}}};e.register("JIRA_CREATE_TICKET",e=>y(e,"create_jira_ticket",{projectKey:d(e.node.config.projectKey,"Project key",100),issueTypeId:d(e.node.config.issueTypeId,"Issue type ID",100),summary:d(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?c(e.node.config.fields,"Additional Jira fields"):void 0})),e.register("JIRA_ADD_WORKLOG",e=>y(e,"add_jira_worklog",{issueKey:a(e,"issueKey","ticket.key","Issue key"),timeSpentSeconds:Number(e.node.config.timeSpentSeconds),startedAt:h(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=>y(e,"link_jira_tickets",{inwardIssueKey:a(e,"inwardIssueKey","ticket.key","Inward issue key"),outwardIssueKey:d(e.node.config.outwardIssueKey,"Outward issue key",100),linkType:d(e.node.config.linkType,"Link type",100)}))}(I,C)}])},381494,e=>{"use strict";var t=e.i(666680),r=e.i(243783);e.s(["WorkflowEventsService",0,class{nextMaintenanceAt=0;async record(e){let t=await (0,r.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,r){let i=await e.workflowTriggerEvent.findUnique({where:{dedupeKey:r.dedupeKey}});return i||e.workflowTriggerEvent.create({data:{id:(0,t.randomUUID)(),kind:r.kind,subjectKey:r.subjectKey,dedupeKey:r.dedupeKey,payloadJson:JSON.stringify(r.payload)}})}async maintain(){let e=Date.now();if(e<this.nextMaintenanceAt)return;let t=await (0,r.getPrismaClient)(),i=await t.workflowTriggerEvent.findMany({where:{status:"FAILED",receivedAt:{lt:new Date(e-6048e5)}},select:{id:!0},orderBy:{receivedAt:"asc"},take:1e3});if(i.length){await t.workflowTriggerEvent.deleteMany({where:{id:{in:i.map(({id:e})=>e)}}}),this.nextMaintenanceAt=0;return}this.nextMaintenanceAt=e+36e5}}])},420533,e=>{"use strict";var t=e.i(666680),r=e.i(586589),i=e.i(119909);e.i(805422);var a=e.i(661983),n=e.i(243783),s=e.i(499162);e.i(714327);var o=e.i(508813);function l(e){try{let t=JSON.parse(e);return t&&"object"==typeof t&&!Array.isArray(t)?t:{}}catch{return{}}}function u(e,t){return{id:e.id,name:e.name,url:e.displayOrigin,canonicalOrigin:e.canonicalOrigin,displayOrigin:e.displayOrigin,defaultBranch:t??null}}function c(e){return{id:e.id,name:e.name,hostname:e.hostname,connected:null===e.disconnectedAt,diskFreeBytes:e.diskFreeBytes,memoryFreeBytes:e.memoryFreeBytes}}e.s(["WorkflowEventBridge",0,class{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===i.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,s.mergeSessionData)(t,{worktree:{id:e.worktreeId},automation:{jobId:e.id,status:e.status,error:e.error,result:l(e.resultJson??"{}")}}),{cursorValue:`${e.id}:${e.status}`})}if("ccusage.report"===e.kind&&"SUCCEEDED"===e.status&&e.resultJson){let t=l(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,s.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=a.agentEventBus.iterate(a.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=a.agentEventBus.iterate(a.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=a.agentEventBus.iterate(a.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,s.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=a.agentEventBus.iterate(a.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=a.agentEventBus.iterate(a.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=a.agentEventBus.iterate(a.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=a.agentEventBus.iterate(a.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=a.agentEventBus.iterate(a.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=a.agentEventBus.iterate(a.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=a.agentEventBus.iterate(a.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=a.agentEventBus.iterate(a.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=a.agentEventBus.iterate(a.TOOL_CALL_AUDIT_CHANGED_TOPIC);try{for await(let t of e){if(!this.running)break;let e=await (0,n.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,s=a?null:await e.workflowStepAttempt.findUnique({where:{id:r.correlationId},select:{run:{select:{id:!0,workflowId:!0}}}}),o=a??s?.run??null,l=r.finishedAt?.toISOString()??"unfinished";await this.record("TOOL_CALL_RESULT",r.id,`tool-call:${r.id}:${r.resultStatus}:${l}`,{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}:${l}`,...o?{workflowCorrelation:{workflowId:o.workflowId,runId:o.id}}:{}})}}finally{await e.return?.()}}async observeRun(e){let t=await (0,n.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),o=(0,s.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:u(r.worktree.codebase.repository,r.worktree.codebase.defaultBranch)}:{},...r.agent?{agent:c(r.agent)}:{},...r.jiraIssueKey?{ticket:{key:r.jiraIssueKey}}:{}}),l=i?{workflowId:i.run.workflowId,runId:i.runId,attemptId:i.attemptId}:null,d={cursorValue:`${r.status}:${r.phase}`,workflowCorrelation:l};r.startedAt&&await this.record("RUN_STARTED",r.id,`run-started:${r.id}:${r.startedAt.toISOString()}`,o,d);let h="COMPLETED"===r.status?"RUN_COMPLETED":"FAILED"===r.status?"RUN_FAILED":"CANCELLED"===r.status?"RUN_CANCELLED":"PAUSED"===r.status?"RUN_PAUSED":null;h&&await this.record(h,r.id,`run-status:${r.id}:${r.status}:${r.finishedAt?.toISOString()??r.updatedAt.toISOString()}`,o,d),"RUNNING"===r.phase&&r.startedAt&&r.updatedAt>r.startedAt&&await this.record("RUN_CONTINUED",r.id,`run-continued:${r.id}:${r.updatedAt.toISOString()}`,o,d),r.sourcePlanId&&await this.record("RUN_PLAN_PLAYED",r.id,`run-plan-played:${r.id}:${r.sourcePlanId}`,o,d),r.parentRunId&&"PLAN_PLAY"!==r.followUpMode&&await this.record("RUN_FOLLOW_UP",r.id,`run-follow-up:${r.id}:${r.parentRunId}`,o,d),"IMPORTED"===r.origin&&await this.record("RUN_IMPORTED",r.id,`run-imported:${r.id}:${r.updatedAt.toISOString()}`,o,d),await this.record("RUN_USAGE_THRESHOLD",r.id,`run-usage:${r.id}:${r.updatedAt.toISOString()}`,o,{...d,cursorValue:r.updatedAt.toISOString()});let p=r.questionBatches[0];if(p){let e={...o,run:{...o.run,questions:p.questions}};"PENDING"===p.status?await this.record("RUN_QUESTION_NEEDED",r.id,`run-question:${p.id}:pending`,e,d):"ANSWERED"===p.status&&await this.record("RUN_QUESTION_ANSWERED",r.id,`run-question:${p.id}:answered`,e,d)}let m=r.events[0];m&&await this.record("RUN_EVENT_MATCH",r.id,`run-event:${m.id}`,o,{...d,event:m});let f=r.toolCalls[0];f&&await this.record("RUN_EVENT_MATCH",r.id,`run-tool:${f.id}:${f.status}`,o,{...d,toolCall:f})}async consumeBuilds(){let e=a.agentEventBus.iterate(a.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,n.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,s.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:u(r.codebase.repository,r.codebase.defaultBranch),agent:c(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=l(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=a.agentEventBus.iterate(a.WORKTREE_CHANGED_TOPIC);try{for await(let t of e){if(!this.running)break;let e=t.worktreeOverviewChanged,r=await (0,n.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,s.mergeSessionData)(i,{repo:u(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=a.agentEventBus.iterate(a.CODEBASE_CHANGED_TOPIC);try{for await(let t of e){if(!this.running)break;let e=await (0,n.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:u(t.repository,t.defaultBranch),agent:c(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=(0,o.diskSpaceStateCursor)(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((0,o.diskSpaceSessionData)(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 r=await this.diskSpace.overview();for(let i of r.agents){let a=(0,o.diskSpaceSessionData)(r.settings,i,e?"STARTUP_RECONCILE":"STATE_AUDIT"),n=JSON.stringify((0,o.diskSpaceStateCursor)(a));(e||this.diskStateFingerprints.get(i.agent.id)!==n)&&await this.emitDiskSnapshot(a,{changeId:(0,t.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*r.DISK_SPACE_POLL_INTERVAL_SECONDS),this.diskAuditTimer.unref?.())}}async consumeAgents(){let e=a.agentEventBus.iterate(a.AGENT_CHANGED_TOPIC);try{for await(let t of e){if(!this.running)break;let e=await (0,n.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?.()}}}])},499162,e=>{"use strict";let t=/^([A-Za-z0-9_-]+)(?:\[(\d+)\])?$/,r=/^[A-Za-z0-9_-]+(?:\[\d+\])?(?:\.[A-Za-z0-9_-]+(?:\[\d+\])?)*$/,i=/\{\{\s*([A-Za-z0-9_-]+(?:\[\d+\])?(?:\.[A-Za-z0-9_-]+(?:\[\d+\])?)*)\s*\}\}/g,a=/\{\{([^{}]*)\}\}/g;function n(e){return e.split(".").flatMap(r=>{let i=t.exec(r);if(!i)throw Error(`Invalid session path: ${e}`);return void 0===i[2]?[i[1]]:[i[1],Number(i[2])]})}function s(e,t){let r=e;for(let e of n(t)){if(null==r)return;if("number"==typeof e){if(!Array.isArray(r))return;r=r[e]}else{if("object"!=typeof r||Array.isArray(r))return;r=r[e]}}return r}e.s(["getSessionValue",0,s,"hasSessionValue",0,function(e,t){return void 0!==s(e,t)},"invalidWorkflowValueBindings",0,function e(t,i=[]){if(Array.isArray(t))for(let r of t)e(r,i);else if(t&&"object"==typeof t)for(let a of("SESSION"!==t.source||"string"==typeof t.path&&r.test(t.path)||i.push("Session bindings require a valid dotted path"),Object.values(t)))e(a,i);else if("string"==typeof t&&/\{\{|\}\}/.test(t)){let e=t.replace(a,"");for(let n of(/\{\{|\}\}/.test(e)&&i.push("Text interpolation contains unmatched braces"),t.matchAll(a)))r.test(n[1].trim())||i.push("Text interpolation requires a valid dotted path")}return i},"mergeSessionData",0,function(e,t){let r=(e,t)=>{if(e&&t&&"object"==typeof e&&"object"==typeof t&&!Array.isArray(e)&&!Array.isArray(t)){let i={...e};for(let[e,a]of Object.entries(t))i[e]=r(i[e],a);return i}return structuredClone(t)};return r(e,t)},"resolveWorkflowValue",0,function e(t,r){var a,n;return t&&"object"==typeof t&&!Array.isArray(t)&&"SESSION"===t.source&&"string"==typeof t.path?s(r,t.path):t&&"object"==typeof t&&!Array.isArray(t)&&"LITERAL"===t.source?t.value:Array.isArray(t)?t.map(t=>e(t,r)):t&&"object"==typeof t?Object.fromEntries(Object.entries(t).map(([t,i])=>[t,e(i,r)])):"string"==typeof t?(a=t,n=r,a.replace(i,(e,t)=>{let r=s(n,t);return null==r?"":"string"==typeof r?r:JSON.stringify(r)})):t},"setSessionValue",0,function(e,t,r){let i=structuredClone(e),a=n(t),s=i;return a.forEach((e,i)=>{if(i===a.length-1){if("number"==typeof e){if(!Array.isArray(s))throw Error(`Expected an array at ${t}`);s[e]=r}else{if(Array.isArray(s))throw Error(`Expected an object at ${t}`);s[e]=r}return}let n="number"==typeof a[i+1];if("number"==typeof e){if(!Array.isArray(s))throw Error(`Expected an array at ${t}`);let r=s[e];r&&"object"==typeof r||(s[e]=n?[]:{}),s=s[e]}else{if(Array.isArray(s))throw Error(`Expected an object at ${t}`);let r=s[e];r&&"object"==typeof r||(s[e]=n?[]:{}),s=s[e]}}),i},"workflowSessionData",0,function(e){let t=JSON.parse(e);if(!t||"object"!=typeof t||Array.isArray(t))throw Error("Workflow session data must be a JSON object");return t},"workflowValueSessionPaths",0,function e(t,a=new Set){if(Array.isArray(t))for(let r of t)e(r,a);else if(t&&"object"==typeof t)for(let i of("SESSION"===t.source&&"string"==typeof t.path&&r.test(t.path)&&a.add(t.path),Object.values(t)))e(i,a);else if("string"==typeof t)for(let e of t.matchAll(i))a.add(e[1]);return a}])},493015,49172,e=>{"use strict";var t=e.i(397554),r=e.i(827957);e.i(582482);var i=e.i(783396),a=e.i(318905),n=e.i(91022);class s extends Error{status;errors;constructor(e,t,r){super(e),this.status=t,this.errors=r,this.name="AppleDeveloperRequestError"}}async function o(e=new n.CredentialService){let t=await e.getJson(a.CREDENTIALS.appStoreConnectSettings);if(!t)throw Error("App Store Connect API credentials are not configured");let r=(0,i.appStoreConnectConnectionSettings)(t),s=await e.getText(a.CREDENTIALS.appStoreConnectPrivateKey);if(!s)throw Error("App Store Connect API credentials are not configured");return{issuerId:r.issuerId,keyId:r.keyId,privateKey:s}}e.s(["AppleDeveloperClient",0,class{credentials;fetcher;constructor(e,t=fetch){this.credentials=e,this.fetcher=t}async token(){let e;try{e=await (0,t.importPKCS8)(this.credentials.privateKey,"ES256")}catch{throw Error("The App Store Connect key must be an ES256 PKCS#8 private key")}return new r.SignJWT({}).setProtectedHeader({alg:"ES256",kid:this.credentials.keyId,typ:"JWT"}).setIssuer(this.credentials.issuerId).setAudience("appstoreconnect-v1").setIssuedAt().setExpirationTime("15m").sign(e)}async request(e,t={}){let r,i=await this.token(),a=e.startsWith("http")?e:`https://api.appstoreconnect.apple.com${e}`;try{r=await this.fetcher(a,{...t,signal:t.signal??AbortSignal.timeout(2e4),headers:{accept:"application/json",authorization:`Bearer ${i}`,...t.body?{"content-type":"application/json"}:{},...t.headers}})}catch(e){if(e instanceof Error&&("TimeoutError"===e.name||"AbortError"===e.name))throw Error("Apple Developer API timed out; retry the operation");throw Error("Could not connect to the Apple Developer API")}if(204===r.status)return;let n=await r.json().catch(()=>({}));if(!r.ok){let e=n.errors?.map(e=>e.detail||e.title||e.code).filter(Boolean).join("; ");throw new s(401===r.status||403===r.status?"Apple rejected the API key or it lacks Certificates, Identifiers & Profiles permission":e||`Apple Developer API returned HTTP ${r.status}`,r.status,n.errors??[])}return n}async list(e){let t=[],r=e;for(;r;){let e=await this.request(r);t.push(...e.data),r=e.links?.next??null}return t}listProfiles(){return this.list("/v1/profiles?limit=200&include=bundleId,certificates,devices")}listCertificates(){return this.list("/v1/certificates?limit=200")}listBundleIds(){return this.list("/v1/bundleIds?limit=200")}listDevices(){return this.list("/v1/devices?limit=200")}async createProfile(e){let t={bundleId:{data:{type:"bundleIds",id:e.bundleIdId}},certificates:{data:e.certificateIds.map(e=>({type:"certificates",id:e}))}};return e.deviceIds?.length&&(t.devices={data:e.deviceIds.map(e=>({type:"devices",id:e}))}),this.request("/v1/profiles",{method:"POST",body:JSON.stringify({data:{type:"profiles",attributes:{name:e.name,profileType:e.profileType},relationships:t}})})}deleteProfile(e){return this.request(`/v1/profiles/${encodeURIComponent(e)}`,{method:"DELETE"})}revokeCertificate(e){return this.request(`/v1/certificates/${encodeURIComponent(e)}`,{method:"DELETE"})}},"AppleDeveloperRequestError",0,s,"storedAppleDeveloperCredentials",0,o],49172),e.s([],493015)},925991,e=>{"use strict";var t=e.i(666680),r=e.i(885418),i=e.i(243783);e.i(805422);var a=e.i(694355),n=e.i(661983),s=e.i(504173),o=e.i(518733);let l=new Set(["SUCCEEDED","FAILED","CANCELLED","TIMED_OUT","INVALID"]),u={agents:{include:{agent:!0}},jobs:{orderBy:{createdAt:"asc"}}};function c(e){return null!==e.lastSeenAt&&Date.now()-e.lastSeenAt.getTime()<=(0,a.agentOnlineWindowMs)(e)&&null===e.disconnectedAt}function d(e){try{let t=JSON.parse(e.capabilitiesJson);return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}catch{return[]}}function h(e){return null===e?null:JSON.parse(e)}function p(e){let t=h(e.payloadJson);return(e.kind===r.BUILD_DATA_DELETE_JOB_KIND?(0,r.buildDataDeletePayload)(t).targets:(0,r.buildDataTargetsPayload)(t).targets).map(e=>e.path)}function m(e,t){let i=e===r.BUILD_DATA_DELETE_JOB_KIND?"delete":"size";return`Invalid Build Data ${i} result: ${t instanceof Error?t.message:String(t)}`}function f(e,t,r){try{for(let i of p(t)){let a=e.get(g(t.agentId,i));a&&(a.error=r)}}catch{}}function g(e,r){return(0,t.createHash)("sha256").update(e).update("\0").update(r).digest("base64url")}e.s(["BuildDataService",0,class{agentControlService;initialized;constructor(e){this.agentControlService=e,this.initialized=!1,this.agentControlService.registerCompletionHandler(r.BUILD_DATA_DELETE_JOB_KIND,e=>this.projectDeletion(e))}async initialize(){this.initialized||(await this.pruneHistory(),this.initialized=!0)}async refresh(e){await this.initialize();let r=e?.trim()||(0,t.randomUUID)();return await this.ensureCollection(r),await this.getCollection(r)}async getCollection(e){await this.initialize();let t=await this.loadCollection(e);if(!t)return null;!t.finishedAt&&t.deadlineAt.getTime()<=Date.now()&&(await this.expireCollection(t),t=await this.loadCollection(e)??t);let r=await this.snapshot(t);if("COMPLETED"===r.status&&!t.finishedAt){let t=new Date,a=await (0,i.getPrismaClient)();await a.buildDataCollection.updateMany({where:{id:e,finishedAt:null},data:{finishedAt:t}}),r.finishedAt=t.toISOString()}return r}async *subscribe(e){await this.initialize();let t=n.agentEventBus.iterate((0,n.buildDataCollectionChangedTopic)(e));try{let r=await this.getCollection(e);for(r&&(yield r);;){if((await t.next()).done)return;let r=await this.getCollection(e);r&&(yield r)}}finally{await t.return?.()}}async calculateSizes(e,t,i){let a=await this.requireCollection(e);return await this.createTargetJobs(a,t,i,r.BUILD_DATA_SIZE_JOB_KIND),await this.getCollection(e)}async deleteEntries(e,t,i,a=!1){let n=await this.requireCollection(e);return await this.createTargetJobs(n,t,i,r.BUILD_DATA_DELETE_JOB_KIND,a),await this.getCollection(e)}async history(e=100,t){await this.initialize(),await this.pruneHistory();let r=Math.max(1,Math.min(e,200)),a=await (0,i.getPrismaClient)(),n=t?await a.buildDataDeletionHistory.findUnique({where:{id:t},select:{id:!0,deletedAt:!0}}):null,s=await a.buildDataDeletionHistory.findMany({where:n?{OR:[{deletedAt:{lt:n.deletedAt}},{deletedAt:n.deletedAt,id:{lt:n.id}}]}:void 0,orderBy:[{deletedAt:"desc"},{id:"desc"}],take:r+1}),o=s.length>r,l=s.slice(0,r);return{items:l,nextCursor:o?l.at(-1)?.id??null:null}}async clearHistory(){await this.initialize();let e=await (0,i.getPrismaClient)();return(await e.buildDataDeletionHistory.deleteMany()).count}async ensureCollection(e){let t=await (0,i.getPrismaClient)(),a=await t.buildDataCollection.findUnique({where:{id:e},select:{id:!0}});if(!a){let i=await this.agentControlService.listAgents();try{a=await t.buildDataCollection.create({data:{id:e,deadlineAt:new Date(Date.now()+6e4),agents:{create:i.map(e=>({agentId:e.id,initialStatus:c(e)?d(e).includes(r.BUILD_DATA_SCAN_JOB_KIND)?"QUEUING":"UNSUPPORTED":"OFFLINE"}))}},select:{id:!0}}),this.publish(e)}catch(r){if(!(a=await t.buildDataCollection.findUnique({where:{id:e},select:{id:!0}})))throw r}}await this.ensureScanJobs(e)}async ensureScanJobs(e){let t=await (0,i.getPrismaClient)(),a=await t.buildDataCollection.findUnique({where:{id:e},select:{deadlineAt:!0,finishedAt:!0}});if(!a||a.finishedAt||a.deadlineAt<=new Date)return;let n=await t.buildDataCollectionAgent.findMany({where:{collectionId:e,initialStatus:"QUEUING"},include:{agent:!0}}),s=new Set((await t.agentJob.findMany({where:{buildDataCollectionId:e,kind:r.BUILD_DATA_SCAN_JOB_KIND},select:{agentId:!0}})).map(e=>e.agentId));for(let i of n)if(!s.has(i.agentId))try{let a=await t.worktree.findMany({where:{missingAt:null,codebase:{agentId:i.agentId}},select:{id:!0,folder:!0}});await this.agentControlService.createJob({agentId:i.agentId,kind:r.BUILD_DATA_SCAN_JOB_KIND,payload:{mode:i.agent.derivedDataLocationMode,path:i.agent.derivedDataPath,worktrees:a},idempotencyKey:`build-data:scan:${e}`,timeoutSeconds:45,buildDataCollectionId:e,visibility:"SYSTEM"})}catch(r){await t.buildDataCollectionAgent.update({where:{collectionId_agentId:{collectionId:e,agentId:i.agentId}},data:{initialStatus:"FAILED",error:r instanceof Error?r.message:String(r)}}),this.publish(e)}}async createTargetJobs(e,t,a,n,s=!1){let o=[...new Set(t)];if(!o.length)throw Error("Select at least one Derived Data entry");let l=new Map(e.entries.map(e=>[e.id,e])),u=o.map(e=>{let t=l.get(e);if(!t)throw Error("A selected Derived Data entry is no longer available");return t});if(n===r.BUILD_DATA_DELETE_JOB_KIND&&!s){let e=u.filter(e=>e.locked||e.activeResources.length>0);if(e.length)throw Error(`Explicit override confirmation is required to delete protected Derived Data: ${e.map(e=>e.name).join(", ")}`)}let h=new Map;for(let e of u){let t=h.get(e.agent.id)??[];t.push(e),h.set(e.agent.id,t)}let p=await (0,i.getPrismaClient)(),m=[];for(let[e,t]of h){let r=t[0].agent,i=await p.agent.findUnique({where:{id:e}});if(!i||!c(i))throw Error(`${r.name} is offline; reconnect it before running this operation`);if(!d(i).includes(n))throw Error(`${r.name} must be updated before this operation can run`);m.push({agentId:e,entries:t})}for(let{agentId:t,entries:i}of m){let s=n===r.BUILD_DATA_DELETE_JOB_KIND?[...new Map(i.filter(e=>!!e.worktreeId).map(e=>[e.worktreeId,e])).values()]:[],o=[];try{for(let e of s)await p.derivedDataCleanupLease.create({data:{worktreeId:e.worktreeId,agentId:t,path:e.path,source:"USER",expiresAt:new Date(Date.now()+6048e5)}}),o.push(e.worktreeId);let r=await this.agentControlService.createJob({agentId:t,kind:n,payload:{targets:i.map(({path:e,rootPath:t})=>({path:e,rootPath:t}))},idempotencyKey:`${n}:${e.id}:${a}:${t}`,timeoutSeconds:604800,buildDataCollectionId:e.id,visibility:"SYSTEM"});s.length&&await p.derivedDataCleanupLease.updateMany({where:{worktreeId:{in:s.map(e=>e.worktreeId)},jobId:null},data:{jobId:r.id}})}catch(e){throw o.length&&await p.derivedDataCleanupLease.deleteMany({where:{worktreeId:{in:o},source:"USER",jobId:null}}),e}}}async requireCollection(e){let t=await this.getCollection(e);if(!t)throw Error("Derived Data collection not found");if("COMPLETED"!==t.status)throw Error("Wait for the Derived Data scan to finish");return t}async loadCollection(e){return(await (0,i.getPrismaClient)()).buildDataCollection.findUnique({where:{id:e},include:u})}progress(e){let t=new Map(e.jobs.filter(e=>e.kind===r.BUILD_DATA_SCAN_JOB_KIND).map(e=>[e.agentId,e])),i=e.agents.map(e=>{let i=t.get(e.agentId),a=e.initialStatus,n=e.error,s=[];if("QUEUING"===e.initialStatus&&i&&(a=i.status,n=i.error,"SUCCEEDED"===i.status))try{s=(0,r.parseBuildDataScanResult)(h(i.resultJson)).warnings}catch(e){a="INVALID",n=e instanceof Error?e.message:String(e)}return{agent:e.agent,status:a,jobId:i?.id??null,error:n,warnings:s}}),a=i.filter(({status:e})=>"OFFLINE"!==e&&"UNSUPPORTED"!==e),n=a.filter(({status:e})=>l.has(e));return{agents:i,eligibleCount:a.length,finishedCount:n.length,successfulCount:a.filter(({status:e})=>"SUCCEEDED"===e).length}}async snapshot(e){let t=this.progress(e),r=await this.entries(e,!1);return{id:e.id,status:t.finishedCount===t.eligibleCount?"COMPLETED":"COLLECTING",createdAt:e.createdAt.toISOString(),deadlineAt:e.deadlineAt.toISOString(),finishedAt:e.finishedAt?.toISOString()??null,progress:t,entries:r}}async entries(e,t){let a=await (0,i.getPrismaClient)(),n=new Map(e.agents.map(e=>[e.agentId,e.agent])),u=await a.worktree.findMany({where:{missingAt:null,codebase:{agentId:{in:[...n.keys()]}}},include:{codebase:{select:{agentId:!0}}}}),c=new Map;for(let e of u){let t=c.get(e.codebase.agentId)??[];t.push(e),c.set(e.codebase.agentId,t)}let d=new Map;for(let t of e.jobs){let e;if(t.kind!==r.BUILD_DATA_SCAN_JOB_KIND||"SUCCEEDED"!==t.status)continue;let i=n.get(t.agentId);if(i){try{e=(0,r.parseBuildDataScanResult)(h(t.resultJson))}catch{continue}for(let r of e.entries){let e=(r.workspacePath?(c.get(t.agentId)??[]).filter(e=>(function(e,t){let r="/"===e?e:e.replace(/\/+$/,"");return t===r||t.startsWith(`${r}/`)})(e.folder,r.workspacePath)).sort((e,t)=>t.folder.length-e.folder.length):[])[0]??null,a=g(t.agentId,r.path);d.set(a,{id:a,name:r.name,kind:r.kind,status:"DEVICE_SUPPORT"===r.kind?"READY":"PENDING"===r.kind?"PENDING":"SHARED_CACHE"===r.kind?"SHARED_CACHE":e?"READY":"UNLINKED",workspacePath:r.workspacePath,worktreeId:e?.id??null,worktreePath:e?(0,s.worktreeDisplayPath)(e.folder,i.baseRepoDirectory):null,sizeBytes:null,operation:"IDLE",error:null,agent:i,path:r.path,rootPath:r.rootPath,modifiedAt:r.modifiedAt,volumeId:r.volumeId,locked:!1,activeResources:[]})}}}for(let i of e.jobs){if(i.kind===r.BUILD_DATA_SIZE_JOB_KIND&&"SUCCEEDED"===i.status)try{for(let e of(0,r.parseBuildDataSizeResult)(h(i.resultJson)).sizes){let t=d.get(g(i.agentId,e.path));t&&(t.sizeBytes=e.sizeBytes,t.error=e.error)}}catch(e){f(d,i,m(r.BUILD_DATA_SIZE_JOB_KIND,e))}if(i.kind===r.BUILD_DATA_DELETE_JOB_KIND&&"SUCCEEDED"===i.status)try{for(let e of(0,r.parseBuildDataDeleteResult)(h(i.resultJson)).deleted){let r=g(i.agentId,e.path),a=d.get(r);a&&(e.deleted&&!t?d.delete(r):a.error=e.error)}}catch(e){f(d,i,m(r.BUILD_DATA_DELETE_JOB_KIND,e))}if("QUEUED"===i.status||"RUNNING"===i.status){if(i.kind!==r.BUILD_DATA_SIZE_JOB_KIND&&i.kind!==r.BUILD_DATA_DELETE_JOB_KIND)continue;try{for(let e of p(i)){let t=d.get(g(i.agentId,e));t&&(t.operation=i.kind===r.BUILD_DATA_DELETE_JOB_KIND?"DELETING":"SIZING")}}catch{}}if("SUCCEEDED"!==i.status&&l.has(i.status)&&(i.kind===r.BUILD_DATA_SIZE_JOB_KIND||i.kind===r.BUILD_DATA_DELETE_JOB_KIND))try{for(let e of p(i)){let t=d.get(g(i.agentId,e));t&&(t.error=i.error||"Build Data operation failed")}}catch{}}let y=[...d.values()],w=y.map(e=>e.worktreeId).filter(e=>!!e),[b,E]=await Promise.all([a.derivedDataLock.findMany({where:{OR:y.map(e=>({agentId:e.agent.id,path:e.path}))},select:{agentId:!0,path:!0}}),(0,o.executingResourcesByWorktree)(w)]),S=new Set(b.map(e=>`${e.agentId}\0${e.path}`));for(let e of y)e.locked=S.has(`${e.agent.id}\0${e.path}`),e.activeResources=e.worktreeId?E.get(e.worktreeId)??[]:[];return y.sort((e,t)=>e.agent.name.localeCompare(t.agent.name)||(null===e.modifiedAt?1:null===t.modifiedAt?-1:new Date(e.modifiedAt).getTime()-new Date(t.modifiedAt).getTime())||e.name.localeCompare(t.name))}async setEntryLocked(e,r,a){let n=(await this.requireCollection(e)).entries.find(e=>e.id===r);if(!n)throw Error("Derived Data entry not found");let s=await (0,i.getPrismaClient)();return a?await s.derivedDataLock.upsert({where:{agentId_path:{agentId:n.agent.id,path:n.path}},create:{id:(0,t.randomUUID)(),agentId:n.agent.id,path:n.path},update:{}}):await s.derivedDataLock.deleteMany({where:{agentId:n.agent.id,path:n.path}}),this.publish(e),await this.getCollection(e)}async expireCollection(e){let t=await (0,i.getPrismaClient)(),a=new Set(e.jobs.filter(e=>e.kind===r.BUILD_DATA_SCAN_JOB_KIND).map(e=>e.agentId));await t.buildDataCollectionAgent.updateMany({where:{collectionId:e.id,initialStatus:"QUEUING",agentId:{notIn:[...a]}},data:{initialStatus:"TIMED_OUT"}}),await this.agentControlService.timeoutBuildDataCollectionJobs(e.id),this.publish(e.id)}async projectDeletion(e){let a;if("SUCCEEDED"!==e.status||!e.resultJson)return;await this.pruneHistory();let n=await (0,i.getPrismaClient)();if(await n.buildDataDeleteProjection.findUnique({where:{jobId:e.id}}))return;try{a=(0,r.parseBuildDataDeleteResult)(h(e.resultJson)).deleted.filter(e=>e.deleted)}catch(i){let t=m(r.BUILD_DATA_DELETE_JOB_KIND,i);try{await n.buildDataDeleteProjection.create({data:{jobId:e.id,error:t}})}catch(t){if(!await n.buildDataDeleteProjection.findUnique({where:{jobId:e.id}}))throw t}return}if(!a.length)return void await n.buildDataDeleteProjection.create({data:{jobId:e.id}});let s=(0,r.buildDataDeletePayload)(h(e.payloadJson)),o=e.buildDataCollectionId?await this.loadCollection(e.buildDataCollectionId):null,l=new Map((o?await this.entries(o,!0):[]).filter(t=>t.agent.id===e.agentId).map(e=>[e.path,e])),u=new Map(s.targets.map(e=>[e.path,e])),c=await n.agent.findUnique({where:{id:e.agentId}});if(c)try{await n.$transaction(async r=>{if(!await r.buildDataDeleteProjection.findUnique({where:{jobId:e.id}}))for(let i of(await r.buildDataDeleteProjection.create({data:{jobId:e.id}}),a)){let a=l.get(i.path),n=u.get(i.path),o=n?.worktreeId??a?.worktreeId??null,d=o?(await r.worktree.findUnique({where:{id:o},select:{id:!0}}))?.id??null:null;await r.buildDataDeletionHistory.create({data:{id:(0,t.randomUUID)(),agentId:e.agentId,agentName:c.name,folderName:n?.name??a?.name??i.path,worktreeId:d,worktreePath:n?.worktreePath??a?.worktreePath??null,source:s.source,entryKind:n?.kind??a?.kind??"PROJECT",jobId:e.id,targetKey:a?.id??g(e.agentId,i.path)}})}})}catch(t){if(!await n.buildDataDeleteProjection.findUnique({where:{jobId:e.id}}))throw t}}async pruneHistory(){let e=await (0,i.getPrismaClient)();await e.buildDataDeletionHistory.deleteMany({where:{deletedAt:{lt:new Date(Date.now()-7776e6)}}})}publish(e){n.agentEventBus.publish(n.BUILD_DATA_CHANGED_TOPIC,{buildDataCollectionChanged:{id:e}}),n.agentEventBus.publish((0,n.buildDataCollectionChangedTopic)(e),{buildDataCollectionChanged:{id:e}})}}])},396763,e=>{"use strict";e.i(925991),e.s([])},163853,e=>e.a(async(t,r)=>{try{e.s(["cacheTransferredArtifact",()=>g,"cachedArtifact",()=>f,"materializeArtifact",()=>b]);var i=e.i(666680),a=e.i(912714),n=e.i(660526),s=e.i(750227),o=e.i(243783),l=e.i(503675),u=e.i(887394),c=t([u]);[u]=c.then?(await c)():c;let E=process.env.ARTIFACT_CACHE_DIRECTORY?.trim()||(0,s.join)((0,n.tmpdir)(),"ade-build-artifact-cache"),S=Number(process.env.ARTIFACT_CACHE_MAX_BYTES)||0x140000000,v=globalThis,I=v.buildArtifactMaterializations??(v.buildArtifactMaterializations=new Map);async function d(e,t){try{await (0,a.rename)(e,t);return}catch(e){if("EXDEV"!==e.code)throw e}let r=`${t}.${(0,i.randomUUID)()}.incoming`;try{await (0,a.copyFile)(e,r),await (0,a.rename)(r,t),await (0,a.rm)(e,{force:!0})}finally{await (0,a.rm)(r,{force:!0}).catch(()=>{})}}async function h(e){try{let t=JSON.parse(await (0,a.readFile)(e,"utf8"));if(!t||"object"!=typeof t)return null;let{filename:r,contentType:i,size:n}=t;if("string"!=typeof r||"string"!=typeof i||"number"!=typeof n)return null;return{filename:r,contentType:i,size:n}}catch{return null}}async function p(e){let t=(0,s.join)(E,e),r=await h(`${t}.json`);if(!r)return null;try{let i=await (0,a.stat)(t);if(!i.isFile()||i.size!==r.size)return null;let n=new Date;return await (0,a.utimes)(t,n,n).catch(()=>{}),{path:t,etag:`"${e}"`,...r}}catch{return null}}async function m(e,t){var r;let a=(0,u.getServerServices)(),n=await a.buildsService.artifactForInstall(e,t);if(!n)throw Error("Build artifact not found");return{artifact:n,key:(r=n.checksum??n.createdAt,(0,i.createHash)("sha1").update(`${t}:${r}`).digest("hex"))}}async function f(e,t){let{key:r}=await m(e,t);return p(r)}async function g(e){let{key:t}=await m(e.buildId,e.artifactId);await (0,a.mkdir)(E,{recursive:!0,mode:448});let r=(0,s.join)(E,t);await d(e.path,r);let i=(await (0,a.stat)(r)).size,n={filename:e.filename,contentType:e.contentType,size:i};return await (0,a.writeFile)(`${r}.json`,JSON.stringify(n),{mode:384}),await y(t).catch(()=>{}),{path:r,etag:`"${t}"`,...n}}async function y(e){let t,r=new Set;try{let e=await (0,o.getPrismaClient)();for(let t of(await e.buildArtifactTransfer.findMany({where:{status:{in:["READY","DOWNLOADING"]},expiresAt:{gt:new Date},stagingPath:{not:null}},select:{stagingPath:!0}})))t.stagingPath&&r.add(t.stagingPath)}catch{}try{t=await (0,a.readdir)(E)}catch{return}let i=[],n=Date.now()-216e5;for(let o of t){if(o.endsWith(".json"))continue;let t=(0,s.join)(E,o);try{let s=await (0,a.stat)(t);if(!s.isFile())continue;if(o.endsWith(".incoming")){s.mtimeMs<n&&await (0,a.rm)(t,{force:!0}).catch(()=>{});continue}i.push({path:t,size:s.size,mtimeMs:s.mtimeMs,keep:o===e||r.has(t)})}catch{continue}}i.sort((e,t)=>e.mtimeMs-t.mtimeMs);let l=i.reduce((e,t)=>e+t.size,0);for(let e of i)!e.keep&&(l<=S&&e.mtimeMs>=n||(await (0,a.rm)(e.path,{force:!0}).catch(()=>{}),await (0,a.rm)(`${e.path}.json`,{force:!0}).catch(()=>{}),l-=e.size))}async function w(e,t,r,n){let o=(0,i.randomUUID)(),c=(0,u.getServerServices)(),h=await c.buildsService.getBuild(e);if(!h?.agentId)throw Error("Build agent is unavailable");let p=Math.min(18e5,12e4+(n??0)/1e3),m=null;try{let[i]=await Promise.all([(0,l.expectArtifactTransfer)(o,h.agentId,p),c.buildsService.prepareArtifactDownload(e,t,o,p)]);m=i.path,await (0,a.mkdir)(E,{recursive:!0,mode:448});let n=(0,s.join)(E,r);await d(i.path,n),m=null;let u=(await (0,a.stat)(n)).size,f={filename:i.filename,contentType:i.contentType,size:u};return await (0,a.writeFile)(`${n}.json`,JSON.stringify(f),{mode:384}),await y(r).catch(()=>{}),{path:n,etag:`"${r}"`,...f}}catch(e){throw(0,l.cancelArtifactTransfer)(o,e),m&&await (0,a.rm)(m,{force:!0}).catch(()=>{}),e}}async function b(e,t){let{artifact:r,key:i}=await m(e,t),a=await p(i);if(a)return a;let n=I.get(i);if(n)return n;let s=w(e,t,i,r.sizeBytes).finally(()=>{I.delete(i)});return I.set(i,s),s}r()}catch(e){r(e)}},!1),933416,e=>e.a(async(t,r)=>{try{e.s(["ARTIFACT_TRANSFER_CHUNK_BYTES",()=>I,"appendBuildArtifactTransferChunk",()=>w,"buildArtifactFileChecksum",()=>b,"buildArtifactTransferStatus",()=>g,"completeBuildArtifactTransferUpload",()=>E,"failBuildArtifactTransferForJob",()=>v,"initializeBuildArtifactTransfer",()=>y,"readBuildArtifactTransferRange",()=>S]);var i=e.i(666680),a=e.i(902157),n=e.i(912714),s=e.i(660526),o=e.i(750227),l=e.i(243783);e.i(805422);var u=e.i(661983),c=e.i(163853),d=t([c]);[c]=d.then?(await d)():d;let I=0x1000000,A=Number(process.env.ARTIFACT_TRANSFER_MAX_BYTES)||0x500000000,k=process.env.ARTIFACT_TRANSFER_DIRECTORY?.trim()||(0,o.join)((0,s.tmpdir)(),"ade-build-artifact-transfers"),_=globalThis,T=_.buildArtifactTransferLocks??(_.buildArtifactTransferLocks=new Map);async function h(e,t,r){let i=0;for(;i<t.byteLength;){let a=t.byteLength-i,{bytesWritten:n}=await e.write(t,i,a,r+i);if(!Number.isSafeInteger(n)||n<=0||n>a)throw Error("Artifact transfer file write made no progress");i+=n}}async function p(e,t){let r;for(;T.has(e);)await T.get(e);let i=new Promise(e=>{r=e});T.set(e,i);try{return await t()}finally{T.get(e)===i&&T.delete(e),r()}}function m(e){u.agentEventBus.publish((0,u.buildTopic)(e),{buildChanged:{id:e}}),u.agentEventBus.publish(u.BUILDS_CHANGED_TOPIC,{buildsChanged:{id:e}})}async function f(e,t,r){let i=await (0,l.getPrismaClient)(),a=await i.buildArtifactTransfer.findUnique({where:{id:e},include:{artifact:{include:{build:!0}}}});if(!a)throw Error("Artifact transfer not found");if(!("source"===r?a.sourceAgentId===t:"target"===r?a.targetAgentId===t:a.sourceAgentId===t||a.targetAgentId===t))throw Error("Artifact transfer belongs to another agent");return a.expiresAt.getTime()<=Date.now()&&!["SUCCEEDED","FAILED","CANCELLED","EXPIRED"].includes(a.status)&&(a=await i.buildArtifactTransfer.update({where:{id:a.id},data:{status:"EXPIRED",error:"Artifact transfer expired",finishedAt:new Date},include:{artifact:{include:{build:!0}}}}),m(a.artifact.buildId)),a}async function g(e,t){return f(e,t,"either")}async function y(e,t,r){return p(e,async()=>{let i=await f(e,t,"source");if(!["QUEUED","UPLOADING"].includes(i.status))throw Error("Artifact transfer is not accepting uploads");if(!Number.isSafeInteger(r.uploadLength)||r.uploadLength<=0||r.uploadLength>A)throw Error("Artifact upload length is invalid");let a=r.checksum.trim().toLowerCase();if(!/^[a-f0-9]{64}$/.test(a))throw Error("Artifact checksum must be SHA-256");let s=function(e){let t=e.trim();if(!t||t.length>255||(0,o.basename)(t)!==t||t.includes("\0"))throw Error("Artifact filename is invalid");return t}(r.filename),u=r.contentType.trim()||"application/octet-stream";if(null!==i.uploadLength&&(i.uploadLength!==r.uploadLength||i.checksum!==a||i.filename!==s))throw Error("Artifact upload metadata does not match the transfer");await (0,n.mkdir)(k,{recursive:!0,mode:448});let c=(0,o.join)(k,`${i.id}.upload`),d=0;try{d=(await (0,n.stat)(c)).size}catch{}d>r.uploadLength&&(await (0,n.rm)(c,{force:!0}),d=0);let h=await (0,n.statfs)(k);if(Number(h.bavail)*Number(h.bsize)<r.uploadLength-d+0x4000000)throw Error("The artifact relay does not have enough free disk space");let p=await (0,l.getPrismaClient)(),g=await p.buildArtifactTransfer.update({where:{id:i.id},data:{status:"UPLOADING",uploadLength:r.uploadLength,uploadOffset:d,checksum:a,filename:s,contentType:u,stagingPath:c,error:null},include:{artifact:{include:{build:!0}}}});return m(g.artifact.buildId),g})}async function w(e,t,r,i){return p(e,async()=>{let a=await f(e,t,"source");if("UPLOADING"!==a.status||null===a.uploadLength||!a.stagingPath)throw Error("Artifact transfer upload has not been initialized");if(!Number.isSafeInteger(r)||r!==a.uploadOffset)throw Error(`Upload offset mismatch; expected ${a.uploadOffset}`);if(!i.byteLength||i.byteLength>I)throw Error("Artifact upload chunks must be 1 to 16 MiB");if(r+i.byteLength>a.uploadLength)throw Error("Artifact upload exceeds its declared length");let s=await (0,n.open)(a.stagingPath,0===r?"w":"r+");try{await h(s,i,r),await s.sync()}finally{await s.close()}let o=await (0,l.getPrismaClient)(),u=await o.buildArtifactTransfer.update({where:{id:a.id},data:{uploadOffset:r+i.byteLength},include:{artifact:{include:{build:!0}}}});return m(u.artifact.buildId),u})}async function b(e){let t=(0,i.createHash)("sha256");for await(let r of(0,a.createReadStream)(e))t.update(r);return t.digest("hex")}async function E(e,t){return p(e,async()=>{let r=await f(e,t,"source");if("UPLOADING"!==r.status||null===r.uploadLength||r.uploadOffset!==r.uploadLength||!r.stagingPath||!r.checksum||!r.filename||!r.contentType)throw Error("Artifact upload is incomplete");let i=await b(r.stagingPath),a=await (0,l.getPrismaClient)();if(i!==r.checksum){await (0,n.rm)(r.stagingPath,{force:!0});let e=await a.buildArtifactTransfer.update({where:{id:r.id},data:{status:"FAILED",error:"Artifact checksum did not match",stagingPath:null,finishedAt:new Date},include:{artifact:{include:{build:!0}}}});throw m(e.artifact.buildId),Error("Artifact checksum did not match")}let s=await (0,c.cacheTransferredArtifact)({buildId:r.artifact.buildId,artifactId:r.artifactId,path:r.stagingPath,filename:r.filename,contentType:r.contentType}),o=await a.buildArtifactTransfer.update({where:{id:r.id},data:{status:"READY",stagingPath:s.path,uploadOffset:s.size,uploadLength:s.size,error:null},include:{artifact:{include:{build:!0}}}});return m(o.artifact.buildId),o})}async function S(e,t,r,i){let a=await f(e,t,"target");if(!["READY","DOWNLOADING","SUCCEEDED"].includes(a.status)||!a.stagingPath||null===a.uploadLength)throw Error("Artifact transfer is not ready to download");if(!Number.isSafeInteger(r)||!Number.isSafeInteger(i)||r<0||i<r||i>=a.uploadLength||i-r+1>I)throw Error("Artifact download range is invalid");let s=Buffer.allocUnsafe(i-r+1),o=await (0,n.open)(a.stagingPath,"r");try{if((await o.read(s,0,s.length,r)).bytesRead!==s.length)throw Error("Artifact download ended unexpectedly")}finally{await o.close()}let u=await (0,l.getPrismaClient)();return await u.buildArtifactTransfer.update({where:{id:a.id},data:{status:"SUCCEEDED"===a.status?"SUCCEEDED":"DOWNLOADING",downloadOffset:Math.max(a.downloadOffset,i+1)}}),m(a.artifact.buildId),{bytes:s,start:r,end:i,size:a.uploadLength,checksum:a.checksum,filename:a.filename??"artifact.tar.gz",contentType:a.contentType??"application/octet-stream"}}async function v(e,t){let r=await (0,l.getPrismaClient)(),i=await r.buildArtifactTransfer.findFirst({where:{OR:[{sourceJobId:e},{targetJobId:e}]},include:{artifact:!0}});!i||["SUCCEEDED","FAILED"].includes(i.status)||(await r.$transaction([r.buildArtifactTransfer.update({where:{id:i.id},data:{status:"FAILED",error:t,finishedAt:new Date}}),r.buildDeployment.updateMany({where:{transferId:i.id,status:{in:["QUEUED","TRANSFERRING"]}},data:{status:"FAILED",error:t,finishedAt:new Date}})]),m(i.artifact.buildId))}r()}catch(e){r(e)}},!1),503675,e=>{"use strict";var t=e.i(902157),r=e.i(912714),i=e.i(660526),a=e.i(750227),n=e.i(81111),s=e.i(188646);let o=globalThis,l=o.buildArtifactTransfers??(o.buildArtifactTransfers=new Map);function u(e,t){let r=l.get(e);r&&(l.delete(e),clearTimeout(r.timeout),r.reject(t instanceof Error?t:Error(String(t))))}async function c(e,o,c){let d=l.get(e);if(!d||d.agentId!==o)throw Error("Artifact upload is not expected");if(!c.body)throw Error("Artifact upload body is required");let h=(0,a.join)((0,i.tmpdir)(),`ade-build-artifact-upload-${e}`);try{await (0,s.pipeline)(n.Readable.fromWeb(c.body),(0,t.createWriteStream)(h,{mode:384}));let r=c.headers.get("x-artifact-filename")??"artifact",i="artifact";try{i=decodeURIComponent(r)}catch{}l.delete(e),clearTimeout(d.timeout);let a=c.headers.get("content-length");d.resolve({path:h,filename:i,contentType:c.headers.get("content-type")??"application/octet-stream",size:null!==a&&Number.isFinite(Number(a))?Number(a):null})}catch(t){throw await (0,r.rm)(h,{force:!0}),u(e,t),t}}e.s(["cancelArtifactTransfer",0,u,"expectArtifactTransfer",0,function(e,t,r=17e4){return new Promise((i,a)=>{let n=setTimeout(()=>{l.delete(e),a(Error("The agent did not upload the artifact in time"))},r);n.unref(),l.set(e,{agentId:t,resolve:i,reject:a,timeout:n})})},"receiveArtifactTransfer",0,c])},971619,e=>{"use strict";var t=e.i(750227);e.s(["effectiveBuildsDirectory",0,function(e){var r;return e.buildsDirectory??((r=e.baseRepoDirectory)?/^[a-z]:[\\/]/i.test(r)||r.startsWith("\\\\")?t.win32.join(r,"Builds"):t.posix.join(r,"Builds"):null)}])},984179,e=>{"use strict";let t=new Set(["QUEUED","PREPARING","RUNNING"]);e.s(["buildOutOfDate",0,function(e){let r;if(t.has(e.status)||!e.worktree||(e.worktree._count?.builds??0)>0||e.finishedAt&&(!e.worktree.lastCheckedAt||e.worktree.lastCheckedAt<e.finishedAt))return!1;try{r=JSON.parse(e.snapshotJson)}catch{return!1}if(!r||"object"!=typeof r||Array.isArray(r))return!1;let i=r.worktree;if(!i||"object"!=typeof i||Array.isArray(i))return!1;if("string"==typeof i.codeStateHash&&e.worktree.codeStateHash)return i.codeStateHash!==e.worktree.codeStateHash;if("string"==typeof i.headSha&&e.worktree.headSha!==i.headSha)return!0;if("boolean"==typeof i.hasStagedChanges){if(i.hasStagedChanges!==e.worktree.hasStagedChanges)return!0}else if(e.worktree.hasStagedChanges)return!0;return"boolean"==typeof i.hasUnstagedChanges?i.hasUnstagedChanges!==e.worktree.hasUnstagedChanges:e.worktree.hasUnstagedChanges}])},190714,e=>{"use strict";var t=e.i(907855);let r=t.object({status:t.string().optional(),codebaseId:t.string().optional(),worktreeId:t.string().optional(),first:t.number().int().min(1).max(200).default(50),after:t.string().optional()}),i=t.object({builds:t.array(t.unknown()),nextCursor:t.string().nullable()}),a=t.object({buildId:t.string().min(1),afterLogId:t.string().min(1).nullable().default(null),logLimit:t.number().int().min(1).max(5e3).default(1e3)}),n=t.object({build:t.unknown(),logs:t.array(t.unknown())}),s=t.object({worktreeId:t.string().min(1)}),o=t.object({project:t.unknown().nullable()}),l=t.union([t.object({buildId:t.string().min(1),requestId:t.string().min(1)}),t.object({worktreeId:t.string().min(1),configurationId:t.string().min(1),action:t.string().optional(),requestId:t.string().min(1)})]),u=t.object({destinations:t.array(t.unknown())}),c=t.object({worktreeId:t.string().min(1),configurationId:t.string().min(1),destination:t.record(t.string(),t.unknown()),scriptIds:t.array(t.string()).default([]),action:t.string().optional(),advancedSettings:t.record(t.string(),t.unknown()).optional(),requestId:t.string().min(1)}),d=t.object({build:t.unknown()}),h=t.object({worktreeId:t.string().min(1),reportPath:t.string().min(1).max(4e3),format:t.enum(["AUTO","LCOV","ISTANBUL"]).default("AUTO"),requestId:t.string().min(1)}),p=t.object({build:t.unknown()}),m=t.object({buildId:t.string().min(1),requestId:t.string().min(1)}),f=t.object({build:t.unknown()}),g=t.object({buildId:t.string().min(1),destinations:t.array(t.record(t.string(),t.unknown())).min(1),requestId:t.string().min(1)}),y=t.object({deployments:t.array(t.unknown())}),w=t.object({buildId:t.string().min(1),settings:t.record(t.string(),t.unknown()),requestId:t.string().min(1)}),b=t.object({export:t.unknown()});e.s(["CancelBuildToolInputSchema",0,m,"CancelBuildToolOutputSchema",0,f,"ExportBuildToolInputSchema",0,w,"ExportBuildToolOutputSchema",0,b,"GetBuildConfigurationsInputSchema",0,s,"GetBuildConfigurationsOutputSchema",0,o,"GetBuildDestinationsInputSchema",0,l,"GetBuildDestinationsOutputSchema",0,u,"GetBuildInputSchema",0,a,"GetBuildOutputSchema",0,n,"GetBuildsInputSchema",0,r,"GetBuildsOutputSchema",0,i,"ImportCoverageReportToolInputSchema",0,h,"ImportCoverageReportToolOutputSchema",0,p,"RunBuildToolInputSchema",0,g,"RunBuildToolOutputSchema",0,y,"StartBuildToolInputSchema",0,c,"StartBuildToolOutputSchema",0,d])},669602,e=>e.a(async(t,r)=>{try{e.s(["BuildsService",()=>C]);var i=e.i(666680),a=e.i(750227),n=e.i(807055),s=e.i(503083),o=e.i(243783);e.i(805422);var l=e.i(694355),u=e.i(661983),c=e.i(971619),d=e.i(163853),h=e.i(933416),p=t([d,h]);[d,h]=p.then?(await p)():p;let A=new Set(n.BUILD_CONFIGURATION_ICON_KEYS),k=new Set(["SUCCEEDED","FAILED","CANCELLED","TIMED_OUT"]),_=["QUEUED","PREPARING","RUNNING"];function m(e,t=null){if(null===e)return t;try{return JSON.parse(e)}catch{return t}}function f(e,t){if(!e||"object"!=typeof e||Array.isArray(e))throw Error(`${t} must be an object`);return e}function g(e){return Array.isArray(e)?e.filter(e=>"string"==typeof e):[]}function y(e){return null!==e.lastSeenAt&&Date.now()-e.lastSeenAt.getTime()<=(0,l.agentOnlineWindowMs)(e)&&null===e.disconnectedAt}function w(e){return g(m(e.capabilitiesJson,[]))}function b(e,t,r=80){let i=e.trim();if(!i)throw Error(`${t} is required`);if(i.length>r)throw Error(`${t} is too long`);return i}function E(e){return e.split(".").map(e=>Number.parseInt(e,10)||0)}function S(e,t){let r="string"==typeof t.minimumOSVersion?t.minimumOSVersion:null;if("SIMULATOR"!==e.type||!r||!e.osVersion)return e;let i=E(e.osVersion),a=E(r),n=Math.max(i.length,a.length);for(let t=0;t<n&&!((i[t]??0)>(a[t]??0));t+=1)if((i[t]??0)<(a[t]??0))return{...e,available:!1};return e}function v(e){if(e.codebaseId)return e.codebaseId;let t=m(e.snapshotJson,{});if(t&&"object"==typeof t&&!Array.isArray(t)){let e=t.codebase;if(e&&"object"==typeof e&&!Array.isArray(e)){let t=e.id;if("string"==typeof t&&t.trim())return t}}throw Error("Build coordination metadata is unavailable")}function I(e){return"SUCCEEDED"===e?"SUCCEEDED":"CANCELLED"===e?"CANCELLED":"FAILED"}let T={agent:!0,codebase:{include:{repository:!0}},worktree:{include:{_count:{select:{builds:{where:{status:{in:_}}}}}}},configuration:{include:{source:!0,project:!0}},artifacts:{orderBy:{createdAt:"asc"}},scriptExecutions:{orderBy:[{phase:"asc"},{position:"asc"}]},deployments:{orderBy:{createdAt:"desc"},include:{targetAgent:!0,transfer:{include:{sourceAgent:!0,targetAgent:!0}}}},exports:{orderBy:{createdAt:"desc"}}};class C{agentControl;telemetry;notifications;diskSpace;constructor(e,t,r,i){this.agentControl=e,this.telemetry=t,this.notifications=r,this.diskSpace=i,this.agentControl.registerCompletionHandler(n.IOS_BUILD_JOB_KIND,e=>this.projectBuildCompletion(e)),this.agentControl.registerCompletionHandler(n.IOS_DEPLOY_JOB_KIND,e=>this.projectDeploymentCompletion(e)),this.agentControl.registerCompletionHandler(n.IOS_REMOTE_DEPLOY_JOB_KIND,e=>this.projectDeploymentCompletion(e)),this.agentControl.registerCompletionHandler(n.IOS_ARTIFACT_TRANSFER_UPLOAD_JOB_KIND,async e=>{"SUCCEEDED"!==e.status&&await (0,h.failBuildArtifactTransferForJob)(e.id,e.error||"The build agent could not upload the runnable app")}),this.agentControl.registerCompletionHandler(n.IOS_EXPORT_JOB_KIND,e=>this.projectExportCompletion(e)),this.agentControl.registerCompletionHandler(n.IOS_TEST_RESULTS_JOB_KIND,e=>this.projectGeneratedReportCompletion(e)),this.agentControl.registerCompletionHandler(n.IOS_COVERAGE_REPORT_JOB_KIND,e=>this.projectGeneratedReportCompletion(e)),this.agentControl.registerCompletionHandler(s.COVERAGE_IMPORT_JOB_KIND,e=>this.importedCoverageCompletion(e))}publish(e){u.agentEventBus.publish((0,u.buildTopic)(e),{buildChanged:{id:e}}),u.agentEventBus.publish(u.BUILDS_CHANGED_TOPIC,{buildsChanged:{id:e}}),u.agentEventBus.publish(u.SIDEBAR_STATUS_CHANGED_TOPIC,{sidebarStatusChanged:!0})}async requireWorktree(e,t,r="Agent must be updated to use iOS builds"){let i=await (0,o.getPrismaClient)(),a=await i.worktree.findUnique({where:{id:e},include:{codebase:{include:{agent:!0,repository:!0}}}});if(!a||a.missingAt||"AVAILABLE"!==a.availability)throw Error("Worktree is unavailable");if(!y(a.codebase.agent))throw Error("Agent is offline");if(!w(a.codebase.agent).includes(t))throw Error(r);return a}identity(e){return{codebaseId:e.codebaseId,worktreeId:e.id,branch:e.branch,folder:e.folder,gitDirectory:e.gitDirectory,expectedOrigin:e.codebase.repository.canonicalOrigin,headSha:e.headSha,baseBranch:e.baseBranchOverride??e.codebase.defaultBranch??null}}async ensureProject(e){let t=await (0,o.getPrismaClient)(),r=await t.codebase.findUnique({where:{id:e},select:{repositoryId:!0}});if(!r)throw Error("Codebase not found");return t.codebaseProject.upsert({where:{repositoryId_type:{repositoryId:r.repositoryId,type:"IOS_APP"}},create:{id:(0,i.randomUUID)(),repositoryId:r.repositoryId,type:"IOS_APP"},update:{}})}async project(e){let t=await (0,o.getPrismaClient)(),r=await t.codebase.findUnique({where:{id:e},include:{repository:!0}});if(!r)return null;let i=await t.codebaseProject.findUnique({where:{repositoryId_type:{repositoryId:r.repositoryId,type:"IOS_APP"}},include:{configurations:{orderBy:{name:"asc"},include:{source:{include:{observations:{where:{codebaseId:e},orderBy:{lastParseAttemptAt:"desc"},take:1}}}}}}}),a=await t.codebaseRepositoryBuildScript.findMany({where:{repositoryId:r.repositoryId,script:{deletedAt:null}},orderBy:[{position:"asc"},{script:{name:"asc"}}],include:{script:!0}});return i?{...i,repository:r.repository,allowedScripts:a}:null}async createProject(e){return await this.ensureProject(e),this.project(e)}async projectForWorktree(e){let t=await (0,o.getPrismaClient)(),r=await t.worktree.findUnique({where:{id:e},select:{codebaseId:!0}});return r?this.project(r.codebaseId):null}async saveConfiguration(e){let t=await this.ensureProject(e.codebaseId),r=(0,n.parseBuildSource)({kind:e.sourceKind,relativePath:e.sourcePath}),a=b(e.name,"Configuration name"),s=b(e.scheme,"Scheme",256),l=b(e.buildConfiguration,"Xcode configuration",256);if(!n.BUILD_ACTIONS.includes(e.defaultAction))throw Error("Build action is invalid");let u=e.iconKey?.trim()||null;if(u&&!A.has(u))throw Error("Icon is invalid");let c=(0,n.parseBuildAdvancedSettings)(e.advancedSettings??n.DEFAULT_BUILD_ADVANCED_SETTINGS),d=!0===e.autoExport;if(d&&"ARCHIVE"!==e.defaultAction)throw Error("Auto Export is available only for Archive configurations");let h=e.exportSettings?(0,n.parseBuildExportSettings)(e.exportSettings):null;if(d&&!h)throw Error("Auto Export settings are required");let p=await (0,o.getPrismaClient)(),m=e.id?await p.buildConfiguration.findUnique({where:{id:e.id}}):null;if(e.id&&(!m||m.projectId!==t.id))throw Error("Build configuration not found");let f=await p.buildSource.upsert({where:{projectId_relativePath:{projectId:t.id,relativePath:r.relativePath}},create:{id:(0,i.randomUUID)(),projectId:t.id,kind:r.kind,relativePath:r.relativePath},update:{kind:r.kind}}),g=m?.id??(0,i.randomUUID)();return p.buildConfiguration.upsert({where:{id:g},create:{id:g,projectId:t.id,sourceId:f.id,name:a,iconKey:u,scheme:s,buildConfiguration:l,defaultAction:e.defaultAction,advancedSettingsJson:JSON.stringify(c),autoExport:d,exportSettingsJson:h?JSON.stringify(h):null},update:{sourceId:f.id,name:a,iconKey:u,scheme:s,buildConfiguration:l,defaultAction:e.defaultAction,advancedSettingsJson:JSON.stringify(c),autoExport:d,exportSettingsJson:h?JSON.stringify(h):null},include:{source:!0}})}async deleteConfiguration(e){let t=await (0,o.getPrismaClient)();if(await t.build.findFirst({where:{configurationId:e,status:{in:_}}}))throw Error("Configuration has an active build");let r=await t.buildConfiguration.deleteMany({where:{id:e}});return 1===r.count}async scripts(){return(await (0,o.getPrismaClient)()).buildScript.findMany({where:{deletedAt:null},orderBy:{name:"asc"}})}async saveScript(e){let t=b(e.name,"Script name"),r=e.preBuildScript?.trim()||null,a=e.postBuildScript?.trim()||null;if(!r&&!a)throw Error("A pre-build or post-build script is required");let s=e.timeoutSeconds??300;if(!Number.isInteger(s)||s<1||s>3600)throw Error("Script timeout must be between 1 and 3600 seconds");if(!n.BUILD_SCRIPT_FAILURE_BEHAVIORS.includes(e.failureBehavior))throw Error("Script failure behavior is invalid");let l=await (0,o.getPrismaClient)(),u=e.id??(0,i.randomUUID)();return l.buildScript.upsert({where:{id:u},create:{id:u,name:t,preBuildScript:r,postBuildScript:a,enabledByDefault:e.enabledByDefault,timeoutSeconds:s,failureBehavior:e.failureBehavior},update:{name:t,preBuildScript:r,postBuildScript:a,enabledByDefault:e.enabledByDefault,timeoutSeconds:s,failureBehavior:e.failureBehavior,deletedAt:null}})}async deleteScript(e){let t=await (0,o.getPrismaClient)(),r=await t.buildScript.updateMany({where:{id:e,deletedAt:null},data:{deletedAt:new Date}});return await t.codebaseRepositoryBuildScript.deleteMany({where:{scriptId:e}}),1===r.count}async setAllowedScripts(e,t){let r=await (0,o.getPrismaClient)(),i=await r.codebase.findUnique({where:{id:e}});if(!i)throw Error("Codebase not found");let a=[...new Set(t)];if((await r.buildScript.findMany({where:{id:{in:a},deletedAt:null}})).length!==a.length)throw Error("Build script not found");return await r.$transaction(async e=>{await e.codebaseRepositoryBuildScript.deleteMany({where:{repositoryId:i.repositoryId}}),a.length&&await e.codebaseRepositoryBuildScript.createMany({data:a.map((e,t)=>({repositoryId:i.repositoryId,scriptId:e,position:t}))})}),this.project(e)}async waitForJob(e,t=12e4){let r=u.agentEventBus.iterate((0,u.agentJobChangedTopic)(e)),i=Date.now()+t;try{for(;Date.now()<i;){let t=await this.agentControl.getJob(e);if(!t)throw Error("Agent job disappeared");if(k.has(t.status))return t;await Promise.race([r.next(),new Promise(e=>setTimeout(e,Math.max(1,i-Date.now())))])}throw await this.agentControl.cancelJob(e),Error("Agent did not respond in time")}finally{await r.return?.()}}result(e){if("SUCCEEDED"!==e.status)throw Error(e.error||"Agent operation failed");return f(m(e.resultJson,{}),"agent result")}async discoverSources(e,t){let r=await this.requireWorktree(e,n.IOS_SOURCE_DISCOVER_JOB_KIND),i=await this.agentControl.createJob({agentId:r.codebase.agentId,codebaseId:r.codebaseId,worktreeId:r.id,kind:n.IOS_SOURCE_DISCOVER_JOB_KIND,payload:this.identity(r),idempotencyKey:`ios:source:discover:${t}:${r.id}`,timeoutSeconds:60,visibility:"SYSTEM"});try{let e=this.result(await this.waitForJob(i.id));return Array.isArray(e.sources)?e.sources:[]}finally{let e=await (0,o.getPrismaClient)();await e.agentJob.deleteMany({where:{id:i.id,visibility:"SYSTEM"}})}}async reparse(e,t,r){let a=await this.requireWorktree(t,n.IOS_SOURCE_PARSE_JOB_KIND),s=await (0,o.getPrismaClient)(),l=await s.buildConfiguration.findUnique({where:{id:e},include:{source:{include:{project:!0}}}});if(!l||l.source.project.repositoryId!==a.codebase.repositoryId)throw Error("Build configuration is not available for this worktree");let u=`worktree:${a.id}`,c=await s.buildSourceObservation.findUnique({where:{sourceId_scopeKey:{sourceId:l.sourceId,scopeKey:u}}}),d=new Date;await s.buildSourceObservation.upsert({where:{sourceId_scopeKey:{sourceId:l.sourceId,scopeKey:u}},create:{id:(0,i.randomUUID)(),sourceId:l.sourceId,scopeKey:u,codebaseId:a.codebaseId,worktreeId:a.id,status:"PARSING",lastParseAttemptAt:d},update:{status:"PARSING",error:null,lastParseAttemptAt:d}});let h=await this.agentControl.createJob({agentId:a.codebase.agentId,codebaseId:a.codebaseId,worktreeId:a.id,kind:n.IOS_SOURCE_PARSE_JOB_KIND,payload:{...this.identity(a),source:{kind:l.source.kind,relativePath:l.source.relativePath},scheme:l.scheme},idempotencyKey:`ios:source:parse:${r}:${l.id}:${a.id}`,timeoutSeconds:120,visibility:"SYSTEM"});try{let e=this.result(await this.waitForJob(h.id)),t=g(e.schemes),r=g(e.configurations),i=t.includes(l.scheme)&&r.includes(l.buildConfiguration);return s.buildSourceObservation.update({where:{sourceId_scopeKey:{sourceId:l.sourceId,scopeKey:u}},data:{status:i?"VALID":"INVALID",schemesJson:JSON.stringify(t),configurationsJson:JSON.stringify(r),testPlansJson:JSON.stringify(g(e.testPlans)),error:i?null:"The saved scheme or configuration is no longer available",stale:!1,headSha:"string"==typeof e.headSha?e.headSha:a.headSha,xcodeVersion:"string"==typeof e.xcodeVersion?e.xcodeVersion:null,lastParsedAt:new Date}})}catch(t){let e=t instanceof Error?t.message:String(t);return s.buildSourceObservation.update({where:{sourceId_scopeKey:{sourceId:l.sourceId,scopeKey:u}},data:{status:"ERROR",error:e,stale:!!c?.lastParsedAt}})}finally{await s.agentJob.deleteMany({where:{id:h.id,visibility:"SYSTEM"}})}}async inspectSource(e){let t=await this.requireWorktree(e.worktreeId,n.IOS_SOURCE_PARSE_JOB_KIND),r=(0,n.parseBuildSource)({kind:e.sourceKind,relativePath:e.sourcePath}),i=await this.agentControl.createJob({agentId:t.codebase.agentId,codebaseId:t.codebaseId,worktreeId:t.id,kind:n.IOS_SOURCE_PARSE_JOB_KIND,payload:{...this.identity(t),source:r,scheme:e.scheme?.trim()||null,configuration:e.configuration?.trim()||null},idempotencyKey:`ios:source:inspect:${e.requestId}:${t.id}:${r.relativePath}:${e.scheme??""}:${e.configuration??""}`,timeoutSeconds:120,visibility:"SYSTEM"});try{var a;let e=this.result(await this.waitForJob(i.id));return{source:r,schemes:g(e.schemes),configurations:g(e.configurations),testPlans:g(e.testPlans),signingRequirements:(a=e.signingRequirements,Array.isArray(a)?a.flatMap(e=>!e||"object"!=typeof e||Array.isArray(e)||"string"!=typeof e.bundleId||"string"!=typeof e.name||"string"!=typeof e.target?[]:[{bundleId:e.bundleId,name:e.name,target:e.target,platform:"string"==typeof e.platform?e.platform:null,teamId:"string"==typeof e.teamId?e.teamId:null,provisioningProfileSpecifier:"string"==typeof e.provisioningProfileSpecifier?e.provisioningProfileSpecifier:null}]):[]),headSha:"string"==typeof e.headSha?e.headSha:t.headSha,xcodeVersion:"string"==typeof e.xcodeVersion?e.xcodeVersion:null}}finally{let e=await (0,o.getPrismaClient)();await e.agentJob.deleteMany({where:{id:i.id,visibility:"SYSTEM"}})}}async destinations(e){let t=await this.requireWorktree(e.worktreeId,n.IOS_DESTINATIONS_JOB_KIND),r=await (0,o.getPrismaClient)(),i=await r.buildConfiguration.findUnique({where:{id:e.configurationId},include:{source:{include:{project:!0}}}});if(!i||i.source.project.repositoryId!==t.codebase.repositoryId)throw Error("Build configuration is not available for this worktree");let a=e.action??i.defaultAction;if(!n.BUILD_ACTIONS.includes(a))throw Error("Build action is invalid");let s=(0,n.genericBuildDestinations)(a);if("ARCHIVE"===a)return s;let l=await this.agentControl.createJob({agentId:t.codebase.agentId,codebaseId:t.codebaseId,worktreeId:t.id,kind:n.IOS_DESTINATIONS_JOB_KIND,payload:{...this.identity(t),source:{kind:i.source.kind,relativePath:i.source.relativePath},scheme:i.scheme,configuration:i.buildConfiguration,action:a},idempotencyKey:`ios:destinations:${e.requestId}:${i.id}:${t.id}:${a}`,timeoutSeconds:120,visibility:"SYSTEM"});try{let e=this.result(await this.waitForJob(l.id));return(Array.isArray(e.destinations)?e.destinations:[]).map(e=>(0,n.parseBuildDestination)(e)).filter(e=>!1!==e.available)}finally{await r.agentJob.deleteMany({where:{id:l.id,visibility:"SYSTEM"}})}}async signingOptionsForBuild(e){let t=await (0,o.getPrismaClient)(),r=await t.build.findUnique({where:{id:e},include:{artifacts:!0}}),i=r?.artifacts.find(e=>"ARCHIVE"===e.kind);if(!r||"SUCCEEDED"!==r.status||!r.worktreeId)throw Error("A successful archive build is required");if(!i)throw Error("Build does not contain an archive");let a=await this.requireWorktree(r.worktreeId,n.IOS_SIGNING_INSPECT_JOB_KIND),s=await this.agentControl.createJob({agentId:a.codebase.agentId,codebaseId:a.codebaseId,worktreeId:a.id,kind:n.IOS_SIGNING_INSPECT_JOB_KIND,payload:{buildId:r.id,codebaseId:a.codebaseId,artifactDirectory:r.artifactDirectory,archiveRelativePath:i.relativePath},idempotencyKey:`ios:signing:${r.id}:${i.id}`,timeoutSeconds:120,visibility:"SYSTEM"});try{let e=this.result(await this.waitForJob(s.id));return{teams:Array.isArray(e.teams)?e.teams:[],identities:Array.isArray(e.identities)?e.identities:[],profiles:Array.isArray(e.profiles)?e.profiles:[],bundles:Array.isArray(e.bundles)?e.bundles:[]}}finally{await t.agentJob.deleteMany({where:{id:s.id,visibility:"SYSTEM"}})}}async runAgentsForBuild(e){let t=await (0,o.getPrismaClient)(),r=await t.build.findUnique({where:{id:e},include:{artifacts:!0,agent:!0,worktree:!0}}),i=r?.artifacts.find(e=>"RUNNABLE_APP"===e.kind);if(!r||"SUCCEEDED"!==r.status||!i||!r.agentId)throw Error("A successful runnable build is required");let a=f(m(i.metadataJson,{}),"runnable metadata"),s=new Set(g(a.architectures).map(e=>"x64"===e?"x86_64":e)),l=await (0,d.cachedArtifact)(r.id,i.id),u=r.agent?w(r.agent):[];return(await t.agent.findMany({orderBy:{name:"asc"}})).map(e=>{let t=e.id===r.agentId,i=null;return e.osVersion.toLocaleLowerCase().startsWith("macos")?y(e)?t?w(e).includes(n.IOS_RUN_DESTINATIONS_JOB_KIND)&&w(e).includes(n.IOS_DEPLOY_JOB_KIND)||(i="AGENT_UPDATE_REQUIRED"):w(e).includes(n.IOS_AGENT_RUN_DESTINATIONS_JOB_KIND)&&w(e).includes(n.IOS_REMOTE_DEPLOY_JOB_KIND)?l||r.agent&&y(r.agent)&&u.includes(n.IOS_ARTIFACT_TRANSFER_UPLOAD_JOB_KIND)?"SIMULATOR"===r.destinationType&&s.size>0&&!s.has("x64"===e.architecture?"x86_64":e.architecture)&&(i="INCOMPATIBLE_ARCHITECTURE"):i="BUILD_AGENT_UNAVAILABLE":i="AGENT_UPDATE_REQUIRED":i="OFFLINE":i="NOT_MACOS",{agent:e,isBuildAgent:t,available:null===i,unavailableReason:i}}).sort((e,t)=>Number(t.isBuildAgent)-Number(e.isBuildAgent)||e.agent.name.localeCompare(t.agent.name))}async destinationsForBuild(e,t,r){let i=await (0,o.getPrismaClient)(),a=await i.build.findUnique({where:{id:e},include:{artifacts:!0}});if(!a||"SUCCEEDED"!==a.status||!a.artifacts.some(e=>"RUNNABLE_APP"===e.kind))throw Error("A successful runnable build is required");let s=a.artifacts.find(e=>"RUNNABLE_APP"===e.kind),l=f(m(s.metadataJson,{}),"runnable metadata"),u=r??a.agentId;if(!u)throw Error("Build agent is unavailable");if(u!==a.agentId){let e=(await this.runAgentsForBuild(a.id)).find(e=>e.agent.id===u);if(!e?.available)throw Error("The selected run agent is unavailable");let r=await this.agentControl.createJob({agentId:u,kind:n.IOS_AGENT_RUN_DESTINATIONS_JOB_KIND,payload:{destinationType:a.destinationType},idempotencyKey:`ios:agent-build-destinations:${b(t,"Request ID",200)}:${a.id}:${u}`,timeoutSeconds:120,visibility:"SYSTEM"});try{let e=this.result(await this.waitForJob(r.id));return(Array.isArray(e.destinations)?e.destinations:[]).map(e=>(0,n.parseBuildDestination)(e)).map(e=>S(e,l)).filter(e=>e.type===a.destinationType&&!e.generic)}finally{await i.agentJob.deleteMany({where:{id:r.id,visibility:"SYSTEM"}})}}if(!a.worktreeId)throw Error("The build worktree is unavailable");let c=await this.requireWorktree(a.worktreeId,n.IOS_RUN_DESTINATIONS_JOB_KIND);if(a.agentId!==c.codebase.agentId||a.codebaseId!==c.codebaseId)throw Error("The build no longer belongs to this worktree checkout");let d=await this.agentControl.createJob({agentId:c.codebase.agentId,codebaseId:c.codebaseId,worktreeId:c.id,kind:n.IOS_RUN_DESTINATIONS_JOB_KIND,payload:{...this.identity(c),destinationType:a.destinationType},idempotencyKey:`ios:build-destinations:${b(t,"Request ID",200)}:${a.id}`,timeoutSeconds:120,visibility:"SYSTEM"});try{let e=this.result(await this.waitForJob(d.id));return(Array.isArray(e.destinations)?e.destinations:[]).map(e=>(0,n.parseBuildDestination)(e)).map(e=>S(e,l)).filter(e=>e.type===a.destinationType&&!e.generic)}finally{await i.agentJob.deleteMany({where:{id:d.id,visibility:"SYSTEM"}})}}async startBuild(e){let t=b(e.requestId,"Request ID",200),r=`${e.worktreeId}:${t}`,s=await (0,o.getPrismaClient)(),l=await s.build.findUnique({where:{requestKey:r},include:T});if(l){if(this.telemetry){let e=m(l.snapshotJson,{}),t=f(e.configuration??{},"build configuration snapshot"),r=f(e.destination??{},"build destination snapshot");await this.telemetry.addBuildSeparator({buildId:l.id,name:`Build \xb7 ${String(t.name??"iOS")} \xb7 ${String(r.name??"Destination")}`,clientTime:l.createdAt})}return l}let u=await this.requireWorktree(e.worktreeId,n.IOS_BUILD_JOB_KIND);if(await this.diskSpace?.assertWorktreeCanStart(u.id),e.worktreeCoverage&&!w(u.codebase.agent).includes(n.IOS_COVERAGE_REPORT_JOB_KIND))throw Error("Build agent must be updated for worktree coverage");let d=await s.buildConfiguration.findUnique({where:{id:e.configurationId},include:{source:{include:{project:!0}}}});if(!d||d.source.project.repositoryId!==u.codebase.repositoryId)throw Error("Build configuration is not available for this worktree");let h=await s.buildSourceObservation.findUnique({where:{sourceId_scopeKey:{sourceId:d.sourceId,scopeKey:`worktree:${u.id}`}}}),p=e.action??d.defaultAction;if(!n.BUILD_ACTIONS.includes(p))throw Error("Build action is invalid");if(e.exportWhenComplete&&"ARCHIVE"!==p)throw Error("Export when complete is available only for Archive builds");let g="ARCHIVE"===p&&(e.exportWhenComplete??d.autoExport),y=e.exportSettings??m(d.exportSettingsJson,null),E=g||y?(0,n.parseBuildExportSettings)(y):null;if(g&&!E)throw Error("Export settings are required when automatic export is enabled");let S=(0,n.parseBuildDestination)(e.destination);if(!n.BUILD_DESTINATION_TYPES.includes(S.type))throw Error("Destination is invalid");if("ARCHIVE"===p&&("PHYSICAL_DEVICE"!==S.type||!S.generic))throw Error("Archive builds require the generic physical iOS destination");if(S.generic&&!n.GENERIC_BUILD_DESTINATION_ACTIONS.includes(p))throw Error("This build action requires a concrete destination");let v=f(m(d.advancedSettingsJson,{}),"saved advanced settings"),I=e.advancedSettings?f(e.advancedSettings,"advanced settings override"):{},A=(0,n.parseBuildAdvancedSettings)({...v,...I,buildSettingOverrides:{...f(v.buildSettingOverrides??{},"saved overrides"),...f(I.buildSettingOverrides??{},"run overrides")}});if("TEST_WITHOUT_BUILDING"===p){if(!A.priorBuildForTestingId)throw Error("Test Without Building requires a prior Build for Testing result");let e=await s.build.findUnique({where:{id:A.priorBuildForTestingId},include:{artifacts:{where:{kind:{in:["TEST_PRODUCTS","XCTESTRUN"]}},orderBy:{createdAt:"asc"}}}});if(!e||"SUCCEEDED"!==e.status||"BUILD_FOR_TESTING"!==e.action)throw Error("Test Without Building requires a successful Build for Testing result");if(e.agentId!==u.codebase.agentId||e.worktreeId!==u.id||e.configurationId!==d.id)throw Error("The prior Build for Testing result is not compatible with this agent, worktree, and configuration");if(e.destinationType!==S.type)throw Error("The prior Build for Testing result uses a different destination type");let t=f(m(e.snapshotJson,{}),"prior Build for Testing snapshot"),r=f(t.configuration??{},"prior Build for Testing configuration snapshot"),i=(0,n.parseBuildAdvancedSettings)(r.advancedSettings??{});if(A.testPlan&&i.testPlan&&A.testPlan!==i.testPlan)throw Error("The selected test plan does not match the prior Build for Testing result");let o=A.testPlan??i.testPlan??null,l=e.artifacts.filter(e=>"TEST_PRODUCTS"===e.kind&&e.relativePath.endsWith(".xctestproducts")),c=e.artifacts.filter(e=>"XCTESTRUN"===e.kind&&e.relativePath.endsWith(".xctestrun"));if(l.length>1)throw Error("The prior Build for Testing result contains multiple test-products artifacts");let h=l[0];if(h||1!==c.length||(h=c[0]),!h&&c.length>1&&o&&(h=c.find(e=>f(m(e.metadataJson,{}),"test-run artifact metadata").testPlan===o||e.relativePath.endsWith(`/${o}.xctestrun`)||e.relativePath===`${o}.xctestrun`)),!h&&c.length>1)throw Error("Select a test plan to choose among the captured .xctestrun artifacts");let p=h?.relativePath??"test-products.xctestproducts",g=(0,a.resolve)(e.artifactDirectory),y=(0,a.resolve)(g,p),w=(0,a.relative)(g,y);if(!w||w.startsWith("..")||(0,a.isAbsolute)(w))throw Error("The prior Build for Testing artifact path is invalid");A={...A,testPlan:o,priorTestProductsPath:p.endsWith(".xctestproducts")?y:null,priorXctestrunPath:p.endsWith(".xctestrun")?y:null}}let k=await s.codebaseRepositoryBuildScript.findMany({where:{repositoryId:u.codebase.repositoryId,script:{deletedAt:null}},orderBy:[{position:"asc"},{script:{name:"asc"}}],include:{script:!0}}),_=new Set(e.scriptIds??[]);if([..._].some(e=>!k.some(t=>t.scriptId===e)))throw Error("A selected build script is not allowed for this codebase");let C=k.filter(e=>_.has(e.scriptId)),R=(0,i.randomUUID)(),N=(0,c.effectiveBuildsDirectory)(u.codebase.agent);if(!N)throw Error("The agent builds directory is unavailable");let O=(0,a.join)(N,R),D={kind:d.source.kind,relativePath:d.source.relativePath},P=function(e){var t;let r=e.advancedSettings,i="TEST_WITHOUT_BUILDING"===e.action,n=["xcodebuild",...i?[]:[..."PACKAGE"===e.source.kind?[]:"PROJECT"===e.source.kind?["-project",e.source.relativePath]:["-workspace",e.source.relativePath],"-scheme",e.scheme,"-configuration",e.configuration],"-destination",(t=e.destination).generic?"SIMULATOR"===t.type?"generic/platform=iOS Simulator":"generic/platform=iOS":"SIMULATOR"===t.type?`platform=iOS Simulator,id=${t.id}`:`platform=iOS,id=${t.id}`,"-hideShellScriptEnvironment","-resultBundlePath",(0,a.join)(e.artifactDirectory,"result.xcresult")];for(let e of(!i&&("RESOLVED_ONLY"===r.packageResolution?n.push("-onlyUsePackageVersionsFromResolvedFile"):"SKIP_UPDATES"===r.packageResolution?n.push("-skipPackageUpdates"):"DISABLE_AUTOMATIC"===r.packageResolution&&n.push("-disableAutomaticPackageResolution"),r.disablePackageRepositoryCache&&n.push("-disablePackageRepositoryCache"),"PROJECT_DEFAULT"!==r.signingStyle&&n.push(`CODE_SIGN_STYLE=${"AUTOMATIC"===r.signingStyle?"Automatic":"Manual"}`),r.developmentTeam&&n.push(`DEVELOPMENT_TEAM=${r.developmentTeam}`),r.codeSignIdentity&&n.push(`CODE_SIGN_IDENTITY=${r.codeSignIdentity}`),r.provisioningProfileSpecifier&&n.push(`PROVISIONING_PROFILE_SPECIFIER=${r.provisioningProfileSpecifier}`),r.productBundleIdentifier&&n.push(`PRODUCT_BUNDLE_IDENTIFIER=${r.productBundleIdentifier}`),r.allowProvisioningUpdates&&n.push("-allowProvisioningUpdates"),r.allowProvisioningDeviceRegistration&&n.push("-allowProvisioningDeviceRegistration")),r.testPlan&&n.push("-testPlan",r.testPlan),r.codeCoverage&&n.push("-enableCodeCoverage","YES"),null!==r.parallelTesting&&n.push("-parallel-testing-enabled",r.parallelTesting?"YES":"NO"),null!==r.parallelTestingWorkers&&n.push("-parallel-testing-worker-count",String(r.parallelTestingWorkers)),r.onlyTesting))n.push(`-only-testing:${e}`);for(let e of r.skipTesting)n.push(`-skip-testing:${e}`);if(!i)for(let[e,t]of Object.entries(r.buildSettingOverrides))n.push(`${e}=${t}`);"ARCHIVE"===e.action&&n.push("-archivePath",(0,a.join)(e.artifactDirectory,"archive.xcarchive")),"BUILD_FOR_TESTING"===e.action&&n.push("-testProductsPath",(0,a.join)(e.artifactDirectory,"test-products.xctestproducts")),"TEST_WITHOUT_BUILDING"===e.action&&r.priorTestProductsPath&&n.push("-testProductsPath",r.priorTestProductsPath),"TEST_WITHOUT_BUILDING"===e.action&&!r.priorTestProductsPath&&r.priorXctestrunPath&&n.push("-xctestrun",r.priorXctestrunPath),n.push({BUILD:"build",TEST:"test",ANALYZE:"analyze",ARCHIVE:"archive",BUILD_FOR_TESTING:"build-for-testing",TEST_WITHOUT_BUILDING:"test-without-building"}[e.action]);let s=n.map(e=>/^[A-Za-z0-9_./:=,-]+$/.test(e)?e:JSON.stringify(e)).join(" ");return`cd ${JSON.stringify(e.folder)} && xcrun ${s}`}({folder:u.folder,source:D,scheme:d.scheme,configuration:d.buildConfiguration,destination:S,action:p,advancedSettings:A,artifactDirectory:O}),x=C.map(({script:e,position:t})=>({id:e.id,name:e.name,preBuildScript:e.preBuildScript,postBuildScript:e.postBuildScript,timeoutSeconds:e.timeoutSeconds,failureBehavior:e.failureBehavior,position:t})),L=await this.telemetry?.buildSettings(S.type,{requestOrigin:e.telemetryRequestOrigin}),U={repository:{id:u.codebase.repository.id,name:u.codebase.repository.name,canonicalOrigin:u.codebase.repository.canonicalOrigin},codebase:{id:u.codebase.id,folder:u.codebase.folder},worktree:{id:u.id,folder:u.folder,branch:u.branch,headSha:u.headSha,codeStateHash:u.codeStateHash,hasStagedChanges:u.hasStagedChanges,hasUnstagedChanges:u.hasUnstagedChanges},agent:{id:u.codebase.agent.id,name:u.codebase.agent.name,hostname:u.codebase.agent.hostname},configuration:{id:d.id,name:d.name,iconKey:d.iconKey,source:D,scheme:d.scheme,buildConfiguration:d.buildConfiguration,action:p,advancedSettings:A,autoExport:g,exportSettings:E,parse:h?{status:h.status,schemes:m(h.schemesJson,[]),configurations:m(h.configurationsJson,[]),testPlans:m(h.testPlansJson,[]),headSha:h.headSha,xcodeVersion:h.xcodeVersion,parsedAt:h.lastParsedAt?.toISOString()??null}:{status:"UNPARSED",schemes:[],configurations:[],testPlans:[],headSha:null,xcodeVersion:null,parsedAt:null}},destination:S,scripts:x,...L?{telemetry:L}:{},worktreeCoverage:!0===e.worktreeCoverage},B=new Date,M=s.build.create({data:{id:R,requestKey:r,requestId:t,agentId:u.codebase.agentId,codebaseId:u.codebaseId,worktreeId:u.id,repositoryId:u.codebase.repository.id,configurationId:d.id,status:"QUEUED",action:p,destinationType:S.type,destinationJson:JSON.stringify(S),snapshotJson:JSON.stringify(U),commandSummary:P,artifactDirectory:O,createdAt:B,scriptExecutions:{create:x.flatMap(e=>[...e.preBuildScript?[{id:(0,i.randomUUID)(),scriptId:e.id,phase:"PRE_BUILD",position:e.position,nameSnapshot:e.name,sourceSnapshot:e.preBuildScript,timeoutSeconds:e.timeoutSeconds,failureBehavior:e.failureBehavior}]:[],...e.postBuildScript?[{id:(0,i.randomUUID)(),scriptId:e.id,phase:"POST_BUILD",position:e.position,nameSnapshot:e.name,sourceSnapshot:e.postBuildScript,timeoutSeconds:e.timeoutSeconds,failureBehavior:e.failureBehavior}]:[]])}}});if(this.telemetry){let e=(0,i.randomUUID)();await s.$transaction([M,s.telemetryEntry.create({data:{id:e,entryType:"SEPARATOR",clientTime:B,receivedAt:B,separatorKind:"BUILD",separatorName:`Build \xb7 ${d.name} \xb7 ${S.name}`.slice(0,100),buildId:R}})]),this.telemetry.notifyChange([e],"BUILD_SEPARATOR_ADDED")}else await M;try{let r=await this.agentControl.createJob({agentId:u.codebase.agentId,codebaseId:u.codebaseId,worktreeId:u.id,kind:n.IOS_BUILD_JOB_KIND,payload:{...this.identity(u),buildId:R,artifactDirectory:O,source:D,scheme:d.scheme,configuration:d.buildConfiguration,action:p,destination:S,advancedSettings:A,scripts:x,...L?{telemetry:L}:{},worktreeCoverage:!0===e.worktreeCoverage},idempotencyKey:`ios:build:${t}:${u.id}`,timeoutSeconds:604800});await s.build.update({where:{id:R},data:{jobId:r.id}})}catch(e){throw await s.build.update({where:{id:R},data:{status:"FAILED",errorCode:"QUEUE_FAILED",error:e instanceof Error?e.message:String(e),finishedAt:new Date}}),e}return this.publish(R),s.build.findUniqueOrThrow({where:{id:R},include:T})}async rebuildBuild(e,t,r){let i=await (0,o.getPrismaClient)(),a=await i.build.findUnique({where:{id:e},select:{worktreeId:!0,configurationId:!0,destinationJson:!0,action:!0,snapshotJson:!0}});if(!a)throw Error("Build not found");let n=f(m(a.snapshotJson,{}),"build snapshot"),s=f(n.worktree??{},"build worktree snapshot"),l=f(n.configuration??{},"build configuration snapshot"),u=Array.isArray(n.scripts)?n.scripts:[],c=a.worktreeId??("string"==typeof s.id?s.id:null),d=a.configurationId??("string"==typeof l.id?l.id:null);if(!c||!d)throw Error("The original build settings are unavailable");return this.startBuild({worktreeId:c,configurationId:d,destination:m(a.destinationJson,{}),scriptIds:u.flatMap(e=>{if(!e||"object"!=typeof e||Array.isArray(e))return[];let t=e.id;return"string"==typeof t?[t]:[]}),action:a.action,advancedSettings:l.advancedSettings,exportWhenComplete:!0===l.autoExport,...Object.hasOwn(l,"exportSettings")?{exportSettings:l.exportSettings}:{},requestId:t,...r?{telemetryRequestOrigin:r}:{}})}async startWorktreeCoverage(e){let t=await (0,o.getPrismaClient)(),r=await t.worktree.findUnique({where:{id:e.worktreeId},select:{baseBranchOverride:!0,codebase:{select:{defaultBranch:!0}}}});if(!r||!(r.baseBranchOverride??r.codebase.defaultBranch))throw Error("A base branch is required for worktree coverage");let i=f(e.advancedSettings??{},"coverage advanced settings");return this.startBuild({...e,action:"TEST",advancedSettings:{...i,codeCoverage:!0,parseTestResults:!0},worktreeCoverage:!0})}async importCoverageReport(e){let t=await (0,o.getPrismaClient)(),r=await this.requireWorktree(e.worktreeId,s.COVERAGE_IMPORT_JOB_KIND,"Agent must be updated to import coverage reports"),n=r.baseBranchOverride??r.codebase.defaultBranch??null,l=(e.format||"AUTO").toUpperCase();if(!s.COVERAGE_REPORT_FORMATS.includes(l))throw Error("Coverage format must be AUTO, LCOV, or ISTANBUL");let u=b(e.buildName??"Coverage report","Build name",200),d=b(e.reportPath,"Coverage file",4e3),h=b(e.requestId,"Request ID",200),p=`coverage:${e.worktreeId}:${h}`,m=await t.build.findUnique({where:{requestKey:p}});if(m)return m;let f=(0,i.randomUUID)(),g=(0,c.effectiveBuildsDirectory)(r.codebase.agent);if(!g)throw Error("The agent builds directory is unavailable");let y={repository:{id:r.codebase.repository.id,name:r.codebase.repository.name,canonicalOrigin:r.codebase.repository.canonicalOrigin},codebase:{id:r.codebase.id,folder:r.codebase.folder},worktree:{id:r.id,folder:r.folder,branch:r.branch,headSha:r.headSha,codeStateHash:r.codeStateHash,hasStagedChanges:r.hasStagedChanges,hasUnstagedChanges:r.hasUnstagedChanges},agent:{id:r.codebase.agent.id,name:r.codebase.agent.name,hostname:r.codebase.agent.hostname},configuration:{name:u},coverageImport:{reportPath:d,format:l,baseBranch:n},worktreeCoverage:!0},w={type:"HOST",id:r.codebase.agent.id,name:r.codebase.agent.name,platform:r.codebase.agent.architecture,osVersion:r.codebase.agent.osVersion||null,state:"Connected"},E=await t.build.create({data:{id:f,requestKey:p,requestId:h,agentId:r.codebase.agentId,codebaseId:r.codebaseId,worktreeId:r.id,repositoryId:r.codebase.repository.id,status:"RUNNING",action:"TEST",destinationType:"HOST",destinationJson:JSON.stringify(w),snapshotJson:JSON.stringify(y),commandSummary:`Import coverage from ${d}`,artifactDirectory:(0,a.join)(g,f),startedAt:new Date}}),S=null;try{await t.buildReport.create({data:{id:(0,i.randomUUID)(),buildId:f,kind:"CODE_COVERAGE",source:"WORKTREE",status:"PENDING"}}),this.publish(f);let e=await this.agentControl.createJob({agentId:r.codebase.agentId,codebaseId:r.codebaseId,worktreeId:r.id,kind:s.COVERAGE_IMPORT_JOB_KIND,payload:{buildId:f,codebaseId:r.codebaseId,worktreeId:r.id,folder:r.folder,reportPath:d,format:l,baseBranch:n},idempotencyKey:`coverage:import:${h}:${f}`,timeoutSeconds:300,visibility:"SYSTEM"});return S=e.id,await t.build.update({where:{id:f},data:{jobId:e.id}}),{...E,jobId:e.id}}catch(a){S&&await this.agentControl.cancelJob(S).catch(()=>void 0);let e=a instanceof Error?a.message:String(a),r=new Date;throw await t.$transaction(async t=>{await t.buildReport.upsert({where:{buildId_kind:{buildId:f,kind:"CODE_COVERAGE"}},create:{id:(0,i.randomUUID)(),buildId:f,kind:"CODE_COVERAGE",source:"WORKTREE",status:"FAILED",error:e,finishedAt:r},update:{status:"FAILED",error:e,finishedAt:r}}),await t.build.update({where:{id:f},data:{status:"FAILED",errorCode:"QUEUE_FAILED",error:e,finishedAt:r}})}),this.publish(f),a}}async importedCoverageCompletion(e){let t=f(m(e.payloadJson,{}),"coverage import payload");if("string"!=typeof t.buildId)return;let r=t.buildId,a=f(m(e.resultJson,{}),"coverage import result"),n="SUCCEEDED"===e.status&&!!a.report&&"object"==typeof a.report,s=await (0,o.getPrismaClient)();await s.$transaction(async t=>{n?await this.upsertReportProjection(t,r,a.report,"WORKTREE"):await t.buildReport.upsert({where:{buildId_kind:{buildId:r,kind:"CODE_COVERAGE"}},create:{id:(0,i.randomUUID)(),buildId:r,kind:"CODE_COVERAGE",source:"WORKTREE",status:"FAILED",error:e.error||"Coverage import failed",finishedAt:new Date},update:{status:"FAILED",error:e.error||"Coverage import failed",finishedAt:new Date}}),await t.build.update({where:{id:r},data:{status:n?"SUCCEEDED":"FAILED",error:n?null:e.error||"Coverage import failed",finishedAt:new Date}})}),this.publish(r)}async generateReport(e,t,r){let a=await (0,o.getPrismaClient)(),s=await a.buildReport.findUnique({where:{buildId_kind:{buildId:e,kind:t}},include:{artifact:!0}});if(s?.status==="READY")return s;let l=await a.build.findUnique({where:{id:e},include:{agent:!0,artifacts:!0}});if(!l)throw Error("Build not found");if(_.includes(l.status))throw Error("Wait for the build to finish before generating reports");if(!l.agentId||!l.agent||!y(l.agent))throw Error("Build agent is offline");let u="TEST_RESULTS"===t?n.IOS_TEST_RESULTS_JOB_KIND:n.IOS_COVERAGE_REPORT_JOB_KIND;if(!w(l.agent).includes(u))throw Error("Build agent must be updated to generate reports");if(!l.artifacts.some(e=>"RESULT_BUNDLE"===e.kind))throw Error("The build result bundle is unavailable");if("TEST_RESULTS"===t&&!["TEST","TEST_WITHOUT_BUILDING"].includes(l.action))throw Error("This build did not run tests");let c=await a.buildReport.upsert({where:{buildId_kind:{buildId:e,kind:t}},create:{id:(0,i.randomUUID)(),buildId:e,kind:t,source:"MANUAL",status:"PENDING"},update:{source:"MANUAL",status:"PENDING",error:null,finishedAt:null}});this.publish(e);let d=v(l),h=await this.agentControl.createJob({agentId:l.agentId,codebaseId:d,worktreeId:l.worktreeId,kind:u,payload:{buildId:e,artifactDirectory:l.artifactDirectory,codebaseId:d,reportKind:t,source:"MANUAL"},idempotencyKey:`ios:report:${t}:${b(r,"Request ID",200)}:${e}`,timeoutSeconds:180,visibility:"SYSTEM"});try{return await this.waitForJob(h.id,17e4),a.buildReport.findUniqueOrThrow({where:{id:c.id},include:{artifact:!0}})}finally{await a.agentJob.deleteMany({where:{id:h.id,visibility:"SYSTEM"}})}}async coverageHistory(e){return(await (0,o.getPrismaClient)()).buildReport.findMany({where:{kind:"CODE_COVERAGE",source:"WORKTREE",build:{worktreeId:e}},orderBy:{createdAt:"desc"},take:50,select:{id:!0,buildId:!0,artifactId:!0,kind:!0,source:!0,status:!0,summaryJson:!0,error:!0,createdAt:!0,updatedAt:!0,finishedAt:!0,artifact:!0,build:{select:{id:!0,status:!0,action:!0,destinationType:!0,destinationJson:!0,snapshotJson:!0,createdAt:!0,startedAt:!0,finishedAt:!0,updatedAt:!0,worktree:{select:{headSha:!0,codeStateHash:!0,hasStagedChanges:!0,hasUnstagedChanges:!0,lastCheckedAt:!0,_count:{select:{builds:{where:{status:{in:_}}}}}}},artifacts:{orderBy:{createdAt:"asc"}}}}}})}async reportsForBuild(e){return(await (0,o.getPrismaClient)()).buildReport.findMany({where:{buildId:e},orderBy:{createdAt:"asc"},include:{artifact:!0}})}async reportData(e){let t=await (0,o.getPrismaClient)(),r=await t.buildReport.findUnique({where:{id:e},select:{dataJson:!0}});return r?.dataJson??"{}"}async builds(e={}){let t=await (0,o.getPrismaClient)(),r=Math.max(1,Math.min(e.first??50,200)),i=await t.build.findMany({where:{...e.status?{status:e.status}:{},...e.codebaseId?{codebaseId:e.codebaseId}:{},...e.worktreeId?{worktreeId:e.worktreeId}:{},...e.appId?{repository:{apps:{some:{appId:e.appId}}}}:{}},orderBy:[{createdAt:"desc"},{id:"desc"}],...e.after?{cursor:{id:e.after},skip:1}:{},take:r+1,include:T});return{items:i.slice(0,r),nextCursor:i.length>r?i[r-1].id:null}}async getBuild(e){return(await (0,o.getPrismaClient)()).build.findUnique({where:{id:e},include:T})}async deleteBuilds(e){let t=[...new Set(e)];if(!t.length)return 0;if(t.length>200)throw Error("At most 200 builds can be deleted at once");let r=await (0,o.getPrismaClient)(),i=await r.build.findMany({where:{id:{in:t}},select:{id:!0,status:!0,artifactDirectory:!0,snapshotJson:!0,agentId:!0,agent:{select:{capabilitiesJson:!0}},codebaseId:!0,worktreeId:!0,deployments:{where:{status:{in:_}},select:{id:!0}},exports:{where:{status:{in:_}},select:{id:!0}}}});if(i.some(e=>_.includes(e.status)))throw Error("Running builds cannot be deleted");if(i.some(e=>e.deployments.length>0||e.exports.length>0))throw Error("Builds with running deployments or exports cannot be deleted");for(let e of i){if(!(0,a.isAbsolute)(e.artifactDirectory)||(0,a.basename)(e.artifactDirectory)!==e.id)throw Error(`Build folder is invalid for ${e.id}`);if(e.agentId){let t=v(e);if(!e.agent||!w(e.agent).includes(n.IOS_BUILD_DELETE_JOB_KIND))throw Error("Build agent must be updated to delete builds");await this.agentControl.createJob({agentId:e.agentId,codebaseId:t,worktreeId:e.worktreeId,kind:n.IOS_BUILD_DELETE_JOB_KIND,payload:{buildId:e.id,artifactDirectory:e.artifactDirectory,codebaseId:t},idempotencyKey:`ios:build:delete:${e.id}`,timeoutSeconds:300,visibility:"SYSTEM"})}}let s=await r.build.deleteMany({where:{id:{in:i.map(e=>e.id)}}});for(let e of i)this.publish(e.id);return s.count}async artifactForInstall(e,t){let r=await (0,o.getPrismaClient)(),i=await r.buildArtifact.findFirst({where:{id:t,buildId:e}});return i?{id:i.id,kind:i.kind,relativePath:i.relativePath,sizeBytes:i.sizeBytes,checksum:i.checksum,createdAt:i.createdAt.toISOString(),metadata:f(m(i.metadataJson,{}),"build artifact metadata")}:null}async prepareArtifactDownload(e,t,r,i=17e4){let a=await (0,o.getPrismaClient)(),s=await a.buildArtifact.findFirst({where:{id:t,buildId:e},include:{build:{include:{agent:!0}}}});if(!s)throw Error("Build artifact not found");let{build:l}=s;if(!l.agentId||!l.agent)throw Error("The build agent is no longer available");if(!y(l.agent))throw Error("Build agent is offline");if(!w(l.agent).includes(n.IOS_ARTIFACT_DOWNLOAD_JOB_KIND))throw Error("Build agent must be updated to download artifacts");let u=v(l),c=await this.agentControl.createJob({agentId:l.agentId,codebaseId:u,worktreeId:l.worktreeId,kind:n.IOS_ARTIFACT_DOWNLOAD_JOB_KIND,payload:{buildId:l.id,artifactDirectory:l.artifactDirectory,artifactRelativePath:s.relativePath,uploadId:r,codebaseId:u},idempotencyKey:`ios:artifact:download:${r}`,timeoutSeconds:Math.ceil(i/1e3)+10,visibility:"SYSTEM"});try{this.result(await this.waitForJob(c.id,i))}finally{await a.agentJob.deleteMany({where:{id:c.id,visibility:"SYSTEM"}})}}async logChunks(e,t=null,r=1e3){let i=await (0,o.getPrismaClient)(),a=t?await i.buildLogChunk.findFirst({where:{id:t,buildId:e},select:{id:!0,createdAt:!0,sequence:!0}}):null;if(t&&!a)throw Error("Build log cursor not found");return i.buildLogChunk.findMany({where:{buildId:e,...a?{OR:[{createdAt:{gt:a.createdAt}},{createdAt:a.createdAt,sequence:{gt:a.sequence}},{createdAt:a.createdAt,sequence:a.sequence,id:{gt:a.id}}]}:{}},orderBy:[{createdAt:"asc"},{sequence:"asc"},{id:"asc"}],take:Math.max(1,Math.min(r,5e3))})}async cancelBuild(e){let t=await (0,o.getPrismaClient)(),r=await t.build.findUnique({where:{id:e}});if(!r)throw Error("Build not found");return _.includes(r.status)&&(r.jobId&&await this.agentControl.cancelJob(r.jobId),await t.build.update({where:{id:e},data:{status:"CANCELLED",finishedAt:new Date,errorCode:"CANCELLED"}}),this.publish(e)),this.getBuild(e)}async reportProgress(e,t){if(!["PREPARING","RUNNING"].includes(t.status))throw Error("Build progress status is invalid");let r=await (0,o.getPrismaClient)(),i=await r.build.findUnique({where:{id:t.buildId}});if(!i||i.agentId!==e)throw Error("Build not found for agent");if(!_.includes(i.status))return i;let a=await r.build.update({where:{id:t.buildId},data:{status:t.status,startedAt:i.startedAt??(t.startedAt?new Date(t.startedAt):new Date),errorCode:t.errorCode??void 0,error:t.error??void 0}});return this.publish(t.buildId),a}async appendLogChunks(e,t,r){if(!r.length||r.length>200)throw Error("Build log batches must contain 1 to 200 chunks");let a=await (0,o.getPrismaClient)(),n=await a.build.findUnique({where:{id:t}});if(!n||n.agentId!==e)throw Error("Build not found for agent");let s=r.map(e=>{if(!Number.isInteger(e.sequence)||e.sequence<0)throw Error("Log sequence must be a non-negative integer");if(!["STDOUT","STDERR","SYSTEM"].includes(e.stream))throw Error("Log stream is invalid");let r=Buffer.from(e.dataBase64,"base64");if(r.length!==e.byteLength||r.length>262144)throw Error("Log byte length is invalid");let a=Buffer.from(r.toString("utf8").replace(/(Bearer\s+)[A-Za-z0-9._~+\/-]+=*/gi,"$1[REDACTED]").replace(/([A-Za-z][A-Za-z0-9+.-]*:\/\/)[^\s/@]+@/g,"$1[REDACTED]@").replace(/\b([A-Z0-9_]*(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY)[A-Z0-9_]*)\s*=\s*[^\s]+/gi,"$1=[REDACTED]").replace(/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?-----END [^-]*PRIVATE KEY-----/g,"[REDACTED PRIVATE KEY]"),"utf8"),n=new Date(e.createdAt);if(Number.isNaN(n.valueOf()))throw Error("Log date is invalid");return{id:(0,i.randomUUID)(),buildId:t,scope:b(e.scope,"Log scope",40),scopeId:b(e.scopeId,"Log scope ID",200),sequence:e.sequence,phase:b(e.phase,"Log phase",80),stream:e.stream,dataBase64:a.toString("base64"),byteLength:a.byteLength,createdAt:n}}),l=[];for(let e of s){let r=await a.buildLogChunk.upsert({where:{scope_scopeId_sequence:{scope:e.scope,scopeId:e.scopeId,sequence:e.sequence}},create:e,update:{}});l.push(r),u.agentEventBus.publish((0,u.buildLogChunkTopic)(t),{buildLogChunkAdded:r})}return l}async runBuild(e){let t=await (0,o.getPrismaClient)(),r=await t.build.findUnique({where:{id:e.buildId},include:{artifacts:!0,worktree:{include:{codebase:{include:{agent:!0,repository:!0}}}}}});if(!r||"SUCCEEDED"!==r.status)throw Error("A successful build is required");let a=r.artifacts.find(e=>"RUNNABLE_APP"===e.kind);if(!a)throw Error("Build does not contain a runnable app");let s=f(m(a.metadataJson,{}),"runnable metadata"),l=b(String(s.bundleIdentifier??""),"Runnable bundle identifier",512),u=e.destinations.map(n.parseBuildDestination);if(!u.length)throw Error("Select at least one destination");if(new Set(u.map(e=>`${e.type}:${e.id}`)).size!==u.length)throw Error("Run destinations must be unique");if(u.some(e=>e.type!==r.destinationType))throw Error("Run destinations must match the build destination type");let c=r.agentId??r.worktree?.codebase.agentId,p=e.targetAgentId??c;if(!p)throw Error("Build agent is unavailable");let g=p===c;if(!g){let e=(await this.runAgentsForBuild(r.id)).find(e=>e.agent.id===p);if(!e?.available)throw Error("The selected run agent is unavailable")}let y=await this.destinationsForBuild(r.id,`${b(e.requestId,"Request ID",200)}:preflight`,p),w=u.map(e=>y.find(t=>t.type===e.type&&t.id===e.id));if(w.some(e=>!e)||(u=w).some(e=>!1===e.available))throw Error("A selected run destination is no longer available");if(g&&!r.worktree)throw Error("The build worktree is unavailable");let E=g?await this.requireWorktree(r.worktree.id,n.IOS_DEPLOY_JOB_KIND):null,S=(0,i.randomUUID)(),v=[];for(let a of u){let n=`${a.type}:${a.id}`,s=await t.buildDeployment.findUnique({where:{buildId_requestId_targetAgentId_destinationKey:{buildId:r.id,requestId:e.requestId,targetAgentId:p,destinationKey:n}}});v.push(s??await t.buildDeployment.create({data:{id:(0,i.randomUUID)(),buildId:r.id,batchId:S,requestId:e.requestId,destinationJson:JSON.stringify(a),destinationKey:n,targetAgentId:p,status:g?"QUEUED":"TRANSFERRING",commandSummary:"SIMULATOR"===a.type?`open -a Simulator --args -CurrentDeviceUDID ${a.id}; xcrun simctl install/launch ${a.id}`:`xcrun devicectl device install/process launch --device ${a.id}`}}))}let I=v.map((e,t)=>({id:e.id,destination:u[t]}));if(g&&E){let i=await this.agentControl.createJob({agentId:E.codebase.agentId,codebaseId:E.codebaseId,worktreeId:E.id,kind:n.IOS_DEPLOY_JOB_KIND,payload:{...this.identity(E),buildId:r.id,artifactDirectory:r.artifactDirectory,artifactRelativePath:a.relativePath,bundleIdentifier:l,deployments:I},idempotencyKey:`ios:deploy:${r.id}:${e.requestId}`,timeoutSeconds:3600});await t.buildDeployment.updateMany({where:{id:{in:v.map(e=>e.id)}},data:{jobId:i.id}})}else if(!v.find(e=>e.transferId)?.transferId){let s=(0,i.randomUUID)(),o=await (0,d.cachedArtifact)(r.id,a.id),u=o?await (0,h.buildArtifactFileChecksum)(o.path):null;await t.buildArtifactTransfer.create({data:{id:s,artifactId:a.id,sourceAgentId:r.agentId,targetAgentId:p,status:o?"READY":"QUEUED",uploadOffset:o?.size??0,uploadLength:o?.size??null,checksum:u,filename:o?.filename??null,contentType:o?.contentType??null,stagingPath:o?.path??null,expiresAt:new Date(Date.now()+216e5)}});try{let i=null;o||(i=(await this.agentControl.createJob({agentId:r.agentId,kind:n.IOS_ARTIFACT_TRANSFER_UPLOAD_JOB_KIND,payload:{transferId:s,buildId:r.id,artifactDirectory:r.artifactDirectory,artifactRelativePath:a.relativePath},idempotencyKey:`ios:artifact-transfer:${s}`,timeoutSeconds:3600,visibility:"SYSTEM"})).id,await t.buildArtifactTransfer.update({where:{id:s},data:{sourceJobId:i}}));let u=await this.agentControl.createJob({agentId:p,kind:n.IOS_REMOTE_DEPLOY_JOB_KIND,payload:{transferId:s,buildId:r.id,bundleIdentifier:l,deployments:I},idempotencyKey:`ios:remote-deploy:${r.id}:${e.requestId}:${p}`,timeoutSeconds:7200});await t.$transaction([t.buildArtifactTransfer.update({where:{id:s},data:{sourceJobId:i,targetJobId:u.id}}),t.buildDeployment.updateMany({where:{id:{in:v.map(e=>e.id)}},data:{jobId:u.id,transferId:s,targetAgentId:p}})])}catch(a){let e=a instanceof Error?a.message:String(a),i=new Date;throw await t.$transaction([t.buildArtifactTransfer.update({where:{id:s},data:{status:"FAILED",error:e,finishedAt:i}}),t.buildDeployment.updateMany({where:{id:{in:v.map(e=>e.id)}},data:{status:"FAILED",error:e,finishedAt:i}})]).catch(()=>{}),this.publish(r.id),a}}return this.publish(r.id),t.buildDeployment.findMany({where:{id:{in:v.map(e=>e.id)}},orderBy:{createdAt:"asc"}})}async exportArchive(e){let t=await (0,o.getPrismaClient)(),r=await t.buildExport.findUnique({where:{buildId_requestId:{buildId:e.buildId,requestId:e.requestId}}});if(r)return r;let a=await t.build.findUnique({where:{id:e.buildId},include:{artifacts:!0,worktree:!0}});if(!a||"SUCCEEDED"!==a.status||!a.worktree)throw Error("A successful archive build is required");let s=a.artifacts.find(e=>"ARCHIVE"===e.kind);if(!s)throw Error("Build does not contain an archive");let l=(0,n.parseBuildExportSettings)(e.settings),u=await this.requireWorktree(a.worktree.id,n.IOS_EXPORT_JOB_KIND),c=(0,i.randomUUID)(),d=await t.buildExport.create({data:{id:c,buildId:a.id,requestId:e.requestId,settingsSnapshotJson:JSON.stringify(l),commandSummary:`xcrun xcodebuild -exportArchive -archivePath ${JSON.stringify(s.relativePath)} -exportPath exports/${c}`}});try{let r=await this.agentControl.createJob({agentId:u.codebase.agentId,codebaseId:u.codebaseId,worktreeId:u.id,kind:n.IOS_EXPORT_JOB_KIND,payload:{...this.identity(u),buildId:a.id,exportId:c,artifactDirectory:a.artifactDirectory,archiveRelativePath:s.relativePath,settings:l},idempotencyKey:`ios:export:${a.id}:${e.requestId}`,timeoutSeconds:3600}),i=await t.buildExport.update({where:{id:d.id},data:{jobId:r.id}});return this.publish(a.id),i}catch(r){let e=await t.buildExport.update({where:{id:d.id},data:{status:"FAILED",error:r instanceof Error?r.message:String(r),finishedAt:new Date}});return this.publish(a.id),e}}async upsertArtifacts(e,t,r){for(let a of(0,n.parseBuildArtifactSnapshots)(r)){let r={kind:a.kind,sizeBytes:a.sizeBytes,checksum:a.checksum,metadataJson:JSON.stringify(a.metadata)};await e.buildArtifact.upsert({where:{buildId_relativePath:{buildId:t,relativePath:a.relativePath}},create:{id:(0,i.randomUUID)(),buildId:t,relativePath:a.relativePath,...r},update:r})}}async upsertReportProjection(e,t,r,a){let n=f(r,"build report");if("TEST_RESULTS"!==n.kind&&"CODE_COVERAGE"!==n.kind)return;let s=n.kind,o=n.artifact&&"object"==typeof n.artifact?f(n.artifact,"build report artifact"):null,l=o&&"string"==typeof o.relativePath?await e.buildArtifact.findUnique({where:{buildId_relativePath:{buildId:t,relativePath:o.relativePath}}}):null,u="READY"===n.status?"READY":"FAILED";await e.buildReport.upsert({where:{buildId_kind:{buildId:t,kind:s}},create:{id:(0,i.randomUUID)(),buildId:t,artifactId:l?.id??null,kind:s,source:a,status:u,summaryJson:JSON.stringify(n.summary&&"object"==typeof n.summary?n.summary:{}),dataJson:JSON.stringify(n.data&&"object"==typeof n.data?n.data:{}),error:"string"==typeof n.error?n.error:null,finishedAt:new Date},update:{artifactId:l?.id??null,source:a,status:u,summaryJson:JSON.stringify(n.summary&&"object"==typeof n.summary?n.summary:{}),dataJson:JSON.stringify(n.data&&"object"==typeof n.data?n.data:{}),error:"string"==typeof n.error?n.error:null,finishedAt:new Date}})}async projectBuildCompletion(e){let t=await (0,o.getPrismaClient)(),r=await t.build.findFirst({where:{jobId:e.id},include:{worktree:{select:{highlightColor:!0}}}});if(!r)return;let a=f(m(e.resultJson,{}),"build result"),n="CANCELLED"===r.status?"CANCELLED":I(e.status),s="string"==typeof a.sourceStateHash?a.sourceStateHash:null,l="string"==typeof a.finalStateHash?a.finalStateHash:null,u="string"==typeof a.codeStateObservedAt&&Number.isFinite(Date.parse(a.codeStateObservedAt))?new Date(a.codeStateObservedAt):new Date,c=l?u:new Date,d=r.snapshotJson;if(s){let e=f(m(r.snapshotJson,{}),"build snapshot"),t=f(e.worktree??{},"build worktree snapshot");d=JSON.stringify({...e,worktree:{...t,codeStateHash:s}})}let h=null;await t.$transaction(async t=>{if(await t.build.update({where:{id:r.id},data:{status:n,errorCode:"string"==typeof a.errorCode?a.errorCode:"TIMED_OUT"===e.status?"TIMEOUT":"FAILED"===n?"XCODEBUILD_FAILED":r.errorCode,error:e.error??("string"==typeof a.error?a.error:r.error),startedAt:r.startedAt??new Date,finishedAt:c,snapshotJson:d}}),r.worktreeId&&l&&await t.worktree.updateMany({where:{id:r.worktreeId,OR:[{lastCheckedAt:null},{lastCheckedAt:{lt:u}}]},data:{codeStateHash:l,lastCheckedAt:u}}),Array.isArray(a.artifacts))for(let e of a.artifacts){let a=f(e,"build artifact");"string"==typeof a.relativePath&&"string"==typeof a.kind&&await t.buildArtifact.upsert({where:{buildId_relativePath:{buildId:r.id,relativePath:a.relativePath}},create:{id:(0,i.randomUUID)(),buildId:r.id,kind:a.kind,relativePath:a.relativePath,sizeBytes:"number"==typeof a.sizeBytes?a.sizeBytes:null,checksum:"string"==typeof a.checksum?a.checksum:null,metadataJson:JSON.stringify(a.metadata&&"object"==typeof a.metadata?a.metadata:{})},update:{}})}if(Array.isArray(a.scriptExecutions))for(let e of a.scriptExecutions){let i=f(e,"script execution");"string"==typeof i.phase&&"number"==typeof i.position&&await t.buildScriptExecution.updateMany({where:{buildId:r.id,phase:i.phase,position:i.position},data:{status:"string"==typeof i.status?i.status:"FAILED",exitCode:"number"==typeof i.exitCode?i.exitCode:null,durationMs:"number"==typeof i.durationMs?i.durationMs:null,causedBuildFailure:!0===i.causedBuildFailure,outputRelativePath:"string"==typeof i.outputRelativePath?i.outputRelativePath:null,error:"string"==typeof i.error?i.error:null}})}if(Array.isArray(a.reports))for(let e of a.reports){let i=e&&"object"==typeof e&&!Array.isArray(e)?e:{};await this.upsertReportProjection(t,r.id,e,"CODE_COVERAGE"===i.kind?"WORKTREE":"AUTOMATIC")}if(this.notifications&&("SUCCEEDED"===n||"FAILED"===n)){let e=f(m(d,{}),"build notification snapshot"),i=f(e.repository??{},"build repository snapshot"),a=f(e.configuration??{},"build configuration snapshot"),s=f(e.worktree??{},"build worktree snapshot"),o=["string"==typeof i.name?i.name:null,"string"==typeof a.name?a.name:null,"string"==typeof s.branch?s.branch:"string"==typeof s.folder?s.folder:null].filter(e=>!!e);h=await this.notifications.recordInTransaction(t,{dedupeKey:`ios-build:${r.id}:${n}`,typeKey:"SUCCEEDED"===n?"IOS_BUILD_SUCCEEDED":"IOS_BUILD_FAILED",title:"SUCCEEDED"===n?"iOS build succeeded":"iOS build failed",body:o.join(" · ")||`Build ${r.id}`,href:`/builds/${r.id}`,resourceKind:"BUILD",resourceId:r.id,worktreeId:r.worktreeId,highlightColor:r.worktree?.highlightColor??null})}}),this.publish(r.id),this.notifications?.created(h),"SUCCEEDED"===n&&await this.queueAutomaticExport(r.id,d)}async queueAutomaticExport(e,t){let r=f(m(t,{}),"build snapshot"),a=f(r.configuration??{},"build configuration snapshot");if(!0!==a.autoExport)return;let n=a.exportSettings;try{await this.exportArchive({buildId:e,requestId:"automatic",settings:n})}catch(a){let t=await (0,o.getPrismaClient)(),r=a instanceof Error?a.message:String(a);await t.buildExport.upsert({where:{buildId_requestId:{buildId:e,requestId:"automatic"}},create:{id:(0,i.randomUUID)(),buildId:e,requestId:"automatic",status:"FAILED",settingsSnapshotJson:JSON.stringify(n??{}),commandSummary:"Automatic archive export",error:r,finishedAt:new Date},update:{status:"FAILED",error:r,finishedAt:new Date}}),this.publish(e)}}async projectGeneratedReportCompletion(e){let t=f(m(e.payloadJson,{}),"build report payload");if("string"!=typeof t.buildId)return;let r=t.buildId,a=f(m(e.resultJson,{}),"build report result"),n=await (0,o.getPrismaClient)();await n.$transaction(async n=>{if(await this.upsertArtifacts(n,r,a.artifacts),a.report&&"object"==typeof a.report)await this.upsertReportProjection(n,r,a.report,"WORKTREE"===t.source?"WORKTREE":"MANUAL");else{let a="CODE_COVERAGE"===t.reportKind?"CODE_COVERAGE":"TEST_RESULTS";await n.buildReport.upsert({where:{buildId_kind:{buildId:r,kind:a}},create:{id:(0,i.randomUUID)(),buildId:r,kind:a,source:"WORKTREE"===t.source?"WORKTREE":"MANUAL",status:"FAILED",error:e.error||"Report generation failed",finishedAt:new Date},update:{status:"FAILED",error:e.error||"Report generation failed",finishedAt:new Date}})}}),this.publish(r)}async projectDeploymentCompletion(e){let t=await (0,o.getPrismaClient)(),r=await t.buildDeployment.findMany({where:{jobId:e.id}});if(!r.length)return;let i=f(m(e.resultJson,{}),"deployment result"),a=Array.isArray(i.deployments)?i.deployments:[];for(let i of r){let r=a.map(e=>f(e,"deployment outcome")).find(e=>e.id===i.id);await t.buildDeployment.update({where:{id:i.id},data:{status:"string"==typeof r?.status?r.status:I(e.status),error:"string"==typeof r?.error?r.error:e.error,outputRelativePath:"string"==typeof r?.outputRelativePath?r.outputRelativePath:null,startedAt:i.startedAt??new Date,finishedAt:new Date}})}for(let i of[...new Set(r.map(e=>e.transferId).filter(e=>!!e))]){let n=r.some(e=>{let t=a.map(e=>f(e,"deployment outcome")).find(t=>t.id===e.id);return t?.status!=="SUCCEEDED"});await t.buildArtifactTransfer.update({where:{id:i},data:{status:n||"SUCCEEDED"!==e.status?"FAILED":"SUCCEEDED",error:n||"SUCCEEDED"!==e.status?e.error||"One or more remote deployments failed":null,finishedAt:new Date}})}this.publish(r[0].buildId)}async projectExportCompletion(e){let t=await (0,o.getPrismaClient)(),r=await t.buildExport.findFirst({where:{jobId:e.id}});if(!r)return;let a=f(m(e.resultJson,{}),"export result");if(await t.buildExport.update({where:{id:r.id},data:{status:I(e.status),error:e.error??("string"==typeof a.error?a.error:null),outputRelativePath:"string"==typeof a.outputRelativePath?a.outputRelativePath:null,startedAt:r.startedAt??new Date,finishedAt:new Date}}),"SUCCEEDED"===e.status&&"string"==typeof a.outputRelativePath){let e=a.outputRelativePath;await t.$transaction(async t=>{await t.buildArtifact.upsert({where:{buildId_relativePath:{buildId:r.buildId,relativePath:e}},create:{id:(0,i.randomUUID)(),buildId:r.buildId,kind:"EXPORT",relativePath:e,sizeBytes:"number"==typeof a.sizeBytes?a.sizeBytes:null,metadataJson:JSON.stringify({exportId:r.id})},update:{}}),await this.upsertArtifacts(t,r.buildId,a.artifacts)})}this.publish(r.buildId)}}r()}catch(e){r(e)}},!1),224174,e=>e.a(async(t,r)=>{try{e.s([]);var i=e.i(669602);e.i(190714);var a=t([i]);[i]=a.then?(await a)():a,r()}catch(e){r(e)}},!1),483024,e=>{"use strict";var t=e.i(666680),r=e.i(986847),i=e.i(735255),a=e.i(243783);e.i(805422);var n=e.i(694355),s=e.i(661983);let o=["inputTokens","outputTokens","cacheCreationTokens","cacheReadTokens","totalTokens","totalCost"],l=["inputTokens","outputTokens","cacheCreationTokens","cacheReadTokens","cost"];function u(){return{daily:[],totals:c()}}function c(){return{inputTokens:0,outputTokens:0,cacheCreationTokens:0,cacheReadTokens:0,totalTokens:0,totalCost:0}}function d(e){return{modelName:e,inputTokens:0,outputTokens:0,cacheCreationTokens:0,cacheReadTokens:0,cost:0}}function h(e){return[...new Set(e)].sort()}function p(e){let t=[...e.values()].sort((e,t)=>e.period.localeCompare(t.period));return{daily:t,totals:function(e){let t=c();for(let r of e)for(let e of o)t[e]+=r[e];return t}(t)}}function m(e){return new Map(e.daily.map(e=>[e.period,e]))}function f(e){return new Map((e?.modelBreakdowns??[]).map(e=>[e.modelName,e]))}function g(e,t,r){return void 0===r?t+e:r<e?t+e-r:t}function y(e,t){let r=0;for(let i of e)r+=function(e,t){switch(t){case"totalCost":return e.cost;case"totalTokens":return e.inputTokens+e.outputTokens+e.cacheCreationTokens+e.cacheReadTokens;default:return e[t]}}(i,t);return r}function w(e,t){if(e)return Math.max(0,e[t]-y(e.modelBreakdowns,t))}function b(e,t){let r=m(e),i=m(t),a=h([...r.keys(),...i.keys()]),n=new Map;for(let e of a){let t=r.get(e),a=i.get(e),s=c();for(let e of o)s[e]=(t?.[e]??0)+(a?.[e]??0);let u=f(t),p=f(a),m=h([...u.keys(),...p.keys()]);n.set(e,{...s,agent:a?.agent??t?.agent??"all",period:e,metadata:{agents:h([...t?.metadata.agents??[],...a?.metadata.agents??[]])},modelsUsed:h([...t?.modelsUsed??[],...a?.modelsUsed??[]]),modelBreakdowns:m.map(e=>{let t=u.get(e),r=p.get(e),i=d(e);for(let e of l)i[e]=(t?.[e]??0)+(r?.[e]??0);return i})})}return p(n)}function E(e,t,r){let i=m(e),a=m(t),n=m(r),s=h([...i.keys(),...a.keys(),...n.keys()]),u=new Map;for(let e of s){let t=function(e,t,r,i){let a=f(e),n=f(t),s=f(r),u=h([...a.keys(),...n.keys(),...s.keys()]).flatMap(e=>{let t=function(e,t,r,i){let a=d(i);for(let i of l)a[i]=g(t?.[i]??0,e?.[i]??0,r?.[i]);return l.some(e=>a[e]>0)?a:null}(a.get(e),n.get(e),s.get(e),e);return t?[t]:[]}),p=c();for(let i of o){let a=w(e,i)??0,n=w(t,i)??0,s=w(r,i);p[i]=y(u,i)+g(n,a,s)}return o.some(e=>p[e]>0)||0!==u.length?{...p,agent:r?.agent??t?.agent??e?.agent??"all",period:i,metadata:{agents:h([...e?.metadata.agents??[],...t?.metadata.agents??[],...r?.metadata.agents??[]])},modelBreakdowns:u,modelsUsed:h([...e?.modelsUsed??[],...t?.modelsUsed??[],...r?.modelsUsed??[]])}:null}(i.get(e),a.get(e),n.get(e),e);t&&u.set(e,t)}let E=p(u);return{archived:E,live:r,combined:b(E,r)}}function S(e){return(0,r.parseCcusageReport)(JSON.parse(e))}let v=new Set(["SUCCEEDED","FAILED","CANCELLED","TIMED_OUT"]);e.s(["CcusageService",0,class{agentControlService;now;deadlineTimers;initialized;initializationPromise;completionObservers;constructor(e,t=()=>new Date){this.agentControlService=e,this.now=t,this.deadlineTimers=new Map,this.initialized=!1,this.initializationPromise=null,this.completionObservers=new Set}async initialize(){if(!this.initialized)return this.initializationPromise||(this.initializationPromise=this.restoreCollections().then(()=>{this.initialized=!0}).finally(()=>{this.initializationPromise=null})),this.initializationPromise}async restoreCollections(){let e=await (0,a.getPrismaClient)(),t=await e.ccusageCollection.findMany({where:{finishedAt:null},select:{id:!0}});await Promise.all(t.map(async({id:e})=>{await this.ensureJobs(e),await this.getCollection(e)}))}async collect(e){let t=await this.start(e);return"COMPLETED"===t.status?t:this.waitForCompletion(t.id)}async start(e){let r=e?.trim()||(0,t.randomUUID)();await this.ensureCollection(r);let i=await this.getCollection(r);if(!i)throw Error("ccusage collection disappeared");return i}registerCompletionObserver(e){return this.completionObservers.add(e),()=>this.completionObservers.delete(e)}async getCollection(e){let t=await this.loadCollection(e);if(!t)return null;null===t.finishedAt&&t.deadlineAt.getTime()<=this.now().getTime()&&(await this.timeoutMembersWithoutJobs(t),await this.agentControlService.timeoutCollectionJobs(e),t=await this.loadCollection(e)??t);let r=await this.snapshot(t);if("COMPLETED"===r.status&&null===t.finishedAt){let t=this.now(),i=await (0,a.getPrismaClient)(),n=await i.ccusageCollection.updateMany({where:{id:e,finishedAt:null},data:{finishedAt:t}});r.finishedAt=t.toISOString(),this.clearDeadline(e),n.count>0&&await this.notifyCompletion(r)}else"COLLECTING"===r.status&&this.scheduleDeadline(t);return r}async clearHistory(){return(await (0,a.getPrismaClient)()).$transaction(async e=>{let t=this.now(),r=await e.ccusageHistory.deleteMany();return await e.sidebarUsageSummary.deleteMany(),await e.ccusageHistoryState.upsert({where:{id:"default"},create:{id:"default",clearedAt:t},update:{clearedAt:t}}),r.count})}async *subscribe(e){let t=s.agentEventBus.iterate((0,s.ccusageCollectionChangedTopic)(e));try{let r=await this.getCollection(e);for(r&&(yield r);;){if((await t.next()).done)return;let r=await this.getCollection(e);r&&(yield r)}}finally{await t.return?.()}}async ensureCollection(e){let t=await (0,a.getPrismaClient)(),i=await t.ccusageCollection.findUnique({where:{id:e},select:{id:!0}});if(!i){let a=await this.agentControlService.listAgents();try{i=await t.ccusageCollection.create({data:{id:e,deadlineAt:new Date(this.now().getTime()+15e4),agents:{create:a.map(e=>{var t;return{agentId:e.id,initialStatus:(t=this.now().getTime(),null!==e.lastSeenAt&&t-e.lastSeenAt.getTime()<=(0,n.agentOnlineWindowMs)(e)&&null===e.disconnectedAt?(function(e){try{let t=JSON.parse(e.capabilitiesJson);return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}catch{return[]}})(e).includes(r.CCUSAGE_REPORT_JOB_KIND)?"QUEUING":"UNSUPPORTED":"OFFLINE")}})}},select:{id:!0}}),this.publish(e)}catch(r){if(!(i=await t.ccusageCollection.findUnique({where:{id:e},select:{id:!0}})))throw r}}await this.ensureJobs(e);let s=await this.getCollection(e);if(s?.status==="COLLECTING"){let r=await t.ccusageCollection.findUnique({where:{id:e},select:{id:!0,deadlineAt:!0,finishedAt:!0}});r&&this.scheduleDeadline(r)}}async ensureJobs(e){let t=await (0,a.getPrismaClient)(),i=await t.ccusageCollection.findUnique({where:{id:e},select:{deadlineAt:!0,finishedAt:!0}});if(!i||i.finishedAt||i.deadlineAt.getTime()<=this.now().getTime())return;let n=await t.ccusageCollectionAgent.findMany({where:{collectionId:e,initialStatus:"QUEUING"},select:{agentId:!0}}),s=new Set((await t.agentJob.findMany({where:{ccusageCollectionId:e},select:{agentId:!0}})).map(({agentId:e})=>e));await Promise.all(n.filter(({agentId:e})=>!s.has(e)).map(async({agentId:i})=>{try{await this.agentControlService.createJob({agentId:i,kind:r.CCUSAGE_REPORT_JOB_KIND,payload:{},idempotencyKey:`ccusage:${e}`,timeoutSeconds:120,ccusageCollectionId:e})}catch(r){await t.ccusageCollectionAgent.update({where:{collectionId_agentId:{collectionId:e,agentId:i}},data:{initialStatus:"FAILED",error:r instanceof Error?r.message:String(r)}}),this.publish(e)}}))}async waitForCompletion(e){let t=s.agentEventBus.iterate((0,s.ccusageCollectionChangedTopic)(e));try{for(;;){let r=await this.getCollection(e);if(!r)throw Error("ccusage collection disappeared");if("COMPLETED"===r.status)return r;let i=Math.max(1,new Date(r.deadlineAt).getTime()-this.now().getTime()+25);await Promise.race([t.next(),new Promise(e=>setTimeout(e,i))])}}finally{await t.return?.()}}async loadCollection(e){return(await (0,a.getPrismaClient)()).ccusageCollection.findUnique({where:{id:e},include:{agents:{include:{agent:!0}},jobs:!0}})}async timeoutMembersWithoutJobs(e){let t=new Set(e.jobs.map(({agentId:e})=>e)),r=e.agents.filter(({agentId:e,initialStatus:r})=>"QUEUING"===r&&!t.has(e)).map(({agentId:e})=>e);if(0===r.length)return;let i=await (0,a.getPrismaClient)();(await i.ccusageCollectionAgent.updateMany({where:{collectionId:e.id,agentId:{in:r},initialStatus:"QUEUING"},data:{initialStatus:"TIMED_OUT"}})).count>0&&this.publish(e.id)}async snapshot(e){let t=new Map(e.jobs.map(e=>[e.agentId,e])),a=e.agents.map(e=>(function(e,t){let i={agent:e.agent,jobId:t?.id??null};if("QUEUING"!==e.initialStatus)return{progress:{...i,status:e.initialStatus,error:e.error}};if(!t)return{progress:{...i,status:"QUEUING",error:e.error}};if("SUCCEEDED"!==t.status)return{progress:{...i,status:t.status,error:t.error}};try{let e=(0,r.parseCcusageJobResult)(null===t.resultJson?null:JSON.parse(t.resultJson));return{progress:{...i,status:"SUCCEEDED",error:null},report:e.report}}catch(e){return{progress:{...i,status:"INVALID",error:e instanceof Error?e.message:String(e)}}}})(e,t.get(e.agentId))),n=a.map(({progress:e})=>e),s=n.filter(({status:e})=>"OFFLINE"!==e&&"UNSUPPORTED"!==e),o=s.filter(({status:e})=>"INVALID"===e||v.has(e)),l=a.flatMap(({progress:r,report:i})=>i&&r.jobId?[{agent:{id:r.agent.id,name:r.agent.name,hostname:r.agent.hostname},report:i,jobId:r.jobId,observedAt:t.get(r.agent.id)?.startedAt??t.get(r.agent.id)?.createdAt??e.createdAt}]:[]);await this.persistReports(l);let u=await this.loadHistoryReports(),c=new Set(u.reports.map(({agent:e})=>e.id)),d=[...u.reports,...l.filter(({agent:e})=>!c.has(e.id))];return{id:e.id,status:o.length===s.length?"COMPLETED":"COLLECTING",createdAt:e.createdAt.toISOString(),deadlineAt:e.deadlineAt.toISOString(),finishedAt:e.finishedAt?.toISOString()??null,progress:{eligibleCount:s.length,finishedCount:o.length,successfulCount:s.filter(({status:e})=>"SUCCEEDED"===e).length,agents:n},aggregate:(0,i.aggregateUsage)(d),liveAggregate:(0,i.aggregateUsage)(l),hasStoredHistory:u.hasStoredHistory}}async persistReports(e){if(0===e.length)return;let t=await (0,a.getPrismaClient)();for(let r of e)await t.$transaction(async e=>{let t=await e.ccusageHistoryState.findUnique({where:{id:"default"},select:{clearedAt:!0}});if(t?.clearedAt&&r.observedAt<=t.clearedAt)return;let i=await e.ccusageHistory.findUnique({where:{agentId:r.agent.id}});if(null!==i&&(i.lastJobId===r.jobId||!(i.lastObservedAt<r.observedAt)))return;let a=i?E(S(i.archivedReportJson),S(i.lastLiveReportJson),r.report):E(u(),u(),r.report),n={agentName:r.agent.name,hostname:r.agent.hostname,archivedReportJson:JSON.stringify(a.archived),lastLiveReportJson:JSON.stringify(a.live),lastObservedAt:r.observedAt,lastJobId:r.jobId};await e.ccusageHistory.upsert({where:{agentId:r.agent.id},create:{agentId:r.agent.id,...n},update:n})})}async loadHistoryReports(){let e=await (0,a.getPrismaClient)(),t=await e.ccusageHistory.findMany();return{hasStoredHistory:t.length>0,reports:t.flatMap(e=>{try{return[{agent:{id:e.agentId,name:e.agentName,hostname:e.hostname},report:b(S(e.archivedReportJson),S(e.lastLiveReportJson))}]}catch(t){return console.error(`Could not read ccusage history for agent ${e.agentId}:`,t instanceof Error?t.message:t),[]}})}}async notifyCompletion(e){for(let t of this.completionObservers)try{await t(e)}catch(e){console.error("ccusage completion observer failed:",e instanceof Error?e.message:e)}}scheduleDeadline(e){if(e.finishedAt||this.deadlineTimers.has(e.id))return;let t=setTimeout(()=>{this.deadlineTimers.delete(e.id),this.expire(e.id)},Math.max(0,e.deadlineAt.getTime()-this.now().getTime()));t.unref?.(),this.deadlineTimers.set(e.id,t)}async expire(e){try{await this.agentControlService.timeoutCollectionJobs(e),await this.getCollection(e),this.publish(e)}catch(t){console.error(`Could not expire ccusage collection ${e}:`,t instanceof Error?t.message:t)}}clearDeadline(e){let t=this.deadlineTimers.get(e);t&&clearTimeout(t),this.deadlineTimers.delete(e)}publish(e){s.agentEventBus.publish((0,s.ccusageCollectionChangedTopic)(e),{ccusageCollectionChanged:{id:e}})}}],483024)},121717,e=>{"use strict";e.i(483024),e.s([])},764892,e=>{"use strict";var t=e.i(666680),r=e.i(937121),i=e.i(243783),a=e.i(988349);e.i(805422);var n=e.i(661983),s=e.i(694355);let o=["ANY_AGENT_HOME","SPECIFIC_AGENT_HOME","ANY_WORKTREE","REPOSITORY_WORKTREE"],l=["NEVER","ON_FAILURE","ALWAYS"],u=["EXCLUSIVE","NON_EXCLUSIVE","EXCLUDED"],c=["QUEUED","RUNNING","RESTARTING","CANCELLING"],d=["SUCCEEDED","FAILED","CANCELLED"],h=["SUCCEEDED","FAILED","CANCELLED","TIMED_OUT"],p=e=>!!(e&&!h.includes(e.status)),m="aide.command.export",f=()=>({targetAgent:!0,repositories:{include:{repository:!0},orderBy:[{createdAt:"asc"},{repositoryId:"asc"}]}}),g=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}},y=["QUEUED","RESTARTING"],w=(e,t)=>e.queuedAt.getTime()-t.queuedAt.getTime()||e.id.localeCompare(t.id);function b(e,t,r){let i=t.trim().toUpperCase();if(!e.includes(i))throw Error(`${r} is not supported`);return i}function E(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 S(e,t){if(!e||"object"!=typeof e||Array.isArray(e))throw Error(`${t} must be an object`);return e}let v=e=>"string"==typeof e&&e.trim()?e.trim():null;function I(e){n.agentEventBus.publish(n.COMMANDS_CHANGED_TOPIC,{commandsChanged:e})}function A(e){n.agentEventBus.publish(n.COMMAND_RUNS_CHANGED_TOPIC,{commandRunsChanged:e}),n.agentEventBus.publish((0,n.commandRunChangedTopic)(e.id),{commandRunChanged:e}),n.agentEventBus.publish(n.SIDEBAR_STATUS_CHANGED_TOPIC,{sidebarStatusChanged:!0})}e.s(["CommandsService",0,class{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(r.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,i.getPrismaClient)();return(await t.commandDefinition.findMany({where:e?{}:{archivedAt:null},include:f(),orderBy:[{archivedAt:"asc"},{name:"asc"}]})).map(g)}async getDefinition(e){let t=await (0,i.getPrismaClient)(),r=await t.commandDefinition.findUnique({where:{id:e},include:f()});return r?g(r):null}normalizeDefinition(e){let t=b(o,e.targetKind,"Target scope"),r=b(l,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 c=b(u,e.concurrency??"NON_EXCLUSIVE","Concurrency");return{name:E(e.name,"Name",120),description:(e.description??"").trim().slice(0,2e3),script:E(e.script,"Script",1e6),targetKind:t,targetAgentId:e.targetAgentId??null,targetRepositoryIds:s,restartPolicy:r,restartLimit:i,concurrency:c,blocksGitOperations:"EXCLUSIVE"===c||(e.blocksGitOperations??!1),quickActionEnabled:e.quickActionEnabled??!1,quickActionIconKey:E(e.quickActionIconKey??"terminal","Quick action icon",40),quickActionButtonVariant:E(e.quickActionButtonVariant??"default","Quick action style",40),notificationsEnabled:e.notificationsEnabled??!0}}async assertRepositoriesExist(e){if(!e.length)return;let t=await (0,i.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 r=await (0,i.getPrismaClient)(),{targetRepositoryIds:a,...n}=this.normalizeDefinition(e);await this.assertRepositoriesExist(a);let s=g(await r.commandDefinition.create({data:{id:(0,t.randomUUID)(),...n,repositories:{create:a.map(e=>({repositoryId:e}))}},include:f()}));return I(s),s}async updateDefinition(e,t){let r=await (0,i.getPrismaClient)(),{targetRepositoryIds:a,...n}=this.normalizeDefinition(t);await this.assertRepositoriesExist(a);let s=g(await r.commandDefinition.update({where:{id:e},data:{...n,repositories:{deleteMany:{},create:a.map(e=>({repositoryId:e}))}},include:f()}));return I(s),s}async deleteDefinition(e){let t=await (0,i.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}}),I(r),!0}async exportDefinition(e){let t=await this.getDefinition(e);if(!t)throw Error("Command not found");return{format:m,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=b(o,v(e.targetKind)??"ANY_AGENT_HOME","Target scope"),r=await (0,i.getPrismaClient)();if("SPECIFIC_AGENT_HOME"===t){let i=v(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=>S(e,"Exported target repository")):[];if(i.length){let e=await r.codebaseRepository.findMany({where:{OR:i.flatMap(e=>{let t=v(e.canonicalOrigin),r=v(e.name);return[...t?[{canonicalOrigin:t}]:[],...r?[{name:r}]:[]]})},orderBy:{id:"asc"}}),a=i.map(t=>{let r=v(t.canonicalOrigin),i=v(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=v(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=S(t,"Command import"),i=r.format===m?S(r.command,"Exported command"):r,{widened:a,...n}=await this.resolveImportTarget(i),s=e.name?.trim()||v(i.name);if(!s)throw Error("Name is required");let o=v(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:v(i.restartPolicy)??"NEVER",restartLimit:null===i.restartLimit||"number"==typeof i.restartLimit?i.restartLimit:3,concurrency:v(i.concurrency)??"NON_EXCLUSIVE",blocksGitOperations:!0===i.blocksGitOperations,quickActionEnabled:!a&&!0===i.quickActionEnabled,quickActionIconKey:v(i.quickActionIconKey)??"terminal",quickActionButtonVariant:v(i.quickActionButtonVariant)??"default",notificationsEnabled:!1!==i.notificationsEnabled})}async archiveDefinition(e,t){let r=await (0,i.getPrismaClient)(),a=g(await r.commandDefinition.update({where:{id:e},data:{archivedAt:t?new Date:null},include:f()}));return I(a),a}async eligibleForAgent(e){let t=await (0,i.getPrismaClient)();return(await t.commandDefinition.findMany({where:{archivedAt:null,OR:[{targetKind:"ANY_AGENT_HOME"},{targetKind:"SPECIFIC_AGENT_HOME",targetAgentId:e}]},include:f(),orderBy:{name:"asc"}})).map(g)}async eligibleForWorktree(e){let t=await (0,i.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:f(),orderBy:{name:"asc"}})).map(g)}async listRuns(e){let t=await (0,i.getPrismaClient)(),r=Math.max(1,Math.min(e.first??50,200)),a=e.search?.trim(),n={...e.includeArchived?{}:{archivedAt:null},...e.agentId?{agentId:e.agentId}:{},...e.worktreeId?{worktreeId:e.worktreeId}:{},...e.statuses?.length?{status:{in:e.statuses}}:{},...a?{OR:[{snapshotName:{contains:a}},{agentName:{contains:a}},{worktreePath:{contains:a}}]}:{}},[s,o]=await Promise.all([t.commandRun.findMany({where:n,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:n})]),l=s.length>r,u=s.slice(0,r);return{nodes:u,totalCount:o,pageInfo:{hasNextPage:l,endCursor:u.at(-1)?.id??null}}}async getRun(e){return(await (0,i.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,i.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 a=r.attempts[0],n=!!(r.agent?.lastSeenAt&&!r.agent.disconnectedAt&&Date.now()-r.agent.lastSeenAt.getTime()<=(0,s.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(w),n=[...e.peers.filter(e=>!e.holdingTarget),...t.holdingTarget?[]:[t]].sort(w),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),u=i.filter(l),c=o.filter(l),d=t.stopRequested||!y.includes(t.status)?"NOT_QUEUED":t.holdingTarget?e.agentOnline?"WAITING_FOR_AGENT":"AGENT_OFFLINE":e.predecessorPending?"WAITING_FOR_PREDECESSOR":e.restartPending?"RESTART_DELAY":u.length?"TARGET_BUSY":c.length?"QUEUED_BEHIND":e.agentOnline?"READY":"AGENT_OFFLINE",h=new Set("TARGET_BUSY"===d||"QUEUED_BEHIND"===d?[...u,...c].map(e=>e.id):[]);return{reason:d,position:s<0?0:s+1,waitingCount:n.length,entries:[...a,...n].map(e=>({...e,blocking:h.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:!!(a?.agentJobId&&!a.completionProcessedAt)},peers:"EXCLUDED"===r.snapshotConcurrency?[]:await this.targetPeers(r),agentOnline:n,predecessorPending:!!(r.predecessor&&!d.includes(r.predecessor.status)),restartPending:!!("RESTARTING"===r.status&&r.nextRestartAt&&r.nextRestartAt.getTime()>Date.now())})}async listOutput(e,t=0,r=-1,a=1e3){let n=await (0,i.getPrismaClient)();return a<1?[]:n.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(a,5e3))})}async resolveTarget(e,t){let r=await (0,i.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 a=await r.worktree.findUnique({where:{id:t.worktreeId},include:{codebase:{include:{agent:!0,repository:!0}}}});if(!a||a.missingAt)throw Error("Worktree is unavailable");if("REPOSITORY_WORKTREE"===e.targetKind&&!e.repositories.some(e=>e.repositoryId===a.codebase.repositoryId))throw Error("This command is not eligible for the selected repository");return this.requireCapability(a.codebase.agent.capabilitiesJson),{agent:a.codebase.agent,worktree:a}}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(r.COMMAND_RUN_JOB_KIND))throw Error("The selected agent must be upgraded before it can run commands")}async startRun(e){let r,a=await (0,i.getPrismaClient)(),n=e.idempotencyKey?.trim()||(0,t.randomUUID)(),s=await a.commandRun.findUnique({where:{idempotencyKey:n}});if(s)return this.getRun(s.id);let o=await a.commandDefinition.findUnique({where:{id:e.commandId},include:f()});if(!o||o.archivedAt)throw Error("Command not found");let{agent:l,worktree:u}=await this.resolveTarget(o,e);try{r=await a.$transaction(async r=>{let i=await r.commandRunNumberSequence.upsert({where:{id:"default"},create:{id:"default",nextValue:1},update:{nextValue:{increment:1}}});return r.commandRun.create({data:{id:(0,t.randomUUID)(),displayNumber:i.nextValue,commandId:o.id,idempotencyKey:n,origin:(e.origin??"MANUAL").trim().toUpperCase(),snapshotName:o.name,snapshotDescription:o.description,snapshotScript:o.script,snapshotTargetKind:o.targetKind,snapshotRestartPolicy:o.restartPolicy,snapshotRestartLimit:o.restartLimit,snapshotConcurrency:o.concurrency,snapshotBlocksGitOperations:o.blocksGitOperations||!0===e.blocksGitOperations,snapshotNotificationsEnabled:o.notificationsEnabled,snapshotJson:JSON.stringify(g(o)),agentId:l.id,worktreeId:u?.id??null,agentName:l.name,agentHostname:l.hostname,worktreePath:u?.folder??null,worktreeBranch:u?.branch??null}})})}catch(t){let e=await a.commandRun.findUnique({where:{idempotencyKey:n}});if(!e)throw t;return this.getRun(e.id)}return A(r),await this.dispatch(r.id),this.getRun(r.id)}async startCustomRun(e){let r,a=await (0,i.getPrismaClient)(),n=e.idempotencyKey?.trim()||(0,t.randomUUID)(),s=await a.commandRun.findUnique({where:{idempotencyKey:n}});if(s)return this.getRun(s.id);let o=E(e.script,"Script",1e6),l=e.agentId&&!e.worktreeId?"ANY_AGENT_HOME":e.worktreeId&&!e.agentId?"ANY_WORKTREE":null;if(!l)throw Error("A custom command requires exactly one agent-home or worktree target");let{agent:u,worktree:c}=await this.resolveTarget({targetKind:l,targetAgentId:null,repositories:[]},e),d={name:"Custom command",description:"",script:o,targetKind:l,restartPolicy:"NEVER",restartLimit:null,concurrency:"NON_EXCLUSIVE",blocksGitOperations:!0===e.blocksGitOperations,notificationsEnabled:!0};try{r=await a.$transaction(async r=>{let i=await r.commandRunNumberSequence.upsert({where:{id:"default"},create:{id:"default",nextValue:1},update:{nextValue:{increment:1}}});return r.commandRun.create({data:{id:(0,t.randomUUID)(),displayNumber:i.nextValue,commandId:null,idempotencyKey:n,origin:(e.origin??"MANUAL").trim().toUpperCase(),status:"QUEUED",snapshotName:d.name,snapshotDescription:d.description,snapshotScript:d.script,snapshotTargetKind:d.targetKind,snapshotRestartPolicy:d.restartPolicy,snapshotRestartLimit:d.restartLimit,snapshotConcurrency:d.concurrency,snapshotBlocksGitOperations:d.blocksGitOperations,snapshotNotificationsEnabled:d.notificationsEnabled,snapshotJson:JSON.stringify(d),agentId:u.id,worktreeId:c?.id??null,agentName:u.name,agentHostname:u.hostname,worktreePath:c?.folder??null,worktreeBranch:c?.branch??null}})})}catch(t){let e=await a.commandRun.findUnique({where:{idempotencyKey:n}});if(!e)throw t;return this.getRun(e.id)}A(r);try{await this.dispatch(r.id)}catch(e){throw await this.failDispatch(r.id,e instanceof Error?e.message:String(e)),e}return this.getRun(r.id)}async targetPeers(e){let t=await (0,i.getPrismaClient)();return(await t.commandRun.findMany({where:{id:{not:e.id},status:{in:[...c]},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 n=await (0,i.getPrismaClient)(),s=await n.commandRun.findUnique({where:{id:e},include:{agent:!0,worktree:{include:{codebase:!0}},attempts:!0}});if(!s||s.stopRequested)return;if(!s.agentId||!s.agent)return void await this.failDispatch(s.id,"The command agent is no longer available");if(s.predecessorRunId){let e=await n.commandRun.findUnique({where:{id:s.predecessorRunId},select:{status:!0}});if(e&&!d.includes(e.status))return}if(new Set(["ANY_WORKTREE","REPOSITORY_WORKTREE"]).has(s.snapshotTargetKind)&&(!s.worktreeId||!s.worktree||s.worktree.missingAt))return void await this.failDispatch(s.id,"The command worktree is no longer available");if(s.worktree&&s.worktree.codebase.agentId!==s.agentId)return void await this.failDispatch(s.id,"The worktree is no longer assigned to the command agent");try{this.requireCapability(s.agent.capabilitiesJson)}catch(e){await this.failDispatch(s.id,e instanceof Error?e.message:String(e));return}let o=s.attempts.reduce((e,t)=>!e||t.attempt>e.attempt?t:e,null);if(!(o?.agentJobId&&!o.completionProcessedAt)&&!await this.admitRun(s))return;let l=!o||o.agentJobId||o.completionProcessedAt||o.finishedAt?(o?.attempt??0)+1:o.attempt,u=o?.attempt===l?o:await n.commandRunAttempt.findUnique({where:{runId_attempt:{runId:e,attempt:l}}});if(!u)try{u=await n.commandRunAttempt.create({data:{id:(0,t.randomUUID)(),runId:e,attempt:l}})}catch(t){if(!(u=await n.commandRunAttempt.findUnique({where:{runId_attempt:{runId:e,attempt:l}}})))throw t}if(!u.agentJobId){let e;try{e=await this.agentControl.createJob({agentId:s.agentId,kind:r.COMMAND_RUN_JOB_KIND,payload:{commandRunId:s.id,attemptId:u.id,targetKind:s.worktreeId?"WORKTREE":"AGENT_HOME",cwd:s.worktree?.folder??null,script:s.snapshotScript},idempotencyKey:`command-run:${s.id}:attempt:${l}`,timeoutSeconds:0,worktreeId:s.worktreeId,codebaseId:s.worktree?.codebaseId??null,visibility:"SYSTEM",blocksGitOperations:s.snapshotBlocksGitOperations})}catch(e){if(!(0,a.isCodebaseBusyError)(e))throw e;return}u=await n.commandRunAttempt.update({where:{id:u.id},data:{agentJobId:e.id,status:e.status}})}A(await n.commandRun.update({where:{id:s.id},data:{status:"RUNNING"===u.status?"RUNNING":"QUEUED",startedAt:"RUNNING"===u.status?s.startedAt??new Date:null,nextRestartAt:null,error:null}}))}async failDispatch(e,t){let r=await (0,i.getPrismaClient)(),a=await r.commandRun.update({where:{id:e},data:{status:"FAILED",error:t,finishedAt:new Date,nextRestartAt:null},include:{worktree:{select:{highlightColor:!0}}}});A(a),await this.notifyFinishedRun(a)}async terminateRun(e){let t=await (0,i.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(d.includes(r.status))return r;let a=await t.commandRun.update({where:{id:e},data:{stopRequested:!0,status:"CANCELLING",nextRestartAt:null}}),n=r.attempts[0]?.agentJobId;return p(n?await this.agentControl.cancelJob(n):null)||await this.finishCancelled(e),A(a),this.getRun(e)}async rerun(e){let r=await (0,i.getPrismaClient)(),a=await r.commandRun.findUnique({where:{id:e}});if(!a)throw Error("Command run not found");let n=await r.commandRun.findUnique({where:{predecessorRunId:a.id}});if(n)return this.getRun(n.id);let s=await r.$transaction(async e=>{let r=await e.commandRunNumberSequence.upsert({where:{id:"default"},create:{id:"default",nextValue:1},update:{nextValue:{increment:1}}});return e.commandRun.create({data:{id:(0,t.randomUUID)(),displayNumber:r.nextValue,commandId:a.commandId,idempotencyKey:`rerun:${a.id}:${(0,t.randomUUID)()}`,origin:"RERUN",snapshotName:a.snapshotName,snapshotDescription:a.snapshotDescription,snapshotScript:a.snapshotScript,snapshotTargetKind:a.snapshotTargetKind,snapshotRestartPolicy:a.snapshotRestartPolicy,snapshotRestartLimit:a.snapshotRestartLimit,snapshotConcurrency:a.snapshotConcurrency,snapshotBlocksGitOperations:a.snapshotBlocksGitOperations,snapshotNotificationsEnabled:a.snapshotNotificationsEnabled,snapshotJson:a.snapshotJson,agentId:a.agentId,worktreeId:a.worktreeId,agentName:a.agentName,agentHostname:a.agentHostname,worktreePath:a.worktreePath,worktreeBranch:a.worktreeBranch,predecessorRunId:a.id}})});return A(s),d.includes(a.status)?await this.dispatch(s.id):await this.terminateRun(a.id),this.getRun(s.id)}async archiveRuns(e,t){let r=await (0,i.getPrismaClient)();for(let i of(await r.commandRun.updateMany({where:{id:{in:e},status:{in:[...d]}},data:{archivedAt:t?new Date:null}}),e)){let e=await r.commandRun.findUnique({where:{id:i}});e&&A(e)}return!0}async deleteRuns(e){let t=await (0,i.getPrismaClient)();return(await t.commandRun.deleteMany({where:{id:{in:e},status:{in:[...d]}}})).count}async appendOutput(e,a,s,o){if(!o.length||o.length>r.MAX_COMMAND_OUTPUT_BATCH_CHUNKS)throw Error(`Output batches must contain 1 to ${r.MAX_COMMAND_OUTPUT_BATCH_CHUNKS} chunks`);let l=await (0,i.getPrismaClient)(),u=await l.commandRunAttempt.findUnique({where:{id:s},include:{run:!0}});if(!u||u.agentJobId!==a||u.run.agentId!==e)throw Error("Command attempt not found for this agent job");let c=o.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(c.map(e=>l.commandRunOutputChunk.upsert({where:{attemptId_sequence:{attemptId:s,sequence:e.sequence}},create:{id:(0,t.randomUUID)(),attemptId:s,...e},update:{}})));let d=await l.commandRunOutputChunk.findMany({where:{attemptId:s,sequence:{in:c.map(e=>e.sequence)}},orderBy:{sequence:"asc"}});for(let e of d){let t={...e,runId:u.runId,attemptNumber:u.attempt};n.agentEventBus.publish((0,n.commandRunOutputTopic)(u.runId),{commandRunOutputAdded:t}),n.agentEventBus.publish(n.COMMAND_RUN_OUTPUT_CHANGED_TOPIC,{commandRunOutputAdded:t})}return d}async finishCancelled(e){let t=await (0,i.getPrismaClient)();A(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,i.getPrismaClient)(),a=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(a)}catch(e){console.error("Command run notification failed:",e)}}async handleAttemptCompletion(e){let t=await (0,i.getPrismaClient)(),r=await t.commandRunAttempt.findUnique({where:{agentJobId:e.id},include:{run:!0,agentJob:!0}});if(!r||r.completionProcessedAt)return;let a=new Date,n=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:n.exitCode??null,signal:n.signal??null,error:e.error,startedAt:r.agentJob?.startedAt??r.startedAt,finishedAt:r.agentJob?.finishedAt??a,completionProcessedAt:a}})).count)return;if(r.run.stopRequested||"CANCELLED"===e.status)return void await this.finishCancelled(r.runId);let s="SUCCEEDED"===e.status&&0===n.exitCode,o=b(l,r.run.snapshotRestartPolicy,"Restart policy"),u=r.agentJob?.startedAt??r.createdAt,c=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:o,limit:r.run.snapshotRestartLimit,restartCount:r.run.restartCount,durationMs:a.getTime()-u.getTime(),clean:s,manualStop:r.run.stopRequested});if(c.restart)return void A(await t.commandRun.update({where:{id:r.runId},data:{status:"RESTARTING",restartCount:c.restartCount,nextRestartAt:new Date(a.getTime()+1e3),exitCode:n.exitCode??null,signal:n.signal??null,error:e.error}}));let d=await t.commandRun.update({where:{id:r.runId},data:{status:s?"SUCCEEDED":"FAILED",exitCode:n.exitCode??null,signal:n.signal??null,error:e.error??(c.exhausted?"Restart limit reached":s?null:"Command failed"),finishedAt:a,nextRestartAt:null},include:{worktree:{select:{highlightColor:!0}}}});A(d),await this.notifyFinishedRun(d)}async reconcile(e={}){let t=await (0,i.getPrismaClient)(),r=new Date;for(let i of(await t.commandRun.findMany({where:{status:{in:[...c]},...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&&p(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&&A(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)}}}])},344518,e=>{"use strict";e.i(764892),e.s([])},508813,e=>{"use strict";e.i(805422);var t=e.i(694355);e.s(["diskSpaceSessionData",0,function(e,r,i=null){let a=[...r.volumes].filter(e=>e.monitored).sort((e,t)=>e.freeBytes-t.freeBytes||e.id.localeCompare(t.id))[0],n=a&&a.totalBytes>0?a.freeBytes/a.totalBytes*100:null,s=null===r.agent.disconnectedAt&&null!==r.agent.lastSeenAt&&Date.now()-r.agent.lastSeenAt.getTime()<=(0,t.agentOnlineWindowMs)(r.agent);return{agent:{id:r.agent.id,name:r.agent.name,hostname:r.agent.hostname,connected:s,diskTotalBytes:r.agent.diskTotalBytes,diskFreeBytes:r.agent.diskFreeBytes},codebase:{agentId:r.agent.id},disk:{enabled:r.enabled,status:r.status,pressureMode:r.pressureMode,manualPressureMode:r.manualPressureMode,automaticPressureMode:r.automaticPressureMode,lastReportedAt:r.lastReportedAt,lastError:r.lastError,warnings:[...r.warnings],monitoredVolumeId:a?.id??null,freeBytes:a?.freeBytes??null,totalBytes:a?.totalBytes??null,freeGiB:a?a.freeBytes/0x40000000:null,freePercent:n,usedPercent:null===n?null:100-n,effectiveThresholdBytes:a?.effectiveThresholdBytes??null,normalThresholdGiB:e.normalThresholdGiB,pressureThresholdGiB:e.pressureThresholdGiB,pollIntervalSeconds:e.pollIntervalSeconds,staleAfterSeconds:e.staleAfterSeconds,changeReason:i,volumes:r.volumes.map(e=>({...e}))}}},"diskSpaceStateCursor",0,function(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}}])},599600,e=>{"use strict";var t=e.i(666680),r=e.i(885418),i=e.i(586589),a=e.i(243783);e.i(805422);var n=e.i(694355),s=e.i(661983),o=e.i(504173),l=e.i(518733),u=e.i(508813);function c(e){try{let t=JSON.parse(e??"[]");return Array.isArray(t)?t:[]}catch{return[]}}function d(e,t){if(!Number.isFinite(e)||e<=0||e>1e6)throw Error(`${t} must be a positive finite GiB value`);return e}e.s(["DiskSpaceService",0,class{agentControl;constructor(e){this.agentControl=e,this.agentControl.registerCompletionObserver(e=>this.observeCompletion(e))}async settings(){let e=await (0,a.getPrismaClient)(),t=await e.diskSpaceSettings.upsert({where:{id:"default"},create:{id:"default",normalThresholdGiB:i.DEFAULT_DISK_SPACE_THRESHOLD_GIB,pressureThresholdGiB:i.DEFAULT_DISK_SPACE_PRESSURE_THRESHOLD_GIB},update:{}});return{normalThresholdGiB:t.normalThresholdGiB,pressureThresholdGiB:t.pressureThresholdGiB,pollIntervalSeconds:i.DISK_SPACE_POLL_INTERVAL_SECONDS,staleAfterSeconds:i.DISK_SPACE_STALE_AFTER_SECONDS}}async updateSettings(e){let t=d(e.normalThresholdGiB,"Normal disk threshold"),r=d(e.pressureThresholdGiB,"Pressure disk threshold");if(r>=t)throw Error("Pressure disk threshold must be lower than the normal threshold");let i=await (0,a.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,a.getPrismaClient)(),[r,n,s]=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:n?.enabled??!0,pollIntervalSeconds:i.DISK_SPACE_POLL_INTERVAL_SECONDS,baseRepoDirectory:r.baseRepoDirectory,derivedDataLocationMode:r.derivedDataLocationMode,derivedDataPath:r.derivedDataPath,worktrees:s}}async report(e,t){let r=(0,i.parseAgentDiskSpaceReport)(t),n=await (0,a.getPrismaClient)(),[s,l]=await Promise.all([n.agent.findUnique({where:{id:e}}),n.worktree.findMany({where:{missingAt:null,codebase:{agentId:e}},include:{codebase:{select:{agentId:!0}}}})]);if(!s)throw Error("Agent not found");let u=new Date(r.observedAt),c=r.entries.map(e=>{let t=e.workspacePath?l.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,o.worktreeDisplayPath)(t.folder,s.baseRepoDirectory):null}});await n.agentDiskSpaceState.upsert({where:{agentId:e},create:{agentId:e,volumesJson:JSON.stringify(r.volumes),entriesJson:JSON.stringify(c),warningsJson:JSON.stringify(r.warnings),lastReportedAt:u,lastError:null},update:{volumesJson:JSON.stringify(r.volumes),entriesJson:JSON.stringify(c),warningsJson:JSON.stringify(r.warnings),lastReportedAt:u,lastError:null}}),this.publish(e,"REPORT_RECEIVED"),this.reconcileAgent(e)}async overview(){let e=await (0,a.getPrismaClient)();await e.derivedDataCleanupLease.deleteMany({where:{jobId:null,expiresAt:{lte:new Date}}});let[t,r,n]=await Promise.all([this.settings(),e.agent.findMany({orderBy:{name:"asc"},include:{diskSpaceState:!0}}),e.derivedDataCleanupLease.findMany({select:{agentId:!0}})]),s=new Set(n.map(e=>e.agentId));return{settings:t,agents:r.map(e=>{let r=e.diskSpaceState,a=r?.enabled??!0,n=r?.manualPressureMode??!1,o=r?.automaticPressureMode??!1,l=r?.lastReportedAt??null,u=!l||Date.now()-l.getTime()>1e3*t.staleAfterSeconds,d=(n||o?t.pressureThresholdGiB:t.normalThresholdGiB)*0x40000000,h=c(r?.volumesJson),p=(0,i.monitoredDiskSpaceVolumes)(h),m=p.some(e=>e.freeBytes<=0x40000000*t.pressureThresholdGiB),f=p.some(e=>e.freeBytes<d),g="IDLE";a?u?g="STALE":r?.lastError||0===h.length&&c(r?.warningsJson).length>0?g="ERROR":m?g="CRITICAL":s.has(e.id)?g="DELETING":n||o?g="PRESSURE":f&&(g="CLEANUP_REQUIRED"):g="DISABLED";let y=h.map(r=>{let l=(0,i.isMonitoredDiskSpaceVolume)(r);return{...r,effectiveThresholdBytes:d,monitored:l,status:a?u?"STALE":l?r.freeBytes<=0x40000000*t.pressureThresholdGiB?"CRITICAL":s.has(e.id)&&r.freeBytes<d?"DELETING":n||o?"PRESSURE":r.freeBytes<d?"CLEANUP_REQUIRED":"IDLE":"IDLE":"DISABLED"}}),w=c(r?.warningsJson);return a&&!u&&h.length>0&&0===p.length&&w.push("No Derived Data volume was reported, so free space is not being monitored for this agent"),{agent:e,enabled:a,status:g,pressureMode:n?"MANUAL":o?"AUTOMATIC":"NORMAL",manualPressureMode:n,automaticPressureMode:o,lastReportedAt:l?.toISOString()??null,lastError:r?.lastError??null,warnings:w,volumes:y}})}}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(0,u.diskSpaceSessionData)(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,a.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,a.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,a.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,a.getPrismaClient)(),[r,n]=await Promise.all([this.settings(),t.agentDiskSpaceState.findUnique({where:{agentId:e}})]);if(!(!n?.enabled||!n.lastReportedAt||n.lastError||Date.now()-n.lastReportedAt.getTime()>1e3*r.staleAfterSeconds)&&(0,i.monitoredDiskSpaceVolumes)(c(n.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 s.agentEventBus.iterate(s.DISK_SPACE_CHANGED_TOPIC)}async reconcileAgent(e){let s=await (0,a.getPrismaClient)();await s.derivedDataCleanupLease.deleteMany({where:{jobId:null,expiresAt:{lte:new Date}}});let[o,u,d,h,p]=await Promise.all([this.settings(),s.agentDiskSpaceState.findUnique({where:{agentId:e}}),s.derivedDataLock.findMany({where:{agentId:e},select:{path:!0}}),s.derivedDataCleanupLease.findFirst({where:{agentId:e}}),s.agent.findUnique({where:{id:e}})]);if(!u?.enabled||!u.lastReportedAt||u.lastError||h||!p||null!==p.disconnectedAt||null===p.lastSeenAt||Date.now()-p.lastSeenAt.getTime()>(0,n.agentOnlineWindowMs)(p)||!c(p.capabilitiesJson).includes(r.BUILD_DATA_DELETE_JOB_KIND)||Date.now()-u.lastReportedAt.getTime()>1e3*o.staleAfterSeconds)return;let m=c(u.entriesJson),f=c(u.volumesJson),g=(0,i.monitoredDiskSpaceVolumes)(f),y=m.map(e=>e.worktreeId).filter(e=>!!e),w=await (0,l.executingResourcesByWorktree)(y),b=new Set(d.map(e=>e.path));m=m.filter(e=>"PROJECT"===e.kind&&!!e.worktreeId&&!b.has(e.path)&&(w.get(e.worktreeId)?.length??0)===0);let E=0x40000000*o.normalThresholdGiB,S=0x40000000*o.pressureThresholdGiB,v=g.filter(e=>e.freeBytes<E),I=e=>e.capacityId??e.id,A=new Map(f.map(e=>[e.id,I(e)])),k=e=>m.some(t=>A.get(t.volumeId)===I(e)),_=u.automaticPressureMode;if(!u.manualPressureMode){let t=v.length>0&&v.some(e=>!k(e)),r=_&&(0===v.length||v.every(e=>k(e)));t?_=!0:r&&(_=!1),_!==u.automaticPressureMode&&(await s.agentDiskSpaceState.update({where:{agentId:e},data:{automaticPressureMode:_}}),this.publish(e,"AUTOMATIC_PRESSURE_CHANGED"))}let T=u.manualPressureMode||_?S:E,C=new Set(g.filter(e=>e.freeBytes<T).map(I)),R=m.filter(e=>C.has(A.get(e.volumeId)??"")).sort((e,t)=>new Date(e.modifiedAt).getTime()-new Date(t.modifiedAt).getTime()||e.path.localeCompare(t.path))[0];if(!R?.worktreeId)return;try{await s.derivedDataCleanupLease.create({data:{worktreeId:R.worktreeId,agentId:e,path:R.path,source:"AUTOMATIC",expiresAt:new Date(Date.now()+6e5)}})}catch{return}let N=await (0,l.executingResourcesByWorktree)([R.worktreeId]);if((N.get(R.worktreeId)?.length??0)>0){await s.derivedDataCleanupLease.deleteMany({where:{worktreeId:R.worktreeId,jobId:null}}),this.publish(e,"CLEANUP_SKIPPED");return}try{var O;let i=await this.agentControl.createJob({agentId:e,kind:r.BUILD_DATA_DELETE_JOB_KIND,payload:{source:"AUTOMATIC",targets:[{path:R.path,rootPath:R.rootPath,name:R.name,kind:R.kind,worktreeId:R.worktreeId,worktreePath:R.worktreePath}]},idempotencyKey:`disk-space:auto:${(O=R.path,(0,t.createHash)("sha256").update(e).update("\0").update(O).digest("base64url"))}:${(0,t.randomUUID)()}`,timeoutSeconds:600,visibility:"SYSTEM"});await s.derivedDataCleanupLease.update({where:{worktreeId:R.worktreeId},data:{jobId:i.id}}),this.publish(e,"CLEANUP_STARTED")}catch(t){await s.derivedDataCleanupLease.deleteMany({where:{worktreeId:R.worktreeId}}),await s.agentDiskSpaceState.update({where:{agentId:e},data:{lastError:t instanceof Error?t.message:String(t)}}),this.publish(e,"CLEANUP_START_FAILED")}}async observeCompletion(e){if(e.kind!==r.BUILD_DATA_DELETE_JOB_KIND)return;let t="USER",i=[];try{let a=(0,r.buildDataDeletePayload)(JSON.parse(e.payloadJson));t=a.source,i=a.targets}catch{}let n=await (0,a.getPrismaClient)(),s=await n.derivedDataCleanupLease.deleteMany({where:{jobId:e.id}});if("AUTOMATIC"===t&&"SUCCEEDED"!==e.status&&await n.agentDiskSpaceState.updateMany({where:{agentId:e.agentId},data:{lastError:e.error||"Automatic Derived Data cleanup failed"}}),s.count||"AUTOMATIC"===t){let a=[];if("AUTOMATIC"===t&&e.resultJson)try{a=(0,r.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:i,deleted:a}:null),this.agentControl.requestDiskSpacePoll(e.agentId)}}publish(e,r,i=null){s.agentEventBus.publish(s.DISK_SPACE_CHANGED_TOPIC,{diskSpaceChanged:e,diskSpaceChange:{id:(0,t.randomUUID)(),reason:r,cleanup:i}}),s.agentEventBus.publish(s.SIDEBAR_STATUS_CHANGED_TOPIC,{sidebarStatusChanged:!0}),s.agentEventBus.publish(s.POLLING_CHANGED_TOPIC,{pollingOperationChanged:`agent-disk-space:${e}`})}}])},714327,e=>{"use strict";e.i(599600),e.i(518733),e.i(508813),e.s([])},695248,e=>{"use strict";var t=e.i(666680),r=e.i(243783),i=e.i(483291);e.i(582482);var a=e.i(318905),n=e.i(783396),s=e.i(919412),o=e.i(407188),l=e.i(616204),u=e.i(334416),c=e.i(963910),d=e.i(940045);let h="server:github-actions-notifications",p=new Set(["failure","timed_out","startup_failure","action_required"]);function m(e){return"string"==typeof e&&e.trim()?e.trim():null}function f(e){return"number"==typeof e&&Number.isInteger(e)&&e>0?e:null}function g(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||"object"!=typeof e||Array.isArray(e))return[];let t=f(e.number);return t?[{number:t,url:m(e.html_url)??m(e.url)}]:[]}):[]}function y(e,t,r){let i=f(r?.id),a=f(r?.workflow_id),n=m(r?.updated_at),s=n?new Date(n):null;return i&&a&&s&&Number.isFinite(s.getTime())?{id:String(i),workflowId:String(a),runAttempt:f(r?.run_attempt)??1,name:m(r?.name)??"GitHub Actions",displayTitle:m(r?.display_title)??m(r?.name)??"Workflow run",status:m(r?.status)?.toLowerCase()??"unknown",conclusion:m(r?.conclusion)?.toLowerCase()??null,headBranch:m(r?.head_branch),headSha:m(r?.head_sha),pullRequests:g(r?.pull_requests),url:m(r?.html_url)??"",updatedAt:s,repositoryGithubId:m(t?.node_id),repositoryNameWithOwner:m(t?.full_name)??`${e.owner}/${e.repository}`,repositoryUrl:m(t?.html_url)??`https://github.com/${e.owner}/${e.repository}`,checkSuiteId:m(r?.check_suite_node_id)}:null}function w(e,t){let r=(0,d.normalizePipelineState)(e,t);return"SUCCESS"===r||"NEUTRAL"===r||"SKIPPED"===r?"IN_PROGRESS":r}function b(e,t){if(!e||!t)return null;try{let r=(0,i.compileRe2)(t,{flags:"i",label:"Jira branch regex"}).exec(e),a=(r?.[1]??r?.[0])?.trim();return a?a.toUpperCase():null}catch{return null}}e.s(["GitHubActionsNotificationsService",0,class{credentials;notifications;polling;workflowEvents;cache;pipelineStatus;timer;running;rerunRequested;constructor(e,t,r,i=!0,a,n=new s.GitHubCache,o=new c.GitHubPipelineStatusService){this.credentials=e,this.notifications=t,this.polling=r,this.workflowEvents=a,this.cache=n,this.pipelineStatus=o,this.timer=null,this.running=!1,this.rerunRequested=!1,this.polling.register({id:h,kind:"GITHUB_ACTIONS_NOTIFICATIONS",runtime:"SERVER",enabled:!1,cadenceSeconds:60,details:{mode:"DISABLED"}}),i&&queueMicrotask(()=>void this.tick())}async appConnection(){let e=await this.credentials.getJson(a.CREDENTIALS.githubAppSettings);return e?(0,n.githubAppConnectionSettings)(e):null}async recordWorkflowRunEvent(e,t){if(!this.workflowEvents||"completed"!==t.status)return;let i=await (0,r.getPrismaClient)(),[a,n]=await Promise.all([t.headBranch?i.worktree.findFirst({where:{branch:t.headBranch,missingAt:null,codebase:{repositoryId:e.id}},orderBy:{updatedAt:"desc"},select:{id:!0,folder:!0,branch:!0,baseBranchOverride:!0,headSha:!0,codebase:{select:{id:!0,folder:!0,agentId:!0,defaultBranch:!0,agent:{select:{id:!0,name:!0,hostname:!0}}}}}}):null,i.codebaseSettings.findUnique({where:{id:"default"}})]),s=b(t.headBranch,e.jiraBranchRegex??n?.defaultJiraBranchRegex??""),o=t.pullRequests[0]??null,l={repo:{id:e.id,name:e.name,owner:e.owner,url:`https://github.com/${e.owner}/${e.repository}`,canonicalOrigin:e.canonicalOrigin,displayOrigin:e.displayOrigin,defaultBranch:a?.codebase.defaultBranch??null},pipeline:{runId:t.id,workflowId:t.workflowId,name:t.name,displayTitle:t.displayTitle,status:t.status,conclusion:t.conclusion,headBranch:t.headBranch,headSha:t.headSha,pullRequests:t.pullRequests,url:t.url},...a?{worktree:{id:a.id,path:a.folder,branch:a.branch,baseBranch:a.baseBranchOverride??a.codebase.defaultBranch,headSha:a.headSha},codebase:{id:a.codebase.id,folder:a.codebase.folder,agentId:a.codebase.agentId},agent:a.codebase.agent}:{},...o?{pr:o}:{},...s?{ticket:{key:s}}:{}},u={cursorValue:`${t.id}:${t.runAttempt}:${t.conclusion??"none"}`};await this.workflowEvents.record({kind:"GITHUB_ACTIONS_RESULT",subjectKey:e.id,dedupeKey:`github-actions-trigger:${e.id}:${t.id}:${t.runAttempt}`,payload:{...l,...u,sessionData:l}});let c="success"===t.conclusion?"GITHUB_WORKFLOW_SUCCEEDED":t.conclusion&&p.has(t.conclusion)?"GITHUB_CHECK_FAILED":null;c&&await this.workflowEvents.record({kind:c,subjectKey:e.id,dedupeKey:`github-workflow-trigger:${c}:${e.id}:${t.id}:${t.runAttempt}`,payload:{...l,...u,sessionData:l}})}async observePipelineRun(e,t,r,i=!0){if(!t.repositoryGithubId||!t.headSha)return!1;let a="completed"===t.status,n=!!t.checkSuiteId;return await this.pipelineStatus.observeSnapshot({repositoryGithubId:t.repositoryGithubId,repositoryNameWithOwner:t.repositoryNameWithOwner,repositoryUrl:t.repositoryUrl,headSha:t.headSha,pipelines:[{id:t.id,name:t.name,status:(0,d.normalizePipelineState)(t.status,t.conclusion),url:t.url,checkSuiteId:t.checkSuiteId,workflowRunId:t.id,workflowId:t.workflowId,runAttempt:t.runAttempt,canRetry:a&&n&&i,retryUnavailableReason:a?n?i?null:"GITHUB_APP_NOT_CONFIGURED":"WORKFLOW_RUN_UNAVAILABLE":"NOT_COMPLETED",source:r,githubUpdatedAt:t.updatedAt}]}),!0}async observeEnhancedWebhook(e,t,r,i){let a={workflow_run:new Set(["requested","in_progress","completed"]),workflow_job:new Set(["queued","in_progress","completed"]),check_run:new Set(["created","rerequested","completed"]),check_suite:new Set(["requested","rerequested","in_progress","completed"]),status:new Set([null])};if(!a[t]?.has(r))return!1;let n=i.repository,s=m(n?.node_id),o="status"===t?m(i.sha):m((i[t]??{}).head_sha);if(!s||!o)return!1;let l=m(n?.full_name)??`${e.owner}/${e.repository}`,u=m(n?.html_url)??`https://github.com/${e.owner}/${e.repository}`;if("workflow_run"===t){let t=y(e,n,i.workflow_run);return!!t&&this.observePipelineRun(e,t,"WEBHOOK")}if("status"===t){let e,t=m(i.context);return!!t&&(await this.pipelineStatus.observeSnapshot({repositoryGithubId:s,repositoryNameWithOwner:l,repositoryUrl:u,headSha:o,pipelines:[{id:t,name:t,status:(0,d.normalizePipelineState)(m(i.state)),url:m(i.target_url),statusContext:t,source:"WEBHOOK",githubUpdatedAt:(e=m(i.updated_at)??m(i.created_at))?new Date(e):null}]}),!0)}if("check_suite"===t){let e=i.check_suite,t=m(e?.node_id);if(!e||!t)return!1;let r=e.app,a=m(e.updated_at)??m(e.completed_at)??m(e.started_at);return await this.pipelineStatus.observeSnapshot({repositoryGithubId:s,repositoryNameWithOwner:l,repositoryUrl:u,headSha:o,pipelines:[{id:t,name:m(r?.name)??"GitHub checks",status:(0,d.normalizePipelineState)(m(e.status),m(e.conclusion)),url:m(e.url),checkSuiteId:t,source:"WEBHOOK",githubUpdatedAt:a?new Date(a):null}]}),!0}if("check_run"===t){let e=i.check_run,t=e?.check_suite,r=m(t?.node_id),a=m(e?.node_id);if(!e||!r||!a)return!1;let n=m(e.completed_at)??m(e.started_at)??m(e.updated_at);return await this.pipelineStatus.observeSnapshot({repositoryGithubId:s,repositoryNameWithOwner:l,repositoryUrl:u,headSha:o,pipelines:[{id:a,name:m(e.name)??"GitHub check",status:w(m(e.status),m(e.conclusion)),url:m(e.details_url)??m(e.html_url),checkSuiteId:r,source:"WEBHOOK",githubUpdatedAt:n?new Date(n):null}]}),!0}let c=i.workflow_job,h=f(c?.run_id)?.toString()??null;if(!c||!h)return!1;let p=m(c.completed_at)??m(c.started_at)??m(c.created_at),g=p?new Date(p):null,b=Array.isArray(c.steps)?c.steps.flatMap(e=>{if(!e||"object"!=typeof e||Array.isArray(e))return[];let t=f(e.number);return t?[{number:t,name:m(e.name)??`Step ${t}`,status:(0,d.normalizePipelineState)(m(e.status),m(e.conclusion))}]:[]}):[],E={id:f(c.id)?.toString()??m(c.node_id)??"unknown",name:m(c.name)??"Workflow job",status:(0,d.normalizePipelineState)(m(c.status),m(c.conclusion)),url:m(c.html_url),canRetry:m(c.status)?.toLowerCase()==="completed",retryUnavailableReason:m(c.status)?.toLowerCase()==="completed"?null:"NOT_COMPLETED",steps:b,runAttempt:f(c.run_attempt)};return await this.pipelineStatus.observeSnapshot({repositoryGithubId:s,repositoryNameWithOwner:l,repositoryUrl:u,headSha:o,pipelines:[{id:h,name:m(c.workflow_name)??"GitHub Actions",status:w(m(c.status),m(c.conclusion)),url:m(c.html_url),workflowRunId:h,runAttempt:f(c.run_attempt),source:"WEBHOOK",githubUpdatedAt:g}]}),await this.pipelineStatus.observeJobs(s,h,[E],"WEBHOOK",g),!0}async recordWebhookTrigger(e,t,i,a,n){if(!this.workflowEvents)return!1;let s=n.repository??{},o=n.pull_request??{},l=n.review??{},u=n.comment??{},c=n.check_run??n.check_suite??{},d=null;if("pull_request"===t&&new Set(["opened","reopened","ready_for_review"]).has(i??"")?d="GITHUB_PR_STATE":"pull_request"===t&&"synchronize"===i?d="GITHUB_PR_SYNCHRONIZED":"pull_request"===t&&"closed"===i?d="GITHUB_PR_CLOSED":"pull_request"===t&&"labeled"===i?d="GITHUB_PR_LABEL":"pull_request_review"===t&&"submitted"===i&&m(l.state)?.toLowerCase()==="changes_requested"?d="GITHUB_REVIEW_CHANGES_REQUESTED":"pull_request_review"===t&&"submitted"===i&&m(l.state)?.toLowerCase()==="approved"?d="GITHUB_REVIEW_APPROVED":"pull_request_review_comment"===t&&"created"===i?d="GITHUB_REVIEW_COMMENT":("check_run"===t||"check_suite"===t)&&p.has(m(c.conclusion)?.toLowerCase()??"")?d="GITHUB_CHECK_FAILED":"push"===t&&m(n.ref)===`refs/heads/${m(s.default_branch)}`?d="GITHUB_PUSH_DEFAULT":"issue_comment"===t&&"created"===i&&(d="GITHUB_ISSUE_COMMAND"),!d)return!1;let h=u.user??{},g=Array.isArray(o.labels)?o.labels.flatMap(e=>{let t=e&&"object"==typeof e?m(e.name):null;return t?[t]:[]}):[],y=o.head,w=o.base,E=c.check_suite??n.check_suite??{},S=m(y?.ref),v=m(n.ref)?.replace(/^refs\/heads\//,"")??null,I=m(c.head_branch)??m(E.head_branch),A=S??v??I,k=await (0,r.getPrismaClient)(),_=await k.codebaseSettings.findUnique({where:{id:"default"}}),T=b(A,e.jiraBranchRegex??_?.defaultJiraBranchRegex??""),C=A?await k.worktree.findFirst({where:{branch:A,primary:!1,missingAt:null,codebase:{repositoryId:e.id}},orderBy:{updatedAt:"desc"},select:{id:!0,folder:!0,branch:!0,baseBranchOverride:!0,headSha:!0,pushStatus:!0,hasStagedChanges:!0,hasUnstagedChanges:!0,codebase:{select:{id:!0,folder:!0,agentId:!0,branch:!0,headSha:!0,defaultBranch:!0,agent:{select:{id:!0,name:!0,hostname:!0}}}}}}):null,R={repo:{id:e.id,name:e.name,owner:e.owner,url:m(s.html_url),canonicalOrigin:e.canonicalOrigin,displayOrigin:m(s.full_name)??e.displayOrigin,defaultBranch:m(s.default_branch)},pr:{number:f(o.number)??f(n.issue?.number),url:m(o.html_url),state:m(o.state)?.toUpperCase()??null,merged:!0===o.merged,labels:g,title:m(o.title),isDraft:!0===o.draft,headBranch:S,headSha:m(y?.sha),baseBranch:m(w?.ref),reviewDecision:m(l.state)?.toUpperCase()??null},pipeline:{checkSuiteId:f(c.id)?.toString()??null,status:m(c.status),conclusion:m(c.conclusion),headBranch:I,headSha:m(c.head_sha)??m(E.head_sha)},comment:{id:f(u.id)?.toString()??null,body:m(u.body)??"",author:{login:m(h.login)}},push:{ref:m(n.ref),before:m(n.before),after:m(n.after)},...C?{worktree:{id:C.id,path:C.folder,branch:C.branch,baseBranch:C.baseBranchOverride??C.codebase.defaultBranch,headSha:C.headSha,pushStatus:C.pushStatus,dirty:C.hasStagedChanges||C.hasUnstagedChanges},codebase:{id:C.codebase.id,folder:C.codebase.folder,agentId:C.codebase.agentId,branch:C.codebase.branch,headSha:C.codebase.headSha},agent:C.codebase.agent}:{},...T?{ticket:{key:T}}:{}};return await this.workflowEvents.record({kind:d,subjectKey:e.id,dedupeKey:`github-webhook-trigger:${a}:${d}`,payload:{...R,sessionData:R,cursorValue:`${a}:${d}`,webhook:{event:t,action:i,deliveryId:a}}}),!0}schedule(e){this.timer&&clearTimeout(this.timer);let t=1e3*Math.max(30,e);this.timer=setTimeout(()=>void this.tick(),t),this.timer.unref(),this.polling.schedule(h,new Date(Date.now()+t))}configurationChanged(){if(this.running){this.rerunRequested=!0;return}this.timer&&clearTimeout(this.timer),this.timer=null,queueMicrotask(()=>void this.tick())}async tick(){if(this.running)return;this.running=!0;let e=60;try{let t=await (0,r.getPrismaClient)(),[i,n,s,o,l]=await Promise.all([t.gitHubSettings.upsert({where:{id:"default"},create:{id:"default"},update:{}}),t.gitHubAppSettings.findUnique({where:{id:"default"}}),this.appConnection(),this.credentials.isConfigured(a.CREDENTIALS.githubPersonalAccessToken),this.credentials.isConfigured(a.CREDENTIALS.githubAppWebhookSecret)]);if(e=i.actionsNotificationPollIntervalSeconds,s?.webhookUrl&&n?.webhookConfiguredAt&&l)return void this.polling.configure(h,{enabled:!1,cadenceSeconds:e,details:{mode:"WEBHOOK"}});if(!o)return void this.polling.configure(h,{enabled:!1,cadenceSeconds:e,details:{mode:"DISABLED",reason:"GITHUB_TOKEN_REQUIRED"}});this.polling.configure(h,{enabled:!0,cadenceSeconds:e,details:{mode:"POLLING"}}),await this.polling.run(h,()=>this.pollRepositories(),e=>e)}catch{}finally{this.running=!1,this.rerunRequested?(this.rerunRequested=!1,queueMicrotask(()=>void this.tick())):this.schedule(e)}}async repositories(){return(await (await (0,r.getPrismaClient)()).codebaseRepository.findMany({orderBy:{name:"asc"},select:{id:!0,name:!0,canonicalOrigin:!0,displayOrigin:!0,jiraBranchRegex:!0}})).flatMap(e=>{let t=/^github\.com\/([^/]+)\/([^/]+)$/i.exec(e.canonicalOrigin.trim());return t?.[1]&&t[2]?[{id:e.id,name:e.name,owner:t[1],repository:t[2],canonicalOrigin:e.canonicalOrigin,displayOrigin:e.displayOrigin,jiraBranchRegex:e.jiraBranchRegex}]:[]})}async fetchRuns(e,t,r){let i=[];for(let a=1;;a+=1){let n,s=`${o.GITHUB_API_BASE_URL}/repos/${encodeURIComponent(e.owner)}/${encodeURIComponent(e.repository)}/actions/runs?per_page=100&page=${a}`,c=Date.now(),d=e=>this.cache.recordRestCall({authentication:"PAT",method:"GET",endpoint:s,operation:u.GITHUB_REST_OPERATIONS.actions.listWorkflowRunsForRepo,requestSource:"ACTIONS_NOTIFICATIONS",durationMs:Date.now()-c,...e}).catch(()=>void 0);try{n=await fetch(s,{headers:{accept:"application/vnd.github+json",authorization:`Bearer ${t}`,"user-agent":"ai-development-environment","x-github-api-version":"2022-11-28"},cache:"no-store"})}catch(t){let e=t instanceof Error?t.message:String(t);throw await d({error:e}),t}let h=await (0,l.observeGitHubRateLimit)("PAT",n),p=await n.json().catch(()=>null);if(!n.ok||!Array.isArray(p?.workflow_runs)){let t=p?.message||`GitHub returned HTTP ${n.status} while polling ${e.owner}/${e.repository}`;throw await d({statusCode:n.status,error:t,rateLimit:h}),Error(t)}await d({statusCode:n.status,rateLimit:h});let y=p.workflow_runs.flatMap(t=>{let r=f(t.id),i=f(t.workflow_id),a=m(t.updated_at),n=a?new Date(a):null,s=t.repository;return r&&i&&n&&Number.isFinite(n.getTime())?[{id:String(r),workflowId:String(i),runAttempt:f(t.run_attempt)??1,name:m(t.name)??"GitHub Actions",displayTitle:m(t.display_title)??m(t.name)??"Workflow run",status:m(t.status)?.toLowerCase()??"unknown",conclusion:m(t.conclusion)?.toLowerCase()??null,headBranch:m(t.head_branch),headSha:m(t.head_sha),pullRequests:g(t.pull_requests),url:m(t.html_url)??"",updatedAt:n,repositoryGithubId:m(s?.node_id),repositoryNameWithOwner:m(s?.full_name)??`${e.owner}/${e.repository}`,repositoryUrl:m(s?.html_url)??`https://github.com/${e.owner}/${e.repository}`,checkSuiteId:m(t.check_suite_node_id)}]:[]});if(i.push(...y),!r||p.workflow_runs.length<100||y.some(e=>e.updatedAt<=r))return i}}async worktreeContext(e,t,r){return r?e.worktree.findFirst({where:{branch:r,missingAt:null,codebase:{repositoryId:t}},orderBy:{updatedAt:"desc"},select:{id:!0,highlightColor:!0}}):null}async observeRun(e,r,i,a,n){var s;let o=new Date,l="success"===(s=i.conclusion)?"GITHUB_ACTIONS_SUCCEEDED":s&&p.has(s)?"GITHUB_ACTIONS_FAILED":null,u=await e.gitHubWorkflowRunObservation.findUnique({where:{codebaseRepositoryId_workflowRunId_runAttempt:{codebaseRepositoryId:r.id,workflowRunId:i.id,runAttempt:i.runAttempt}}});if(await e.gitHubWorkflowRunObservation.upsert({where:{codebaseRepositoryId_workflowRunId_runAttempt:{codebaseRepositoryId:r.id,workflowRunId:i.id,runAttempt:i.runAttempt}},create:{id:(0,t.randomUUID)(),codebaseRepositoryId:r.id,workflowRunId:i.id,runAttempt:i.runAttempt,workflowId:i.workflowId,status:i.status,conclusion:i.conclusion,githubUpdatedAt:i.updatedAt,source:a,lastObservedAt:o},update:{workflowId:i.workflowId,status:i.status,conclusion:i.conclusion,githubUpdatedAt:i.updatedAt,source:a,lastObservedAt:o}}),!(u?"completed"!==u.status||u.conclusion!==i.conclusion:n)||!l||"completed"!==i.status||u?.notifiedAt)return null;let c=await this.worktreeContext(e,r.id,i.headBranch),d=new URLSearchParams({repository:r.id});i.headBranch&&d.set("branch",i.headBranch),d.set("pipeline",i.workflowId);let h=await this.notifications.recordInTransaction(e,{dedupeKey:`github-actions:${r.id}:${i.id}:${i.runAttempt}`,typeKey:l,title:"GITHUB_ACTIONS_SUCCEEDED"===l?"GitHub Actions succeeded":"GitHub Actions failed",body:[r.name,i.name,i.headBranch].filter(e=>!!e).join(" · "),href:`/actions?${d.toString()}`,resourceKind:"GITHUB_WORKFLOW_RUN",resourceId:`${r.id}:${i.id}:${i.runAttempt}`,worktreeId:c?.id??null,highlightColor:c?.highlightColor??null});return await e.gitHubWorkflowRunObservation.update({where:{codebaseRepositoryId_workflowRunId_runAttempt:{codebaseRepositoryId:r.id,workflowRunId:i.id,runAttempt:i.runAttempt}},data:{notifiedAt:o}}),h}async pollRepository(e,t,i){let a=await (0,r.getPrismaClient)(),n=new Date,s=await a.gitHubActionsPollingState.findUnique({where:{codebaseRepositoryId:e.id}});await a.gitHubActionsPollingState.upsert({where:{codebaseRepositoryId:e.id},create:{codebaseRepositoryId:e.id,initializedAt:n,lastPollStartedAt:n},update:{lastPollStartedAt:n}});try{let r=await this.fetchRuns(e,t,s?s.lastPollSucceededAt??s.initializedAt:null),n=[];return await a.$transaction(async t=>{for(let i of r){let r=await this.observeRun(t,e,i,"POLL",!!(s&&i.updatedAt>(s.lastPollSucceededAt??s.initializedAt)));r&&n.push(r)}let i=new Date;await t.gitHubActionsPollingState.update({where:{codebaseRepositoryId:e.id},data:{lastPollCompletedAt:i,lastPollSucceededAt:i,lastError:null}})}),n.forEach(e=>this.notifications.created(e)),await Promise.allSettled(r.flatMap(t=>[this.observePipelineRun(e,t,"REST",i),this.recordWorkflowRunEvent(e,t)])),n.length}catch(t){throw await a.gitHubActionsPollingState.update({where:{codebaseRepositoryId:e.id},data:{lastPollCompletedAt:new Date,lastError:t instanceof Error?t.message:String(t)}}),t}}async pollRepositories(){let e=await this.credentials.getText(a.CREDENTIALS.githubPersonalAccessToken);if(!e)throw Error("GitHub personal access token is unavailable");let[t,i,n]=await Promise.all([this.repositories(),(await (0,r.getPrismaClient)()).gitHubAppSettings.findUnique({where:{id:"default"},select:{id:!0}}),this.credentials.isConfigured(a.CREDENTIALS.githubAppPrivateKey)]),s=!!(i&&n),o=await Promise.allSettled(t.map(t=>this.pollRepository(t,e,s))),l=o.filter(e=>"rejected"===e.status),u=o.reduce((e,t)=>e+("fulfilled"===t.status?t.value:0),0);if(await this.prune(),l.length===t.length&&t.length>0)throw l[0].reason;return{mode:"POLLING",repositories:t.length,failures:l.length,notificationsCreated:u}}async prune(){let e=new Date(Date.now()-2592e6),t=await (0,r.getPrismaClient)();await Promise.all([t.gitHubWorkflowRunObservation.deleteMany({where:{lastObservedAt:{lt:e}}}),t.gitHubWebhookDelivery.deleteMany({where:{receivedAt:{lt:e}}})])}async handleWebhook(e){var i,n;let s,o,l=await this.credentials.getText(a.CREDENTIALS.githubAppWebhookSecret);if(!l)throw Error("GitHub webhook is not configured");if(!e.signature?.startsWith("sha256="))throw Error("GitHub webhook signature is missing");if(i=`sha256=${(0,t.createHmac)("sha256",l).update(e.body).digest("hex")}`,n=e.signature,s=Buffer.from(i),o=Buffer.from(n),!(s.length===o.length&&(0,t.timingSafeEqual)(s,o)))throw Error("GitHub webhook signature is invalid");if(!e.deliveryId?.trim())throw Error("GitHub delivery ID is missing");let u=await (0,r.getPrismaClient)(),c=e.deliveryId.trim();try{await u.gitHubWebhookDelivery.create({data:{deliveryId:c,event:e.event??"unknown",outcome:"RECEIVED"}})}catch(t){if("object"==typeof t&&null!==t&&"code"in t&&"P2002"===t.code){if(0===(await u.gitHubWebhookDelivery.updateMany({where:{deliveryId:c,outcome:{notIn:["PROCESSED","IGNORED"]}},data:{event:e.event??"unknown",action:null,repositoryName:null,workflowRunId:null,outcome:"RECEIVED",error:null,receivedAt:new Date,processedAt:null}})).count)return{outcome:"DUPLICATE",notificationCreated:!1}}else throw t}let d=async(e,t=null)=>{await u.gitHubWebhookDelivery.update({where:{deliveryId:c},data:{outcome:e,error:t,processedAt:new Date}})};try{let t;try{t=JSON.parse(Buffer.from(e.body).toString("utf8"))}catch{throw Error("GitHub webhook payload is invalid JSON")}let r=m(t.action),i=t.repository,a=t.workflow_run;if(await u.gitHubWebhookDelivery.update({where:{deliveryId:c},data:{action:r,repositoryName:m(i?.full_name),workflowRunId:f(a?.id)?.toString()??null}}),"workflow_run"!==e.event||"completed"!==r){let[a,n]=await Promise.all([u.gitHubAppSettings.findUnique({where:{id:"default"}}),this.appConnection()]),s=t.installation;if(!a||!n||String(f(s?.id)??"")!==n.installationId)return await d("IGNORED","Installation does not match configured App"),{outcome:"IGNORED",notificationCreated:!1};let o=m(i?.full_name),l=o?(await this.repositories()).find(e=>`${e.owner}/${e.repository}`.toLowerCase()===o.toLowerCase()):null;if(!l)return await d("IGNORED","Repository is not registered"),{outcome:"IGNORED",notificationCreated:!1};let h=e.event??"unknown",[p,g]=await Promise.all([!!a.enhancedPipelineWebhooksEnabled&&this.observeEnhancedWebhook(l,h,r,t),this.recordWebhookTrigger(l,h,r,c,t)]),y=p||g;return await d(y?"PROCESSED":"IGNORED"),{outcome:y?"PROCESSED":"IGNORED",notificationCreated:!1}}let[n,s]=await Promise.all([u.gitHubAppSettings.findUnique({where:{id:"default"}}),this.appConnection()]),o=t.installation;if(!n||!s||String(f(o?.id)??"")!==s.installationId)return await d("IGNORED","Installation does not match configured App"),{outcome:"IGNORED",notificationCreated:!1};let l=m(i?.full_name),p=f(a?.id),g=f(a?.workflow_id),w=m(a?.updated_at);if(!l||!p||!g||!w)throw Error("GitHub workflow_run payload is incomplete");let b=(await this.repositories()).find(e=>`${e.owner}/${e.repository}`.toLowerCase()===l.toLowerCase());if(!b)return await d("IGNORED","Repository is not registered"),{outcome:"IGNORED",notificationCreated:!1};let E=y(b,i,a);if(!E)throw Error("GitHub workflow_run payload is incomplete");let S=null;return await u.$transaction(async e=>{S=await this.observeRun(e,b,E,"WEBHOOK",!0)}),this.notifications.created(S),await this.observePipelineRun(b,E,"WEBHOOK"),await this.recordWorkflowRunEvent(b,E),await d("PROCESSED"),this.polling.configure(h,{enabled:!1,details:{mode:"WEBHOOK",lastDeliveryId:c,lastDeliveryAt:new Date().toISOString()}}),this.prune().catch(()=>void 0),{outcome:"PROCESSED",notificationCreated:!!S}}catch(t){let e=t instanceof Error?t.message:String(t);throw await d("ERROR",e),t}}}])},963910,940045,e=>{"use strict";var t=e.i(666680),r=e.i(243783);e.i(805422);var i=e.i(661983);let a={LEGACY:0,GRAPHQL:1,REST:2,WEBHOOK:3,MUTATION:4},n=new Set(["CANCELLED","FAILURE","STALE","STARTUP_FAILURE","TIMED_OUT"]),s=new Set(["ACTION_REQUIRED","IN_PROGRESS","PENDING","QUEUED"]),o=new Set(["SUCCESS","NEUTRAL","SKIPPED"]);function l(e,t=null){return e.some(e=>"ERROR"===e)?"ERROR":e.some(e=>n.has(e))?"FAILURE":e.some(e=>s.has(e))?"PENDING":e.some(e=>"EXPECTED"===e)||"EXPECTED"===t?"EXPECTED":e.length>0&&e.every(e=>o.has(e))?"SUCCESS":0===e.length&&t?t:"NONE"}function u(e){return e.checkSuiteId?`CHECK_SUITE:${e.checkSuiteId}`:e.workflowRunId?`WORKFLOW_RUN:${e.workflowRunId}`:e.statusContext?`STATUS_CONTEXT:${e.statusContext}`:`PIPELINE:${e.id}`}function c(e){return s.has(e)?1:2*("NONE"!==e&&"EXPECTED"!==e)}function d(e,t,r){let i=e.runAttempt??0,n=t.runAttempt??0;if(n!==i)return n>i;let s=e.githubUpdatedAt?.getTime()??0,o=t.githubUpdatedAt?.getTime()??0;if(o!==s)return o>s;if("MUTATION"===e.source&&e.optimisticUntil&&e.optimisticUntil.getTime()>r.getTime())return"MUTATION"===t.source;let l="MUTATION"===e.source?a.LEGACY:a[e.source],u=a[t.source];if("MUTATION"!==e.source&&"MUTATION"!==t.source&&e.status&&t.status){let r=c(e.status),i=c(t.status);if(i!==r)return i>r}return u===l||u>l}function h(e){return"ACTION_REQUIRED"===e||"CANCELLED"===e||"ERROR"===e||"EXPECTED"===e||"FAILURE"===e||"IN_PROGRESS"===e||"NEUTRAL"===e||"PENDING"===e||"QUEUED"===e||"SKIPPED"===e||"STALE"===e||"STARTUP_FAILURE"===e||"SUCCESS"===e||"TIMED_OUT"===e||"NONE"===e}function p(e){return"ERROR"===e||"EXPECTED"===e||"FAILURE"===e||"PENDING"===e||"SUCCESS"===e||"NONE"===e}function m(e){try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function f(e){return"NONE"===e||"EXPECTED"===e?0:"ACTION_REQUIRED"===e||"PENDING"===e||"QUEUED"===e?1:"IN_PROGRESS"===e?2:3}function g(e){return"GRAPHQL"===e||"REST"===e||"WEBHOOK"===e||"MUTATION"===e?e:"LEGACY"}function y(e){return{id:e.githubPipelineId,name:e.name,status:h(e.status)?e.status:"NONE",url:e.url,checkSuiteId:e.checkSuiteId,canRetry:e.canRetry,retryUnavailableReason:e.retryUnavailableReason,jobs:m(e.jobsJson),workflowRunId:e.workflowRunId,workflowId:e.workflowId,runNumber:e.runNumber,runAttempt:e.runAttempt}}function w(e,t){return{...y(t),repositoryGithubId:e.repositoryGithubId,headSha:e.headSha,revision:e.revision,isCurrent:t.isCurrent}}function b(e){return{repositoryGithubId:e.repositoryGithubId,repositoryNameWithOwner:e.repositoryNameWithOwner,repositoryUrl:e.repositoryUrl,headSha:e.headSha,pipelineStatus:p(e.pipelineStatus)?e.pipelineStatus:"NONE",pipelines:e.records.filter(e=>e.isCurrent).map(y).sort((e,t)=>e.name.localeCompare(t.name)),revision:e.revision,updatedAt:e.updatedAt.toISOString()}}function E(e){return JSON.stringify({identityKey:e.identityKey,githubPipelineId:e.githubPipelineId,name:e.name,status:e.status,url:e.url,checkSuiteId:e.checkSuiteId,workflowRunId:e.workflowRunId,workflowId:e.workflowId,runNumber:e.runNumber,runAttempt:e.runAttempt,canRetry:e.canRetry,retryUnavailableReason:e.retryUnavailableReason,jobsJson:e.jobsJson,isCurrent:e.isCurrent})}function S(e){return JSON.stringify({repositoryNameWithOwner:e.repositoryNameWithOwner,repositoryUrl:e.repositoryUrl,pipelineStatus:e.pipelineStatus,records:e.records.map(E).sort((e,t)=>e.localeCompare(t))})}e.s(["GITHUB_PIPELINE_OPTIMISTIC_MS",0,12e4,"GITHUB_PIPELINE_RETENTION_MS",0,2592e6,"aggregatePipelineStatus",0,l,"isPipelineState",0,h,"isPipelineStatus",0,p,"normalizePipelineState",0,function(e,t){let r=(t||e||"NONE").toUpperCase();return h(r)?r:"REQUESTED"===r||"WAITING"===r?"QUEUED":"NONE"},"pipelineIdentity",0,u,"shouldReplacePipelineRecord",0,d],940045),e.s(["GitHubPipelineStatusService",0,class{lastPrunedAt=0;async snapshot(e){let t=await (0,r.getPrismaClient)(),i=await t.gitHubPipelineSnapshot.findUnique({where:{repositoryGithubId_headSha:{repositoryGithubId:e.repositoryGithubId.trim(),headSha:e.headSha.trim()}},include:{records:!0}});return i?b(i):null}async snapshots(e){let t=e.map(e=>({repositoryGithubId:e.repositoryGithubId.trim(),headSha:e.headSha.trim()})).filter(e=>e.repositoryGithubId&&e.headSha);if(0===t.length)return[];let i=await (0,r.getPrismaClient)();return(await i.gitHubPipelineSnapshot.findMany({where:{OR:t},include:{records:!0}})).map(b)}async records(e){let t=e.map(e=>({repositoryGithubId:e.repositoryGithubId.trim(),workflowRunId:e.workflowRunId.trim()})).filter(e=>e.repositoryGithubId&&e.workflowRunId);if(0===t.length)return[];let i=await (0,r.getPrismaClient)();return(await i.gitHubPipelineRecord.findMany({where:{OR:t.map(e=>({workflowRunId:e.workflowRunId,snapshot:{repositoryGithubId:e.repositoryGithubId}}))},include:{snapshot:{include:{records:!0}}}})).map(e=>w(e.snapshot,e))}async observeWorkflowRuns(e,t="REST",r=!0){let i=new Map;for(let t of e){if(!t.repositoryGithubId||!t.headSha)continue;let e=`${t.repositoryGithubId}\u0000${t.headSha}`,r=i.get(e)??[];r.push(t),i.set(e,r)}let a=new Map;for(let e of i.values()){let i=e[0];await this.observeSnapshot({repositoryGithubId:i.repositoryGithubId,repositoryNameWithOwner:i.repositoryNameWithOwner,repositoryUrl:i.repositoryUrl,headSha:i.headSha,pipelines:e.map(e=>(function(e,t,r=!0){return{id:e.id,name:e.name,status:e.status,url:e.url,checkSuiteId:e.checkSuiteId,workflowRunId:e.id,workflowId:e.workflowId,runNumber:e.runNumber,runAttempt:e.runAttempt,canRetry:e.canRetry,retryUnavailableReason:e.retryUnavailableReason,source:t,githubUpdatedAt:new Date(e.updatedAt),sourceFetchedAt:new Date,isCurrent:r}})(e,t,r))})}for(let t of(await this.records(e.map(e=>({repositoryGithubId:e.repositoryGithubId,workflowRunId:e.id})))))t.workflowRunId&&a.set(t.workflowRunId,t);return a}async observeJobs(e,t,i,a="REST",n=null){let s=await (0,r.getPrismaClient)(),o=await s.gitHubPipelineRecord.findFirst({where:{workflowRunId:t,...e?{snapshot:{repositoryGithubId:e}}:{}},include:{snapshot:!0},orderBy:[{runAttempt:"desc"},{sourceFetchedAt:"desc"}]});if(!o)return null;let u=i.filter(e=>null==e.runAttempt||null==o.runAttempt||e.runAttempt===o.runAttempt);if(i.length>0&&0===u.length)return w({...o.snapshot,records:[o]},o);let c=m(o.jobsJson),d=new Map(c.map(e=>[e.id,e])),p=u.map(e=>(function(e,t){if(!e)return t;let r=e.runAttempt??0,i=t.runAttempt??0;if(i!==r)return i>r?t:e;let a=f(e.status),n=f(t.status);return n<a?e:n===a&&t.steps.length<e.steps.length?{...t,steps:e.steps}:t})(d.get(e.id),e)),g="WEBHOOK"===a?[...new Map([...c,...p].map(e=>[e.id,e])).values()]:p,b=h(o.status)?o.status:"NONE",E="REST"===a&&u.length>0?l(u.map(e=>e.status),null):"NONE",S=("ERROR"===E||"FAILURE"===E||"SUCCESS"===E)&&o.snapshot.graphqlRollupStatus===E?E:b;return(await this.observeSnapshot({repositoryGithubId:o.snapshot.repositoryGithubId,repositoryNameWithOwner:o.snapshot.repositoryNameWithOwner,repositoryUrl:o.snapshot.repositoryUrl,headSha:o.snapshot.headSha,pipelines:[{...y(o),status:S,source:a,jobs:g,githubUpdatedAt:n??o.githubUpdatedAt,isCurrent:o.isCurrent}]})).changedPipeline}async optimisticByCheckSuite(e,t,r){return this.optimisticRecord({repositoryGithubId:e,checkSuiteId:t,workflowRunId:null},r)}async optimisticByWorkflowRun(e,t,r){return this.optimisticRecord({repositoryGithubId:e,checkSuiteId:null,workflowRunId:t},r)}async optimisticJobByCheckSuite(e,t,i){let a=await (0,r.getPrismaClient)(),n=await a.gitHubPipelineRecord.findFirst({where:{checkSuiteId:t,snapshot:{repositoryGithubId:e}},orderBy:[{runAttempt:"desc"},{sourceFetchedAt:"desc"}]});if(!n)return null;let s=m(n.jobsJson).map(e=>e.id===i?{...e,status:"QUEUED",canRetry:!1,retryUnavailableReason:"NOT_COMPLETED"}:e);return this.optimisticByCheckSuite(e,t,{status:"QUEUED",jobs:s})}async optimisticJobByWorkflowRun(e,t,i){let a=await (0,r.getPrismaClient)(),n=await a.gitHubPipelineRecord.findFirst({where:{workflowRunId:t,...e?{snapshot:{repositoryGithubId:e}}:{}},orderBy:[{runAttempt:"desc"},{sourceFetchedAt:"desc"}]});if(!n)return null;let s=m(n.jobsJson).map(e=>e.id===i?{...e,status:"QUEUED",canRetry:!1,retryUnavailableReason:"NOT_COMPLETED"}:e);return this.optimisticByWorkflowRun(e,t,{status:"QUEUED",jobs:s})}async optimisticRecord(e,t){let i=await (0,r.getPrismaClient)(),a=await i.gitHubPipelineRecord.findFirst({where:{...e.repositoryGithubId?{snapshot:{repositoryGithubId:e.repositoryGithubId}}:{},...e.checkSuiteId?{checkSuiteId:e.checkSuiteId}:{workflowRunId:e.workflowRunId}},include:{snapshot:!0},orderBy:[{runAttempt:"desc"},{sourceFetchedAt:"desc"}]});if(!a)return null;let n=new Date;return(await this.observeSnapshot({repositoryGithubId:a.snapshot.repositoryGithubId,repositoryNameWithOwner:a.snapshot.repositoryNameWithOwner,repositoryUrl:a.snapshot.repositoryUrl,headSha:a.snapshot.headSha,pipelines:[{...y(a),status:t.status,jobs:t.jobs,canRetry:!1,retryUnavailableReason:"NOT_COMPLETED",source:"MUTATION",githubUpdatedAt:a.githubUpdatedAt,sourceFetchedAt:n,optimisticUntil:new Date(n.getTime()+12e4),isCurrent:a.isCurrent}]})).changedPipeline}async observeSnapshot(e){let a=e.repositoryGithubId.trim(),n=e.headSha.trim();if(!a||!n)throw Error("GitHub repository ID and head SHA are required");let s=new Date,o=e.sourceFetchedAt??s,c=await (0,r.getPrismaClient)(),f=await c.$transaction(async r=>{let i=await r.gitHubPipelineSnapshot.upsert({where:{repositoryGithubId_headSha:{repositoryGithubId:a,headSha:n}},create:{id:(0,t.randomUUID)(),repositoryGithubId:a,repositoryNameWithOwner:e.repositoryNameWithOwner,repositoryUrl:e.repositoryUrl,headSha:n,pipelineStatus:"NONE",graphqlRollupStatus:null,revision:0,lastGraphqlSyncAt:null,lastObservedAt:s},update:{lastObservedAt:s},include:{records:!0}}),c=S(i),f=!!(e.completeGraphqlRollup&&(!i.lastGraphqlSyncAt||o.getTime()>=i.lastGraphqlSyncAt.getTime())),y=new Set,v=null;for(let a of e.pipelines){let e=u({id:a.id,checkSuiteId:a.checkSuiteId,workflowRunId:a.workflowRunId,statusContext:a.statusContext}),n=(await r.gitHubPipelineRecord.findMany({where:{snapshotId:i.id}})).filter(t=>t.identityKey===e||a.checkSuiteId&&t.checkSuiteId===a.checkSuiteId||a.workflowRunId&&t.workflowRunId===a.workflowRunId),l=n[0]??null;for(let e of n.slice(1))l&&d({runAttempt:l.runAttempt,githubUpdatedAt:l.githubUpdatedAt,source:g(l.source),optimisticUntil:l.optimisticUntil,status:h(l.status)?l.status:"NONE"},{runAttempt:e.runAttempt,githubUpdatedAt:e.githubUpdatedAt,source:g(e.source),status:h(e.status)?e.status:"NONE"},s)&&(l=e);for(let e of n)l&&e.id!==l.id&&(0===m(l.jobsJson).length&&m(e.jobsJson).length>0&&(l=await r.gitHubPipelineRecord.update({where:{id:l.id},data:{jobsJson:e.jobsJson}})),await r.gitHubPipelineRecord.delete({where:{id:e.id}}),v=l.id);let c=a.sourceFetchedAt??o,p=a.githubUpdatedAt??null,w=void 0===a.runAttempt?l?.runAttempt??null:a.runAttempt,b=void 0!==a.jobs?JSON.stringify(a.jobs):l&&(w??0)<=(l.runAttempt??0)?l.jobsJson:"[]",S=!!f||(!1===a.isCurrent?l?.isCurrent??!1:a.isCurrent??l?.isCurrent??!0);if(l){y.add(l.id);let t=E(l),i=d({runAttempt:l.runAttempt,githubUpdatedAt:l.githubUpdatedAt,source:g(l.source),optimisticUntil:l.optimisticUntil,status:h(l.status)?l.status:"NONE"},{runAttempt:w,githubUpdatedAt:p,source:a.source,status:a.status},s),n=!!(!i&&"MUTATION"===l.source&&l.optimisticUntil&&l.optimisticUntil.getTime()>s.getTime()&&"MUTATION"!==a.source);t!==E(l=await r.gitHubPipelineRecord.update({where:{id:l.id},data:i?{identityKey:e,githubPipelineId:a.id,name:a.name,status:a.status,url:void 0===a.url?l.url:a.url,checkSuiteId:void 0===a.checkSuiteId?l.checkSuiteId:a.checkSuiteId,workflowRunId:void 0===a.workflowRunId?l.workflowRunId:a.workflowRunId,workflowId:void 0===a.workflowId?l.workflowId:a.workflowId,runNumber:void 0===a.runNumber?l.runNumber:a.runNumber,runAttempt:w,canRetry:void 0===a.canRetry?l.canRetry:a.canRetry,retryUnavailableReason:void 0===a.retryUnavailableReason?l.retryUnavailableReason:a.retryUnavailableReason,jobsJson:b,source:a.source,githubUpdatedAt:p,sourceFetchedAt:c,lastObservedAt:s,optimisticUntil:void 0===a.optimisticUntil?l.optimisticUntil:a.optimisticUntil,isCurrent:S}:{lastObservedAt:s,...void 0!==a.jobs&&!n?{jobsJson:b}:{},...f?{isCurrent:!0}:{}}}))&&(v=l.id)}else v=(l=await r.gitHubPipelineRecord.create({data:{id:(0,t.randomUUID)(),snapshotId:i.id,identityKey:e,githubPipelineId:a.id,name:a.name,status:a.status,url:a.url??null,checkSuiteId:a.checkSuiteId??null,workflowRunId:a.workflowRunId??null,workflowId:a.workflowId??null,runNumber:a.runNumber??null,runAttempt:w,canRetry:a.canRetry??!1,retryUnavailableReason:a.retryUnavailableReason??null,jobsJson:b,source:a.source,githubUpdatedAt:p,sourceFetchedAt:c,lastObservedAt:s,optimisticUntil:a.optimisticUntil??null,isCurrent:S}})).id;y.add(l.id)}if(f)for(let e of(await r.gitHubPipelineRecord.findMany({where:{snapshotId:i.id,isCurrent:!0}})))!y.has(e.id)&&e.sourceFetchedAt.getTime()<=o.getTime()&&(!e.optimisticUntil||e.optimisticUntil.getTime()<=s.getTime())&&(await r.gitHubPipelineRecord.update({where:{id:e.id},data:{isCurrent:!1}}),v??=e.id);let I=await r.gitHubPipelineRecord.findMany({where:{snapshotId:i.id}}),A=f?e.graphqlRollupStatus??null:i.graphqlRollupStatus,k=l(I.filter(e=>e.isCurrent).map(e=>h(e.status)?e.status:"NONE"),A&&p(A)?A:null),_=c!==S(i=await r.gitHubPipelineSnapshot.update({where:{id:i.id},data:{repositoryNameWithOwner:e.repositoryNameWithOwner,repositoryUrl:e.repositoryUrl,pipelineStatus:k,graphqlRollupStatus:A,lastGraphqlSyncAt:f?o:i.lastGraphqlSyncAt,lastObservedAt:s},include:{records:!0}}))||null!==v;_&&(i=await r.gitHubPipelineSnapshot.update({where:{id:i.id},data:{revision:{increment:1}},include:{records:!0}}));let T=i,C=v?T.records.find(e=>e.id===v)??null:null;return{changed:_,change:{snapshot:b(T),changedPipeline:C?w(T,C):null}}});return f.changed&&i.agentEventBus.publish(i.GITHUB_PIPELINE_STATUS_CHANGED_TOPIC,{githubPipelineStatusChanged:f.change}),this.pruneIfNeeded().catch(()=>void 0),f.change}subscribe(){return i.agentEventBus.iterate(i.GITHUB_PIPELINE_STATUS_CHANGED_TOPIC)}async pruneIfNeeded(){let e=Date.now();if(e-this.lastPrunedAt<864e5)return;this.lastPrunedAt=e;let t=await (0,r.getPrismaClient)();await t.gitHubPipelineSnapshot.deleteMany({where:{lastObservedAt:{lt:new Date(e-2592e6)}}})}}],963910)},616204,334416,919412,407188,e=>{"use strict";var t=e.i(243783);function r(e){if(null===e||!/^\d+$/.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null}function i(e){let t=r(e.get("x-ratelimit-limit")),i=r(e.get("x-ratelimit-remaining")),a=r(e.get("x-ratelimit-used")),n=r(e.get("x-ratelimit-reset")),s=e.get("x-ratelimit-resource")?.trim()??"";if(null===t||null===i||null===a||null===n||!s)return null;let o=new Date(1e3*n);return Number.isFinite(o.getTime())?{limit:t,remaining:i,used:a,resetAt:o,resource:s}:null}async function a(e,r){let a=i(r.headers);if(!a)return null;try{let r=await (0,t.getPrismaClient)(),i=`${e}:${a.resource}`,n=new Date;await r.gitHubRateLimitSnapshot.upsert({where:{authentication_resource:{authentication:e,resource:a.resource}},create:{id:i,authentication:e,observedAt:n,...a},update:{observedAt:n,...a}})}catch{}return a}async function n(){let e=await (0,t.getPrismaClient)();return(await e.gitHubRateLimitSnapshot.findMany({orderBy:[{resource:"asc"},{authentication:"asc"}]})).map(e=>({authentication:e.authentication,resource:e.resource,limit:e.limit,remaining:e.remaining,used:e.used,resetAt:e.resetAt.toISOString(),observedAt:e.observedAt.toISOString()}))}e.s(["listGitHubRateLimitSnapshots",0,n,"observeGitHubRateLimit",0,a,"parseGitHubRateLimitHeaders",0,i],616204),e.s(["GITHUB_REST_OPERATIONS",0,{actions:{cancelWorkflowRun:"actions.cancelWorkflowRun",dispatchWorkflow:"actions.dispatchWorkflow",forceCancelWorkflowRun:"actions.forceCancelWorkflowRun",getJobForWorkflowRun:"actions.getJobForWorkflowRun",getWorkflowRun:"actions.getWorkflowRun",getWorkflowRunAttempt:"actions.getWorkflowRunAttempt",listJobsForWorkflowRun:"actions.listJobsForWorkflowRun",listJobsForWorkflowRunAttempt:"actions.listJobsForWorkflowRunAttempt",listRepoWorkflows:"actions.listRepoWorkflows",listWorkflowRuns:"actions.listWorkflowRuns",listWorkflowRunsForRepo:"actions.listWorkflowRunsForRepo",reRunJobForWorkflowRun:"actions.reRunJobForWorkflowRun",reRunWorkflow:"actions.reRunWorkflow",reRunWorkflowFailedJobs:"actions.reRunWorkflowFailedJobs"},apps:{createInstallationAccessToken:"apps.createInstallationAccessToken",getAuthenticated:"apps.getAuthenticated",getInstallation:"apps.getInstallation",updateWebhookConfigForApp:"apps.updateWebhookConfigForApp"},repos:{listPullRequestsAssociatedWithCommit:"repos.listPullRequestsAssociatedWithCommit"},users:{listEmailsForAuthenticatedUser:"users.listEmailsForAuthenticatedUser"}}],334416);var s=e.i(666680);let o=/^[_A-Za-z][_0-9A-Za-z]*$/,l=new Map([["GitHubWorktreePullRequestStatuses",60]]),u=[{window:"5m",milliseconds:3e5},{window:"10m",milliseconds:6e5},{window:"1h",milliseconds:36e5},{window:"24h",milliseconds:864e5}];function c(e){return JSON.stringify(function e(t){return Array.isArray(t)?t.map(e):t&&"object"==typeof t?Object.fromEntries(Object.keys(t).sort().map(r=>[r,e(t[r])])):t}(e))}let d=/(?:authorization|password|private.?key|secret|token)$/i;function h(e,t=""){return d.test(t)?"[REDACTED]":Array.isArray(e)?e.map(e=>h(e)):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,h(t,e)])):e}function p(e){try{return JSON.parse(e)}catch{return null}}function m(e){return e&&"object"==typeof e?{statusCode:"number"==typeof e.statusCode?e.statusCode:null,rateLimit:e.rateLimit&&"object"==typeof e.rateLimit?e.rateLimit:null}:{statusCode:null,rateLimit:null}}e.s(["GitHubCache",0,class{recordCallLogs;inFlight;cacheWrites;cacheGeneration;lastPrunedAt;constructor(e="true"!==process.env.GITHUB_CACHE_LOGGING_DISABLED){this.recordCallLogs=e,this.inFlight=new Map,this.cacheWrites=new Set,this.cacheGeneration=0,this.lastPrunedAt=0}cacheKey(e){return(0,s.createHash)("sha256").update(c({authentication:e.authentication,endpoint:e.endpoint,query:e.normalizedQuery,variables:e.variables})).digest("hex")}inFlightKey(e,t,r){return[r,e,!0===t.force?"force":"normal",!1===t.allowStaleOnError?"strict":"stale"].join(":")}async defaultTtlSeconds(){let e=await (0,t.getPrismaClient)();return(await e.gitHubSettings.upsert({where:{id:"default"},create:{id:"default",cacheTtlSeconds:300},update:{}})).cacheTtlSeconds}async effectiveTtlSeconds(e){let r=await (0,t.getPrismaClient)(),[i,a]=await Promise.all([r.gitHubGraphqlCacheTtlOverride.findUnique({where:{operation:e}}),this.defaultTtlSeconds()]);return i?.ttlSeconds??a}async query(e){let r=this.cacheGeneration,i=await (0,t.getPrismaClient)(),a=this.cacheKey(e),n=this.inFlightKey(a,e,r),o=Date.now(),[l,u,d]=await Promise.all([i.gitHubGraphqlCacheEntry.findUnique({where:{cacheKey:a}}),this.effectiveTtlSeconds(e.operation),i.gitHubRateLimitSnapshot.findUnique({where:{authentication_resource:{authentication:e.authentication,resource:"graphql"}}})]);if(r!==this.cacheGeneration)return this.query(e);let h=null!==l&&Date.now()-l.fetchedAt.getTime()<1e3*u;if(!e.force&&h)return(await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"CACHE",durationMs:Date.now()-o,pointCost:0,pointsAvoided:l.pointCost??0}).catch(()=>void 0),r!==this.cacheGeneration)?this.query(e):{data:p(l.responseJson),source:"CACHE",stale:!1,fetchedAt:l.fetchedAt,entryId:l.id,pointCost:l.pointCost};let f=this.inFlight.get(n);if(f){let t=await f;return r!==this.cacheGeneration||(await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"CACHE",durationMs:Date.now()-o,pointCost:0,pointsAvoided:t.pointCost??0}).catch(()=>void 0),r!==this.cacheGeneration)?this.query(e):{...t,source:"CACHE"}}if(d?.remaining===0&&d.resetAt.getTime()>Date.now()){let t=`GitHub GraphQL rate limit is exhausted until ${d.resetAt.toISOString()}`,i=null!==l&&!1!==e.allowStaleOnError;if(await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"ERROR",durationMs:Date.now()-o,error:t,servedStale:i,pointCost:0,pointsAvoided:i?l.pointCost??0:0,rateLimit:{limit:d.limit,remaining:d.remaining,used:d.used,resetAt:d.resetAt,resource:d.resource}}).catch(()=>void 0),r!==this.cacheGeneration)return this.query(e);if(i)return{data:p(l.responseJson),source:"ERROR",stale:!0,fetchedAt:l.fetchedAt,entryId:l.id,pointCost:l.pointCost};throw Error(t)}let g=(async()=>{try{let t=await e.fetcher(),n=new Date,l=null;if(r===this.cacheGeneration){let r=i.gitHubGraphqlCacheEntry.upsert({where:{cacheKey:a},create:{id:(0,s.randomUUID)(),cacheKey:a,authentication:e.authentication,endpoint:e.endpoint,operation:e.operation,query:e.query,variablesJson:c(e.variables),responseJson:JSON.stringify(t.data),fetchedAt:n,pointCost:t.pointCost},update:{operation:e.operation,query:e.query,variablesJson:c(e.variables),responseJson:JSON.stringify(t.data),fetchedAt:n,pointCost:t.pointCost}});this.cacheWrites.add(r);try{l=await r}finally{this.cacheWrites.delete(r)}}return await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"LIVE",durationMs:Date.now()-o,statusCode:t.statusCode,pointCost:t.pointCost,rateLimit:t.rateLimit}).catch(()=>void 0),{data:t.data,source:"LIVE",stale:!1,fetchedAt:n,entryId:r===this.cacheGeneration?l?.id??null:null,pointCost:t.pointCost}}catch(a){let t=m(a),i=r===this.cacheGeneration&&null!==l&&!1!==e.allowStaleOnError;if(await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"ERROR",durationMs:Date.now()-o,statusCode:t.statusCode,error:a instanceof Error?a.message:String(a),servedStale:i,pointsAvoided:i?l?.pointCost??0:0,rateLimit:t.rateLimit}).catch(()=>void 0),r!==this.cacheGeneration)throw a;if(i)return{data:p(l.responseJson),source:"ERROR",stale:!0,fetchedAt:l.fetchedAt,entryId:l.id,pointCost:l.pointCost};throw a}})();this.inFlight.set(n,g);try{return await g}finally{this.inFlight.get(n)===g&&this.inFlight.delete(n)}}async mutation(e){let t,r=Date.now();try{t=await e.fetcher()}catch(i){let t=m(i);throw await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"ERROR",durationMs:Date.now()-r,statusCode:t.statusCode,error:i instanceof Error?i.message:String(i),rateLimit:t.rateLimit}).catch(()=>void 0),i}return await this.clear(),await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"LIVE",durationMs:Date.now()-r,statusCode:t.statusCode,pointCost:null,rateLimit:t.rateLimit}).catch(()=>void 0),t.data}async updateTtl(e,r){if(!Number.isInteger(e)||e<1||e>1440)throw Error("Cache TTL must be an integer from 1 to 1440 minutes");let i=await (0,t.getPrismaClient)();return await i.gitHubSettings.upsert({where:{id:"default"},create:{id:"default",cacheTtlSeconds:60*e},update:{cacheTtlSeconds:60*e}}),r()}async ttlOverrides(){let e=await (0,t.getPrismaClient)();return(await e.gitHubGraphqlCacheTtlOverride.findMany({orderBy:{operation:"asc"}})).map(e=>({operation:e.operation,ttlSeconds:e.ttlSeconds,builtIn:l.has(e.operation),createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString()}))}async cacheableOperations(){let e=await (0,t.getPrismaClient)(),[r,i]=await Promise.all([e.gitHubGraphqlCacheTtlOverride.findMany({select:{operation:!0}}),e.gitHubGraphqlCacheEntry.findMany({distinct:["operation"],select:{operation:!0}})]);return[...new Set([...l.keys(),...r.map(({operation:e})=>e),...i.map(({operation:e})=>e)])].sort((e,t)=>e.localeCompare(t))}async saveTtlOverride(e,r){let i=e.trim();if(!o.test(i))throw Error("Operation must be a valid GraphQL operation name");if(!Number.isInteger(r)||r<1||r>86400)throw Error("Cache TTL must be an integer from 1 to 86400 seconds");let a=await (0,t.getPrismaClient)(),n=await a.gitHubGraphqlCacheTtlOverride.upsert({where:{operation:i},create:{operation:i,ttlSeconds:r},update:{ttlSeconds:r}});return{operation:n.operation,ttlSeconds:n.ttlSeconds,builtIn:l.has(n.operation),createdAt:n.createdAt.toISOString(),updatedAt:n.updatedAt.toISOString()}}async deleteTtlOverride(e){let r=e.trim();if(l.has(r))throw Error("Built-in cache TTL overrides cannot be deleted");let i=await (0,t.getPrismaClient)();return(await i.gitHubGraphqlCacheTtlOverride.deleteMany({where:{operation:r}})).count>0}async recordRestCall(e){let t=e.endpoint,r={};try{let i=new URL(e.endpoint);t=i.pathname,r={path:i.pathname,query:Object.fromEntries(i.searchParams)}}catch{r={endpoint:e.endpoint}}await this.log({authentication:e.authentication,apiType:"REST",method:e.method.toUpperCase(),endpoint:e.endpoint,operation:e.operation,requestSource:e.requestSource,requestSummary:`${e.method.toUpperCase()} ${t}`,variables:r,source:e.error?"ERROR":"LIVE",durationMs:e.durationMs,statusCode:e.statusCode,error:e.error,pointCost:1,rateLimit:e.rateLimit})}async recordGraphqlTransportCall(e){await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,requestSource:e.requestSource,source:e.error?"ERROR":"LIVE",durationMs:e.durationMs,statusCode:e.statusCode,error:e.error,rateLimit:e.rateLimit})}async clear(){let{cacheWrites:e}=this.beginInvalidation();await Promise.allSettled(e);let r=await (0,t.getPrismaClient)();return await r.gitHubGraphqlCacheEntry.deleteMany(),!0}async clearForCredentialChange(e){let{cacheWrites:r,inFlight:i}=this.beginInvalidation();await Promise.allSettled(r);let a=await (0,t.getPrismaClient)();return await a.gitHubGraphqlCacheEntry.deleteMany(),await Promise.allSettled(i),await a.gitHubRateLimitSnapshot.deleteMany({where:{authentication:e}}),!0}async clearCalls(){let e=await (0,t.getPrismaClient)();return await e.gitHubApiCallLog.deleteMany(),!0}async delete(e){let r=await (0,t.getPrismaClient)();return(await r.gitHubGraphqlCacheEntry.deleteMany({where:{id:e}})).count>0}async entries(e=50,r=0){let i=this.pagination(e,r),a=await (0,t.getPrismaClient)(),[n,s,o,l]=await Promise.all([a.gitHubGraphqlCacheEntry.findMany({take:i.limit,skip:i.offset,orderBy:{fetchedAt:"desc"}}),a.gitHubGraphqlCacheEntry.count(),this.defaultTtlSeconds(),a.gitHubGraphqlCacheTtlOverride.findMany({select:{operation:!0,ttlSeconds:!0}})]),u=new Map(l.map(({operation:e,ttlSeconds:t})=>[e,t]));return{...i,total:s,items:n.map(e=>this.entryView(e,u.get(e.operation)??o))}}async entry(e){let r=await (0,t.getPrismaClient)(),i=await r.gitHubGraphqlCacheEntry.findUnique({where:{id:e}});if(!i)return null;let a=await this.effectiveTtlSeconds(i.operation);return{...this.entryView(i,a),query:i.query,variables:p(i.variablesJson),response:p(i.responseJson)}}async calls(e=50,r=0,i={}){let a=this.pagination(e,r);await this.pruneLogs();let n=await (0,t.getPrismaClient)(),s={...i.apiType?{apiType:i.apiType}:{},...i.requestSource?{requestSource:i.requestSource}:{},...i.source?{source:i.source}:{}},[o,l]=await Promise.all([n.gitHubApiCallLog.findMany({where:s,take:a.limit,skip:a.offset,orderBy:{createdAt:"desc"}}),n.gitHubApiCallLog.count({where:s})]);return{...a,total:l,items:o.map(e=>({id:e.id,authentication:e.authentication,apiType:e.apiType,method:e.method,endpoint:e.endpoint,operation:e.operation,requestSource:e.requestSource,requestSummary:e.requestSummary,variables:p(e.variablesJson),source:e.source,durationMs:e.durationMs,statusCode:e.statusCode,error:e.error,servedStale:e.servedStale,pointCost:e.pointCost,pointsAvoided:e.pointsAvoided,rateLimitLimit:e.rateLimitLimit,rateLimitRemaining:e.rateLimitRemaining,rateLimitUsed:e.rateLimitUsed,rateLimitResetAt:e.rateLimitResetAt?.toISOString()??null,rateLimitResource:e.rateLimitResource,createdAt:e.createdAt.toISOString()}))}}async metrics(){await this.pruneLogs();let e=await (0,t.getPrismaClient)(),r=Date.now(),i=await e.gitHubApiCallLog.findMany({where:{createdAt:{gte:new Date(r-u.at(-1).milliseconds)}},orderBy:{createdAt:"asc"}}),a=u.map(e=>this.metricWindow(e.window,i.filter(t=>t.createdAt.getTime()>=r-e.milliseconds)));return{windows:a,apiTypes:["GRAPHQL","REST"].map(e=>({apiType:e,windows:u.map(t=>this.metricWindow(t.window,i.filter(i=>i.apiType===e&&i.createdAt.getTime()>=r-t.milliseconds)))})),operations:[...new Set(i.map(e=>e.operation))].sort().map(e=>({operation:e,windows:u.map(t=>this.metricWindow(t.window,i.filter(i=>i.operation===e&&i.createdAt.getTime()>=r-t.milliseconds)))})),requestSources:[...new Set(i.map(e=>e.requestSource))].sort().map(e=>({requestSource:e,windows:u.map(t=>this.metricWindow(t.window,i.filter(i=>i.requestSource===e&&i.createdAt.getTime()>=r-t.milliseconds)))}))}}entryView(e,t){return{id:e.id,authentication:e.authentication,operation:e.operation,endpoint:e.endpoint,fetchedAt:e.fetchedAt.toISOString(),pointCost:e.pointCost,stale:Date.now()-e.fetchedAt.getTime()>=1e3*t}}metricWindow(e,t){let r=t.length;return{window:e,total:r,live:t.filter(e=>"LIVE"===e.source).length,cache:t.filter(e=>"CACHE"===e.source).length,errors:t.filter(e=>"ERROR"===e.source).length,averageMs:0===r?0:Math.round(t.reduce((e,t)=>e+t.durationMs,0)/r),pointsUsed:t.reduce((e,t)=>e+Math.max(0,t.pointCost??0),0),pointsAvoided:t.reduce((e,t)=>e+Math.max(0,t.pointsAvoided),0)}}pagination(e,t){if(!Number.isInteger(e)||e<1||e>100)throw Error("limit must be an integer from 1 to 100");if(!Number.isInteger(t)||t<0)throw Error("offset must be a non-negative integer");return{limit:e,offset:t}}beginInvalidation(){let e=[...this.cacheWrites],t=[...new Set(this.inFlight.values())];return this.cacheGeneration+=1,this.inFlight.clear(),{cacheWrites:e,inFlight:t}}graphqlContext(e){let t=h(e.variables);return{apiType:"GRAPHQL",method:"POST",endpoint:e.endpoint,requestSource:e.requestSource,requestSummary:function(e){if(!e||"object"!=typeof e||Array.isArray(e))return"No variables";let t=Object.entries(e);return t.length?t.map(([e,t])=>{let r=("string"==typeof t?t:JSON.stringify(t))??String(t);return`${e}=${r.length>120?`${r.slice(0,117)}…`:r}`}).join(" · "):"No variables"}(t),variables:t}}async log(e){if(!this.recordCallLogs)return;await this.pruneLogs();let r=await (0,t.getPrismaClient)();await r.gitHubApiCallLog.create({data:{id:(0,s.randomUUID)(),authentication:e.authentication,apiType:e.apiType,method:e.method,endpoint:e.endpoint,operation:e.operation,requestSource:e.requestSource,requestSummary:e.requestSummary,variablesJson:c(h(e.variables)),source:e.source,durationMs:Math.max(0,Math.round(e.durationMs)),statusCode:e.statusCode??null,error:e.error?.slice(0,2e3)??null,servedStale:e.servedStale??!1,pointCost:e.pointCost??null,pointsAvoided:Math.max(0,e.pointsAvoided??0),rateLimitLimit:e.rateLimit?.limit??null,rateLimitRemaining:e.rateLimit?.remaining??null,rateLimitUsed:e.rateLimit?.used??null,rateLimitResetAt:e.rateLimit?.resetAt??null,rateLimitResource:e.rateLimit?.resource??null}})}async pruneLogs(){let e=Date.now();if(e-this.lastPrunedAt<36e5)return;this.lastPrunedAt=e;let r=await (0,t.getPrismaClient)();await r.gitHubApiCallLog.deleteMany({where:{createdAt:{lt:new Date(e-2592e6)}}})}}],919412);let f=(process.env.GITHUB_API_BASE_URL||"https://api.github.com").replace(/\/+$/,""),g=process.env.GITHUB_GRAPHQL_URL||`${f}/graphql`;e.s(["GITHUB_API_BASE_URL",0,f,"GITHUB_GRAPHQL_URL",0,g],407188)},112627,685155,e=>{"use strict";var t=e.i(666680),r=e.i(243783),i=e.i(483291);e.i(582482);var a=e.i(318905),n=e.i(91022),s=e.i(783396),o=e.i(397554),l=e.i(827957),u=e.i(616204),c=e.i(334416);class d extends Error{code;githubRequestId;statusCode;rateLimit;constructor(e,t,r=null,i=null,a=null){super(t),this.code=e,this.githubRequestId=r,this.statusCode=i,this.rateLimit=a,this.name="GitHubAppError"}}let h=new Map,p=new Map;function m(e,t,r){let i=e.trim();if(!/^[1-9]\d*$/.test(i))throw new d(r,`${t} must be a positive integer`);return i}function f(e){let{privateKeyPkcs8:r,keyFingerprint:i}=function(e){try{let r=(0,t.createPrivateKey)({key:e.trim(),format:"pem"});if("rsa"!==r.asymmetricKeyType)throw Error("The key is not RSA");let i=r.export({format:"pem",type:"pkcs8"}).toString(),a=(0,t.createPublicKey)(r).export({format:"der",type:"spki"}),n=`SHA256:${(0,t.createHash)("sha256").update(a).digest("base64url")}`;return{key:r,privateKeyPkcs8:i,keyFingerprint:n}}catch{throw new d("INVALID_PRIVATE_KEY","The GitHub App private key is not a valid RSA PEM")}}(e.privateKey);return{...e,appId:m(e.appId,"GitHub App ID","INVALID_APP_ID"),installationId:m(e.installationId,"GitHub installation ID","INVALID_INSTALLATION_ID"),privateKeyPkcs8:r,keyFingerprint:i}}async function g(e){try{let t=await (0,o.importPKCS8)(e.privateKeyPkcs8,"RS256"),r=Math.floor(Date.now()/1e3);return await new l.SignJWT({}).setProtectedHeader({alg:"RS256",typ:"JWT"}).setIssuer(e.appId).setIssuedAt(r-60).setExpirationTime(r+540).sign(t)}catch{throw new d("INVALID_PRIVATE_KEY","The GitHub App private key could not sign an App JWT")}}function y(e){return`${e.appId}:${e.installationId}:${e.keyFingerprint}`}function w(e){return{accept:"application/vnd.github+json",authorization:e,"user-agent":"ai-development-environment","x-github-api-version":"2022-11-28"}}async function b(e,t,r,i,a){let n,s=Date.now(),o=(t.method??"GET").toUpperCase(),l=e===i?.graphqlUrl&&"string"==typeof t.body?t.body:null;try{n=await fetch(e,{...t,cache:"no-store"})}catch{throw i?.requestObserver&&await Promise.resolve(i.requestObserver({url:e,method:o,operation:r,requestSource:a,body:l,durationMs:Date.now()-s,statusCode:null,error:"GitHub could not be reached",rateLimit:null})).catch(()=>void 0),new d("GITHUB_APP_REQUEST_FAILED","GitHub could not be reached")}return i?.responseObserver&&await Promise.resolve(i.responseObserver(n)).catch(()=>void 0),i?.requestObserver&&await Promise.resolve(i.requestObserver({url:e,method:o,operation:r,requestSource:a,body:l,durationMs:Date.now()-s,statusCode:n.status,error:n.ok?null:`GitHub returned HTTP ${n.status}`,rateLimit:(0,u.parseGitHubRateLimitHeaders)(n.headers)})).catch(()=>void 0),n}async function E(e){try{return await e.json()}catch{return null}}function S(e){return e.headers.get("x-github-request-id")}function v(e,t,r=[]){let i=`GitHub returned HTTP ${t}`;for(let t of(e&&"object"==typeof e&&"message"in e&&"string"==typeof e.message&&(i=e.message),r))t&&(i=i.split(t).join("[REDACTED]"));return i}async function I(e,t){let r=await b(`${e.apiBaseUrl}/app/installations/${e.installationId}`,{headers:w(`Bearer ${t}`)},c.GITHUB_REST_OPERATIONS.apps.getInstallation,e,"GITHUB_SETTINGS"),i=await E(r),a=S(r);if(401===r.status)throw new d("GITHUB_APP_UNAUTHORIZED","GitHub rejected the App ID or private key",a);if(404===r.status)throw new d("INSTALLATION_NOT_FOUND","The GitHub App installation was not found",a);if(!r.ok||!i||"object"!=typeof i)throw new d("GITHUB_APP_REQUEST_FAILED",v(i,r.status,[t,e.privateKey,e.privateKeyPkcs8]),a);if(String(i.app_id)!==e.appId)throw new d("APP_INSTALLATION_MISMATCH","The installation does not belong to the configured GitHub App",a);return i}async function A(e,t){let r=await b(`${e.apiBaseUrl}/app`,{headers:w(`Bearer ${t}`)},c.GITHUB_REST_OPERATIONS.apps.getAuthenticated,e,"GITHUB_SETTINGS"),i=await E(r),a=S(r);if(401===r.status)throw new d("GITHUB_APP_UNAUTHORIZED","GitHub rejected the App ID or private key",a);if(!r.ok||!i||"object"!=typeof i)throw new d("GITHUB_APP_REQUEST_FAILED",v(i,r.status,[t,e.privateKey,e.privateKeyPkcs8]),a);if(String(i.id)!==e.appId||!i.slug||!i.owner?.login||!i.owner.type)throw new d("GITHUB_APP_REQUEST_FAILED","GitHub returned incomplete GitHub App registration details",a);return{details:i,githubRequestId:a}}async function k(e){let t=f(e),r=await g(t),i=await A(t,r);return{appSlug:i.details.slug,appOwnerLogin:i.details.owner.login,appOwnerType:i.details.owner.type,githubRequestId:i.githubRequestId}}async function _(e,t,r){let i=r??await g(e),a=await b(`${e.apiBaseUrl}/app/installations/${e.installationId}/access_tokens`,{method:"POST",headers:w(`Bearer ${i}`)},c.GITHUB_REST_OPERATIONS.apps.createInstallationAccessToken,e,t),n=await E(a),s=S(a);if(401===a.status)throw new d("GITHUB_APP_UNAUTHORIZED","GitHub rejected the App ID or private key",s);if(404===a.status)throw new d("INSTALLATION_NOT_FOUND","The GitHub App installation was not found",s);if(!a.ok||!n||"object"!=typeof n)throw new d("GITHUB_APP_REQUEST_FAILED",v(n,a.status,[i,e.privateKey,e.privateKeyPkcs8]),s);if("string"!=typeof n.token||!n.token||"string"!=typeof n.expires_at||Number.isNaN(Date.parse(n.expires_at)))throw new d("GITHUB_APP_REQUEST_FAILED","GitHub returned an invalid installation token response",s);if("write"!==(n.permissions?.actions??"none"))throw new d("ACTIONS_PERMISSION_REQUIRED","The GitHub App installation must grant Actions: read and write",s);return{token:n.token,expiresAt:new Date(n.expires_at),permissions:n.permissions??{},repositorySelection:n.repository_selection??"selected"}}async function T(e,t){let r=y(e),i=h.get(r);if(i&&i.expiresAt.getTime()-3e5>Date.now())return i;let a=p.get(r);if(a)return a;let n=_(e,t).then(e=>(h.set(r,e),e)).finally(()=>p.delete(r));return p.set(r,n),n}function C(){h.clear(),p.clear()}async function R(e,t,r){let i=f(e),a=await T(i,r),n=await t(a.token);return 401===n.status&&(h.delete(y(i)),a=await T(i,r),n=await t(a.token)),{response:n,token:a.token}}async function N(e,t,r,i){let{response:a,token:n}=await R(e,a=>b(e.graphqlUrl,{method:"POST",headers:{...w(`Bearer ${a}`),"content-type":"application/json"},body:JSON.stringify({query:t,variables:r})},null,e,i),i),s=await E(a),o=S(a),l=(0,u.parseGitHubRateLimitHeaders)(a.headers);if(401===a.status)throw new d("GITHUB_APP_UNAUTHORIZED","GitHub rejected the installation access token",o,a.status,l);if(!a.ok||s?.errors?.length||!s?.data){let t=s?.errors?.map(e=>e.message).filter(Boolean).join("; ")||v(s,a.status,[n]);throw new d("GITHUB_APP_REQUEST_FAILED",v({message:t},a.status,[n,e.privateKey]),o,a.status,l)}return{data:s.data,githubRequestId:o,statusCode:a.status,rateLimit:l}}async function O(e){let t=f(e),r=await g(t),[i,a]=await Promise.all([I(t,r),A(t,r)]),n=await _(t,"GITHUB_SETTINGS",r);h.set(y(t),n);let s=await N(t,"query VerifyGitHubApp { viewer { login } }",{},"GITHUB_SETTINGS");return{appId:t.appId,installationId:t.installationId,keyFingerprint:t.keyFingerprint,appSlug:a.details.slug,appOwnerLogin:a.details.owner.login,appOwnerType:a.details.owner.type,accountLogin:i.account.login,repositorySelection:n.repositorySelection,actionsPermission:n.permissions.actions??"none",checksPermission:n.permissions.checks??"none",commitStatusesPermission:n.permissions.statuses??"none",webhookEvents:Array.isArray(i.events)?i.events:[],viewerLogin:s.data.viewer.login,verifiedAt:new Date,githubRequestId:s.githubRequestId}}async function D(e,t){let r=f(e),i=await g(r),a=await b(`${r.apiBaseUrl}/app/hook/config`,{method:"PATCH",headers:{...w(`Bearer ${i}`),"content-type":"application/json"},body:JSON.stringify({url:t.url,content_type:"json",secret:t.secret,insecure_ssl:"0"})},c.GITHUB_REST_OPERATIONS.apps.updateWebhookConfigForApp,r,"GITHUB_SETTINGS"),n=S(a);if(404===a.status)return{configured:!1,githubRequestId:n};if(!a.ok)throw new d("GITHUB_APP_REQUEST_FAILED",v(await E(a),a.status,[i,t.secret,r.privateKey]),n);return{configured:!0,githubRequestId:n}}async function P(e,t){let r=`${e.apiBaseUrl}/repos/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repository)}/actions/runs/${encodeURIComponent(t.workflowRunId)}/rerun`,{response:i,token:a}=await R(e,i=>b(r,{method:"POST",headers:w(`Bearer ${i}`)},c.GITHUB_REST_OPERATIONS.actions.reRunWorkflow,e,t.requestSource),t.requestSource),n=S(i);if(401===i.status)throw new d("GITHUB_APP_UNAUTHORIZED","GitHub rejected the installation access token",n);if(!i.ok){let t=await E(i);throw new d(404===i.status?"REPOSITORY_NOT_INSTALLED":"GITHUB_APP_REQUEST_FAILED",404===i.status?"The repository or workflow run is not available to this installation":v(t,i.status,[a,e.privateKey]),n)}return{githubRequestId:n}}async function x(e,t){let r=`${e.apiBaseUrl}/repos/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repository)}/actions/runs/${encodeURIComponent(t.workflowRunId)}/rerun-failed-jobs`,{response:i,token:a}=await R(e,i=>b(r,{method:"POST",headers:w(`Bearer ${i}`)},c.GITHUB_REST_OPERATIONS.actions.reRunWorkflowFailedJobs,e,t.requestSource),t.requestSource),n=S(i);if(!i.ok){let t=await E(i);throw new d(404===i.status?"REPOSITORY_NOT_INSTALLED":"GITHUB_APP_REQUEST_FAILED",404===i.status?"The repository or workflow run is not available to this installation":v(t,i.status,[a,e.privateKey]),n)}return{githubRequestId:n}}async function L(e,t){let r=t.force?"force-cancel":"cancel",i=t.force?c.GITHUB_REST_OPERATIONS.actions.forceCancelWorkflowRun:c.GITHUB_REST_OPERATIONS.actions.cancelWorkflowRun,a=`${e.apiBaseUrl}/repos/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repository)}/actions/runs/${encodeURIComponent(t.workflowRunId)}/${r}`,{response:n,token:s}=await R(e,r=>b(a,{method:"POST",headers:w(`Bearer ${r}`)},i,e,t.requestSource),t.requestSource),o=S(n);if(401===n.status)throw new d("GITHUB_APP_UNAUTHORIZED","GitHub rejected the installation access token",o);if(!n.ok){let t=await E(n);throw new d(404===n.status?"REPOSITORY_NOT_INSTALLED":"GITHUB_APP_REQUEST_FAILED",404===n.status?"The repository or workflow run is not available to this installation":v(t,n.status,[s,e.privateKey]),o)}return{githubRequestId:o}}async function U(e,t){let r=[],i=1,a=0;do{let n=`${e.apiBaseUrl}/repos/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repository)}/actions/runs/${encodeURIComponent(t.workflowRunId)}/jobs?filter=latest&per_page=100&page=${i}`,{response:s,token:o}=await R(e,r=>b(n,{headers:w(`Bearer ${r}`)},c.GITHUB_REST_OPERATIONS.actions.listJobsForWorkflowRun,e,t.requestSource),t.requestSource),l=S(s);if(401===s.status)throw new d("GITHUB_APP_UNAUTHORIZED","GitHub rejected the installation access token",l);let u=await E(s);if(!s.ok||!u||"object"!=typeof u)throw new d("GITHUB_APP_REQUEST_FAILED",v(u,s.status,[o,e.privateKey]),l);if(!Number.isInteger(u.total_count)||!Array.isArray(u.jobs))throw new d("GITHUB_APP_REQUEST_FAILED","GitHub returned an invalid workflow jobs response",l);a=u.total_count??0,r.push(...u.jobs),i+=1}while(r.length<a)return r}async function B(e,t){let r=`${e.apiBaseUrl}/repos/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repository)}`,i=`${r}/actions/jobs/${encodeURIComponent(t.jobId)}`,a=await R(e,r=>b(i,{headers:w(`Bearer ${r}`)},c.GITHUB_REST_OPERATIONS.actions.getJobForWorkflowRun,e,t.requestSource),t.requestSource),n=S(a.response);if(401===a.response.status)throw new d("GITHUB_APP_UNAUTHORIZED","GitHub rejected the installation access token",n);let s=await E(a.response);if(!a.response.ok||!s||"object"!=typeof s)throw new d(404===a.response.status?"ACTIONS_JOB_NOT_FOUND":"GITHUB_APP_REQUEST_FAILED",404===a.response.status?"The GitHub Actions job is not available to this installation":v(s,a.response.status,[a.token,e.privateKey]),n);if(String(s.run_id??"")!==t.workflowRunId)throw new d("ACTIONS_JOB_RUN_MISMATCH","The GitHub Actions job does not belong to the selected workflow run",n);if(s.status?.toLowerCase()!=="completed")throw new d("ACTIONS_JOB_NOT_COMPLETED","The GitHub Actions job must be completed before it can be retried",n);let o=await R(e,r=>b(`${i}/rerun`,{method:"POST",headers:w(`Bearer ${r}`)},c.GITHUB_REST_OPERATIONS.actions.reRunJobForWorkflowRun,e,t.requestSource),t.requestSource),l=S(o.response);if(401===o.response.status)throw new d("GITHUB_APP_UNAUTHORIZED","GitHub rejected the installation access token",l);if(!o.response.ok){let t=await E(o.response);throw new d(404===o.response.status?"ACTIONS_JOB_NOT_FOUND":"GITHUB_APP_REQUEST_FAILED",404===o.response.status?"The GitHub Actions job is not available to this installation":v(t,o.response.status,[o.token,e.privateKey]),l)}return{githubRequestId:l}}let M=new Set(["FAILURE","ERROR","STARTUP_FAILURE","TIMED_OUT"]),q=new Set(["ACTION_REQUIRED","EXPECTED","IN_PROGRESS","PENDING","QUEUED"]),j=["COMPLETED","EXHAUSTED","STOPPED"],$={WORKFLOW_RUN:4,PULL_REQUEST:3,WORKTREE_BRANCH:2,REPOSITORY:1},G="server:github-auto-retry";function F(e){return e.toISOString()}function z(e){return{...e,scope:e.scope,mode:e.mode,failureStrategy:e.failureStrategy,status:e.status,executions:e.executions.map(e=>({...e,lastStatus:e.lastStatus,updatedAt:F(e.updatedAt)})),createdAt:F(e.createdAt),updatedAt:F(e.updatedAt)}}class H{github;polling;timer;pollingTickRunning;rerunRequested;reconciling;constructor(e,t,r=!0){this.github=e,this.polling=t,this.timer=null,this.pollingTickRunning=!1,this.rerunRequested=!1,this.reconciling=!1,this.polling?.register({id:G,kind:"GITHUB_AUTO_RETRY",runtime:"SERVER",enabled:!0,cadenceSeconds:60,details:{}}),r&&queueMicrotask(()=>void this.pollReconcile())}schedule(e){this.timer&&clearTimeout(this.timer);let t=1e3*Math.max(30,e);this.timer=setTimeout(()=>void this.pollReconcile(),t),this.timer.unref(),this.polling?.schedule(G,new Date(Date.now()+t))}configurationChanged(){if(this.pollingTickRunning){this.rerunRequested=!0;return}this.timer&&clearTimeout(this.timer),this.timer=null,queueMicrotask(()=>void this.pollReconcile())}async pollReconcile(){if(this.pollingTickRunning)return;this.pollingTickRunning=!0;let e=60;try{let t=async()=>(e=(await (await (0,r.getPrismaClient)()).gitHubSettings.upsert({where:{id:"default"},create:{id:"default"},update:{}})).actionsNotificationPollIntervalSeconds,this.polling?.configure(G,{cadenceSeconds:e}),this.reconcile());this.polling?await this.polling.run(G,t,e=>({activeRules:e})):await t()}catch{}finally{this.pollingTickRunning=!1,this.rerunRequested?(this.rerunRequested=!1,queueMicrotask(()=>void this.pollReconcile())):this.schedule(e)}}include(){return{targets:{orderBy:{createdAt:"asc"}},executions:{orderBy:{updatedAt:"desc"}}}}async list(e){let t=await (0,r.getPrismaClient)(),i=e.codebaseRepositoryId?await this.github.autoRetryRepositoryId(e.codebaseRepositoryId):null;return(await t.gitHubAutoRetryRule.findMany({where:{...i?{codebaseRepositoryId:i}:{},...e.workflowRunId?{targets:{some:{workflowRunId:e.workflowRunId}}}:{}},include:this.include(),orderBy:{updatedAt:"desc"}})).map(z)}validate(e){if(!e.codebaseRepositoryId.trim())throw Error("Codebase repository is required");if("COUNT"===e.mode&&null==e.retryLimit)throw Error("Count mode requires a retry limit");if(null!=e.retryLimit&&(!Number.isInteger(e.retryLimit)||e.retryLimit<1||e.retryLimit>100))throw Error("Retry limit must be an integer from 1 to 100");if("FAILURE"===e.mode&&void 0===e.retryLimit)throw Error("Failure retry limit must be a number or null");if("WORKFLOW_RUN"===e.scope){if(!e.targets.length||e.targets.some(e=>!e.workflowRunId))throw Error("Current-run rules require workflow run targets")}else if(!e.allWorkflows&&!e.targets.length)throw Error("Select at least one workflow or choose all workflows");if("WORKTREE_BRANCH"===e.scope&&!e.worktreeId)throw Error("Worktree future rules require a worktree");if("PULL_REQUEST"===e.scope&&!e.pullRequestNumber)throw Error("Pull request future rules require a pull request number")}async save(e){if(!await this.github.autoRetryCredentialsReady())throw Error("A GitHub token and verified GitHub App with Actions write access are required");e={...e,codebaseRepositoryId:await this.github.autoRetryRepositoryId(e.codebaseRepositoryId)},this.validate(e);let i=await (0,r.getPrismaClient)(),a=e.branch?.trim()||null;if("WORKTREE_BRANCH"===e.scope&&e.worktreeId){let t=await i.worktree.findUnique({where:{id:e.worktreeId},select:{branch:!0}});if(!(a=t?.branch??null))throw Error("The worktree does not have a branch")}let n=await i.gitHubAutoRetryRule.findMany({where:{id:e.id?{not:e.id}:void 0,enabled:!0,scope:e.scope,codebaseRepositoryId:e.codebaseRepositoryId},include:{targets:!0}}),s=new Set(e.targets.map(e=>e.workflowRunId).filter(e=>!!e));if(n.find(t=>"WORKFLOW_RUN"===e.scope?t.targets.some(e=>e.workflowRunId&&s.has(e.workflowRunId)):"WORKTREE_BRANCH"===e.scope?t.branch===a:"PULL_REQUEST"!==e.scope||t.pullRequestNumber===e.pullRequestNumber))throw Error("An enabled Auto Retry rule already exists for this scope");let o=e.id??(0,t.randomUUID)(),l=await i.$transaction(async r=>(await r.gitHubAutoRetryRule.upsert({where:{id:o},create:{id:o,scope:e.scope,codebaseRepositoryId:e.codebaseRepositoryId,repositoryGithubId:e.repositoryGithubId??null,worktreeId:e.worktreeId??null,branch:a,pullRequestNumber:e.pullRequestNumber??null,allWorkflows:e.allWorkflows,mode:e.mode,retryLimit:e.retryLimit??null,failureStrategy:e.failureStrategy,status:"ACTIVE",enabled:!0},update:{scope:e.scope,codebaseRepositoryId:e.codebaseRepositoryId,repositoryGithubId:e.repositoryGithubId??null,worktreeId:e.worktreeId??null,branch:a,pullRequestNumber:e.pullRequestNumber??null,allWorkflows:e.allWorkflows,mode:e.mode,retryLimit:e.retryLimit??null,failureStrategy:e.failureStrategy,status:"ACTIVE",enabled:!0,lastError:null,activatedAt:new Date}}),await r.gitHubAutoRetryTarget.deleteMany({where:{ruleId:o}}),e.targets.length&&await r.gitHubAutoRetryTarget.createMany({data:e.targets.map(e=>({id:(0,t.randomUUID)(),ruleId:o,workflowId:e.workflowId?.trim()||null,workflowRunId:e.workflowRunId?.trim()||null,jobName:e.jobName?.trim()||null}))}),await r.gitHubAutoRetryExecution.deleteMany({where:{ruleId:o}}),r.gitHubAutoRetryRule.findUniqueOrThrow({where:{id:o},include:this.include()})));return queueMicrotask(()=>void this.reconcile().catch(()=>void 0)),z(l)}async setEnabled(e,t){let i=await (0,r.getPrismaClient)(),a=await i.$transaction(async r=>(t&&await r.gitHubAutoRetryExecution.updateMany({where:{ruleId:e,pendingFromAttempt:{not:null}},data:{pendingFromAttempt:null,observedAttempt:0,status:"WATCHING",lastError:null,finishedAt:null}}),r.gitHubAutoRetryRule.update({where:{id:e},data:{enabled:t,status:t?"ACTIVE":"PAUSED",lastError:null,...t?{activatedAt:new Date}:{}},include:this.include()})));return t&&queueMicrotask(()=>void this.reconcile().catch(()=>void 0)),z(a)}async delete(e){return(await (await (0,r.getPrismaClient)()).gitHubAutoRetryRule.deleteMany({where:{id:e}})).count>0}matches(e,t,r=!1){if("WORKFLOW_RUN"!==e.scope){let i=q.has(t.status);if(!r&&!i&&Date.parse(t.createdAt)<e.activatedAt.getTime())return!1}return"WORKTREE_BRANCH"===e.scope?t.headBranch===e.branch:"PULL_REQUEST"!==e.scope||t.pullRequests.some(t=>t.number===e.pullRequestNumber)}async execution(e,i,a){return(await (0,r.getPrismaClient)()).gitHubAutoRetryExecution.upsert({where:{ruleId_workflowRunId_targetKey:{ruleId:e,workflowRunId:i.id,targetKey:a}},create:{id:(0,t.randomUUID)(),ruleId:e,workflowRunId:i.id,workflowId:i.workflowId,targetKey:a},update:{}})}targetKeys(e,t){if(e.allWorkflows)return["workflow"];let r=e.targets.filter(e=>e.workflowRunId===t.id||e.workflowId===t.workflowId);return r.some(e=>!e.jobName)||"FAILURE"===e.mode&&"ALL_JOBS"===e.failureStrategy?["workflow"]:r.flatMap(e=>e.jobName?[`job:${e.jobName}`]:[])}async finishExecution(e,t,i){await (await (0,r.getPrismaClient)()).gitHubAutoRetryExecution.update({where:{id:e},data:{status:i,observedAttempt:t.runAttempt,lastStatus:t.status,pendingFromAttempt:null,finishedAt:new Date,lastError:null}})}async trigger(e,t,i,a,n){let s=await (0,r.getPrismaClient)();await s.gitHubAutoRetryExecution.update({where:{id:t.id},data:{status:"RETRYING",pendingFromAttempt:i.runAttempt,observedAttempt:i.runAttempt,lastStatus:i.status,lastError:null}});try{await this.github.autoRetryRerun(e.codebaseRepositoryId,i.id,a,n,{actor:"auto-retry",ipAddress:null,autoRetryRuleId:e.id,autoRetryExecutionId:t.id}),await s.gitHubAutoRetryExecution.update({where:{id:t.id},data:{automaticRetries:{increment:1},lastError:null}})}catch(i){let r=i instanceof Error?i.message:String(i);await s.gitHubAutoRetryExecution.update({where:{id:t.id},data:{lastError:r}}),await s.gitHubAutoRetryRule.update({where:{id:e.id},data:{lastError:r}})}}async reconcileExecution(e,t,i,a){var n;let s,o=await this.execution(e.id,t,i);if(null!=o.pendingFromAttempt)if(t.runAttempt>o.pendingFromAttempt)await (await (0,r.getPrismaClient)()).gitHubAutoRetryExecution.update({where:{id:o.id},data:{pendingFromAttempt:null,status:"WATCHING",lastError:null}});else{if(Date.now()-o.updatedAt.getTime()<12e4)return!1;let t=await (0,r.getPrismaClient)(),i="GitHub did not report a new attempt after the rerun request; automatic retries are paused to prevent a duplicate rerun";return await t.$transaction(async t=>{await t.gitHubAutoRetryExecution.update({where:{id:o.id},data:{status:"ERROR",lastError:i}}),await t.gitHubAutoRetryRule.update({where:{id:e.id},data:{enabled:!1,status:"PAUSED",lastError:i}})}),!1}if(o.observedAttempt===t.runAttempt&&null==o.pendingFromAttempt)return!1;let l=a?.status??t.status,u=(s=null!=(n={mode:e.mode,retryLimit:e.retryLimit,automaticRetries:o.automaticRetries,state:l}).retryLimit&&n.automaticRetries>=n.retryLimit,"COUNT"===n.mode?"SUCCESS"!==n.state?"STOP":s?"COMPLETE":"RETRY":"SUCCESS"===n.state?"COMPLETE":M.has(n.state)?s?"EXHAUSTED":"RETRY":"STOP");return"COMPLETE"===u?(await this.finishExecution(o.id,t,"COMPLETED"),!1):"EXHAUSTED"===u?(await this.finishExecution(o.id,t,"EXHAUSTED"),!1):"STOP"===u?(await this.finishExecution(o.id,t,"STOPPED"),!1):("COUNT"===e.mode?await this.trigger(e,o,t,a?"JOB":"ALL_JOBS",a?.id??null):await this.trigger(e,o,t,a?"ALL_JOBS"===e.failureStrategy?"ALL_JOBS":"JOB":"ALL_JOBS"===e.failureStrategy?"ALL_JOBS":"FAILED_JOBS",a?.id??null),!0)}async reconcile(){if(this.reconciling)return 0;this.reconciling=!0;let e=0;try{let t=await (0,r.getPrismaClient)(),i=await t.gitHubAutoRetryRule.findMany({where:{enabled:!0,status:"ACTIVE"},include:{targets:!0},orderBy:{createdAt:"asc"}});e=i.length;let a=new Map,n=i.length?await t.gitHubAutoRetryExecution.findMany({where:{ruleId:{in:i.map(e=>e.id)},status:{notIn:j}},select:{ruleId:!0,workflowRunId:!0}}):[],s=new Map;for(let e of n){let t=s.get(e.ruleId)??new Set;t.add(e.workflowRunId),s.set(e.ruleId,t)}let o=new Map;for(let e of i){let r=a.get(e.codebaseRepositoryId);if(!r)try{r=await this.github.autoRetryRuns(e.codebaseRepositoryId),a.set(e.codebaseRepositoryId,r)}catch(r){await t.gitHubAutoRetryRule.update({where:{id:e.id},data:{lastError:r instanceof Error?r.message:String(r)}});continue}let i=new Set(e.targets.map(e=>e.workflowRunId).filter(e=>!!e)),n=s.get(e.id)??new Set;for(let a of new Set([...i,...n]))if(!r.some(e=>e.id===a))try{r.push(await this.github.autoRetryRun(e.codebaseRepositoryId,a,!1))}catch(r){await t.gitHubAutoRetryRule.update({where:{id:e.id},data:{lastError:r instanceof Error?r.message:String(r)}})}for(let t of r){if("WORKFLOW_RUN"===e.scope&&!i.has(t.id)||!this.matches(e,t,n.has(t.id))||!e.allWorkflows&&!e.targets.some(e=>e.workflowRunId===t.id||e.workflowId===t.workflowId))continue;let r=o.get(t.id);(!r||$[e.scope]>$[r.rule.scope])&&o.set(t.id,{rule:e,run:t})}}for(let{rule:e,run:r}of o.values()){let i=this.targetKeys(e,r);if(q.has(r.status)){await Promise.all(i.map(t=>this.execution(e.id,r,t)));continue}let a=r,n=e.allWorkflows?[{jobName:null}]:e.targets.filter(e=>e.workflowRunId===a.id||e.workflowId===a.workflowId);if(n.some(e=>!e.jobName)){await this.reconcileExecution(e,a,"workflow",null);continue}let s=await Promise.all(i.map(t=>this.execution(e.id,a,t)));if(!s.some(e=>e.observedAttempt!==a.runAttempt||null!=e.pendingFromAttempt&&a.runAttempt>e.pendingFromAttempt)){for(let t=0;t<s.length;t+=1)s[t]?.pendingFromAttempt!=null&&await this.reconcileExecution(e,a,i[t],null);continue}try{a=await this.github.autoRetryRun(e.codebaseRepositoryId,a.id)}catch(r){await t.gitHubAutoRetryRule.update({where:{id:e.id},data:{lastError:r instanceof Error?r.message:String(r)}});continue}if("FAILURE"===e.mode&&"ALL_JOBS"===e.failureStrategy){let t=a.jobs.filter(e=>n.some(t=>t.jobName===e.name)),r=t.find(e=>M.has(e.status))??t.find(e=>"SUCCESS"!==e.status)??t[0];r?await this.reconcileExecution(e,a,"workflow",r):s[0]&&await this.finishExecution(s[0].id,a,"STOPPED");continue}let o=new Map(i.map((e,t)=>[e,s[t]]));for(let t of n){let r=a.jobs.find(e=>e.name===t.jobName);if(!r){let e=o.get(`job:${t.jobName}`);e&&await this.finishExecution(e.id,a,"STOPPED");continue}if(await this.reconcileExecution(e,a,`job:${r.name}`,r))break}}for(let e of i.filter(e=>"WORKFLOW_RUN"===e.scope)){let r=await t.gitHubAutoRetryExecution.findMany({where:{ruleId:e.id},select:{status:!0}});r.length>0&&r.every(e=>j.includes(e.status))&&await t.gitHubAutoRetryRule.update({where:{id:e.id},data:{enabled:!1,status:r.some(e=>"EXHAUSTED"===e.status)?"EXHAUSTED":"COMPLETED"}})}}finally{this.reconciling=!1}return e}}e.s(["GitHubAutoRetryService",0,H],685155);var V=e.i(963910),K=e.i(940045),W=e.i(919412),J=e.i(407188),Y=e.i(995702),Q=e.i(151112),Z=e.i(312851);let X="_adeRateLimit";function ee(e){let t=(0,Q.parse)(e),r=t.definitions.filter(e=>e.kind===Y.Kind.OPERATION_DEFINITION);if(1!==r.length||!r[0])throw Error("GitHub GraphQL requests must contain one operation");let i=r[0],a=i.name?.value??("mutation"===i.operation?"AnonymousMutation":"AnonymousQuery"),n=(0,Z.print)(t);if("query"!==i.operation)return{kind:"mutation",operation:a,normalizedQuery:n,liveQuery:n};let s={...t,definitions:t.definitions.map(e=>e===i?{...i,selectionSet:{...i.selectionSet,selections:[...i.selectionSet.selections,{kind:Y.Kind.FIELD,alias:{kind:Y.Kind.NAME,value:X},name:{kind:Y.Kind.NAME,value:"rateLimit"},arguments:[],directives:[],selectionSet:{kind:Y.Kind.SELECTION_SET,selections:[{kind:Y.Kind.FIELD,name:{kind:Y.Kind.NAME,value:"cost"},arguments:[],directives:[]}]}}]}}:e)};return{kind:"query",operation:a,normalizedQuery:n,liveQuery:(0,Z.print)(s)}}function et(e){if(!e||"object"!=typeof e||Array.isArray(e))return{data:e,pointCost:null};let t=e[X],r=t&&"object"==typeof t&&!Array.isArray(t)&&Number.isSafeInteger(t.cost)?t.cost:null;if(!(X in e))return{data:e,pointCost:r};let i={...e};return delete i[X],{data:i,pointCost:r}}let er="default",ei="default",ea=String.raw`\b([A-Z][A-Z0-9_]*-\d+)\b`,en=["workflow_run","workflow_job","check_run","check_suite","status"];function es(e){return"read"===e||"write"===e}function eo(e){let t=[];for(let r of(e.webhookConfigured||t.push("configure the signed webhook URL"),es(e.actionsPermission)||t.push("grant Actions read permission"),es(e.checksPermission)||t.push("grant Checks read permission"),es(e.commitStatusesPermission)||t.push("grant Commit statuses read permission"),en))e.webhookEvents.includes(r)||t.push(`subscribe to the ${r} event`);return t}function el(e){return"auto-retry"===e.actor?"AUTO_RETRY":"workflow"===e.actor?"WORKFLOW_AUTOMATION":"ACTIONS_PAGE"}class eu extends Error{statusCode;rateLimit;constructor(e,t,r){super(e),this.statusCode=t,this.rateLimit=r,this.name="GitHubRequestError"}}let ec=`
|
|
67
67
|
__typename
|
|
68
68
|
... on CheckRun {
|
|
69
69
|
id
|