@knoflows/engine 0.1.0-alpha.12 → 0.1.0-alpha.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/dist/engine.js +81 -13
  2. package/dist/migrations/20260919073531_tense_grey_gargoyle/migration.sql +1 -0
  3. package/dist/migrations/20260919073531_tense_grey_gargoyle/snapshot.json +1348 -0
  4. package/dist/migrations/20260919081637_fearless_warlock/migration.sql +1 -0
  5. package/dist/migrations/20260919081637_fearless_warlock/snapshot.json +1358 -0
  6. package/package.json +3 -3
  7. package/static/apple-touch-icon.png +0 -0
  8. package/static/assets/i18n/en.json +50 -9
  9. package/static/assets/i18n/es.json +50 -9
  10. package/static/chunk-1Oqdt_Gp.js +1 -0
  11. package/static/{chunk-C3Ej8Ue9.js → chunk-1eeePIP1.js} +1 -1
  12. package/static/chunk-37yFTUcY.js +1 -0
  13. package/static/chunk-7MZQgksi.js +1 -0
  14. package/static/chunk-7VyHTRp_.js +1 -0
  15. package/static/chunk-B0V1VBvY.js +1 -0
  16. package/static/chunk-BH5zvE8A.js +1 -0
  17. package/static/chunk-BZxs3wP7.js +1 -0
  18. package/static/chunk-B_L2A3hm.js +1 -0
  19. package/static/chunk-BbIC5sO2.js +1 -0
  20. package/static/chunk-BeWWb9rm.js +1 -0
  21. package/static/chunk-BnD2l9n3.js +1 -0
  22. package/static/chunk-Bp8u1CCw.js +1 -0
  23. package/static/chunk-BpOumnMU.js +1 -0
  24. package/static/chunk-BuPc66MS.js +1 -0
  25. package/static/{chunk-CK-2DsDH.js → chunk-C4Ee3umI.js} +1 -1
  26. package/static/chunk-C5n_oTWP.js +1 -0
  27. package/static/chunk-CF4gc4Im.js +1 -0
  28. package/static/chunk-CM8oLO7n.js +1 -0
  29. package/static/chunk-CXGgR5M1.js +1 -0
  30. package/static/chunk-CiJRU6lo.js +1 -0
  31. package/static/chunk-Cn95hfnf.js +1 -0
  32. package/static/chunk-Cq09TrKP.js +1 -0
  33. package/static/chunk-Cx2n09Ng.js +1 -0
  34. package/static/chunk-DFoFQkTa.js +1 -0
  35. package/static/chunk-DMAf3Qir.js +66 -0
  36. package/static/chunk-DYARU-G0.js +1 -0
  37. package/static/chunk-DZhQ2iEt.js +1 -0
  38. package/static/chunk-D_DUAV49.js +1 -0
  39. package/static/chunk-DgEO14wO.js +1 -0
  40. package/static/{chunk-hEYSTlD1.js → chunk-DphMF2VB.js} +1 -1
  41. package/static/chunk-DxZsQqxS.js +1 -0
  42. package/static/chunk-GQe0l3Uh.js +1 -0
  43. package/static/chunk-J9qS04nF.js +1 -0
  44. package/static/chunk-dOUa0Vhs.js +1 -0
  45. package/static/chunk-nx1xncBD.js +1 -0
  46. package/static/chunk-q9oVn_qj.js +5 -0
  47. package/static/{chunk-BquoV7tV.js → chunk-vYeIWxg4.js} +1 -1
  48. package/static/chunk-yxqIQom4.js +1 -0
  49. package/static/favicon-16x16.png +0 -0
  50. package/static/favicon-32x32.png +0 -0
  51. package/static/favicon.ico +0 -0
  52. package/static/favicon.svg +12 -0
  53. package/static/icon-192.png +0 -0
  54. package/static/icon-512.png +0 -0
  55. package/static/index.html +30 -5
  56. package/static/main-2ZW45HAE.js +248 -0
  57. package/static/media/inter-latin-400-normal-55WT6UWF.woff2 +0 -0
  58. package/static/media/inter-latin-400-normal-FR5HOXA4.woff +0 -0
  59. package/static/media/inter-latin-500-normal-W62DVTXI.woff2 +0 -0
  60. package/static/media/inter-latin-500-normal-ZNGIZ2YB.woff +0 -0
  61. package/static/media/inter-latin-600-normal-R6Y2SZCR.woff2 +0 -0
  62. package/static/media/inter-latin-600-normal-ZYHV6QZT.woff +0 -0
  63. package/static/media/jetbrains-mono-latin-500-normal-ETEQEOVZ.woff +0 -0
  64. package/static/media/jetbrains-mono-latin-500-normal-V4XIP5OW.woff2 +0 -0
  65. package/static/media/space-grotesk-latin-500-normal-GESQWJQV.woff2 +0 -0
  66. package/static/media/space-grotesk-latin-500-normal-HV4TE4RA.woff +0 -0
  67. package/static/media/space-grotesk-latin-700-normal-6Z7GHSI6.woff +0 -0
  68. package/static/media/space-grotesk-latin-700-normal-I3MXRIUZ.woff2 +0 -0
  69. package/static/nz-theme-dark.css +1 -0
  70. package/static/nz-theme.css +1 -0
  71. package/static/styles-JGCTKGGH.css +1 -0
  72. package/static/chunk--F2Y9kLC.js +0 -1
  73. package/static/chunk-A3t8CipM.js +0 -1
  74. package/static/chunk-BAgwFLbm.js +0 -1
  75. package/static/chunk-BLSuZA6j.js +0 -1
  76. package/static/chunk-Bc9kVhav.js +0 -1
  77. package/static/chunk-BdrifDCS.js +0 -66
  78. package/static/chunk-BkJuaRUH.js +0 -1
  79. package/static/chunk-BmP-Xct3.js +0 -1
  80. package/static/chunk-BqB1I-vg.js +0 -1
  81. package/static/chunk-C5T1qa5G.js +0 -1
  82. package/static/chunk-CKFZoQzp.js +0 -1
  83. package/static/chunk-CLNhyiRm.js +0 -1
  84. package/static/chunk-CN5_Adst.js +0 -1
  85. package/static/chunk-COSsVdG3.js +0 -1
  86. package/static/chunk-Cj-KtAk-.js +0 -1
  87. package/static/chunk-CrD5w72_.js +0 -1
  88. package/static/chunk-CxBYhrEj.js +0 -1
  89. package/static/chunk-D5Bqg3D5.js +0 -7
  90. package/static/chunk-DAfnL0eP.js +0 -1
  91. package/static/chunk-Dc3mv2RT.js +0 -1
  92. package/static/chunk-Dc7Nho4-.js +0 -1
  93. package/static/chunk-Df_jRm7U.js +0 -1
  94. package/static/chunk-Dl9xoaKd.js +0 -1
  95. package/static/chunk-DqECIHE5.js +0 -1
  96. package/static/chunk-Dtfc5XNc.js +0 -1
  97. package/static/chunk-DxtF2GQ1.js +0 -1
  98. package/static/chunk-KhdCYqqN.js +0 -1
  99. package/static/chunk-TkjFi8lV.js +0 -1
  100. package/static/chunk-UArWmYDU.js +0 -1
  101. package/static/chunk-WGWZEfc0.js +0 -1
  102. package/static/chunk-jg6TAN9F.js +0 -1
  103. package/static/chunk-mb666CWY.js +0 -1
  104. package/static/chunk-nXCKNQUo.js +0 -1
  105. package/static/chunk-ndsN8K7Q.js +0 -5
  106. package/static/chunk-tnTBlRRN.js +0 -1
  107. package/static/main-RRKPLQCF.js +0 -249
  108. package/static/styles-6MW3GE4V.css +0 -1
package/dist/engine.js CHANGED
@@ -1,26 +1,94 @@
1
1
  #!/usr/bin/env node
2
- var l=(r,e)=>()=>(r&&(e=r(r=0)),e);import{Controller as Gl,Get as zl}from"@nestjs/common";var fs,go,Zt,ms=l(()=>{"use strict";fs=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},go=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},Zt=class{getHealth(){return{ok:!0,service:"kno-engine",timestamp:new Date().toISOString()}}};fs([zl(),go("design:type",Function),go("design:paramtypes",[]),go("design:returntype",Object)],Zt.prototype,"getHealth",null);Zt=fs([Gl("health")],Zt)});import{Module as Xl}from"@nestjs/common";var Ql,Er,hs=l(()=>{"use strict";Ql=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Er=class{};Er=Ql([Xl({})],Er)});import{Module as Zl}from"@nestjs/common";var Yl,Pr,ys=l(()=>{"use strict";Yl=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Pr=class{};Pr=Yl([Zl({})],Pr)});var er,wo=l(()=>{"use strict";er=Symbol("NOTIFICATION_PROVIDER")});var Rr,gs=l(()=>{"use strict";Rr=class{async send(e){console.log("[notification]",JSON.stringify(e))}}});import{existsSync as ws}from"node:fs";import{dirname as ed,join as tr}from"node:path";import{fileURLToPath as td}from"node:url";function rr(){let r=ed(td(import.meta.url)),e=tr(r,"../data"),t=tr(r,"../../data");return ws(tr(e,"kno.db"))?e:ws(tr(t,"kno.db"))?t:e}function bs(){return tr(rr(),"kno.db")}var kr=l(()=>{"use strict"});import{createCipheriv as rd,createDecipheriv as nd,randomBytes as Ss}from"node:crypto";import{mkdir as xs,readFile as vs,writeFile as Is}from"node:fs/promises";import{join as So}from"node:path";function kt(r){return`kno.${r}.apiKey`}function ad(r){return So(r,"secrets")}function _s(r){return new xo(ad(r.dataDir),r.keyring)}function cd(r){try{return r(Ar,"__kno_probe__").getPassword(),!0}catch(e){return vo(e)}}function vo(r){let e=r instanceof Error?r.message:String(r);return/noentry|no matching entry|not found|no such/i.test(e)}var Ar,js,od,bo,id,sd,xo,fe,Oe=l(()=>{"use strict";Ar="kno-flows";js="aes-256-gcm",od=12,bo=32,id="master.key",sd="store.json",xo=class{secretsDir;keyring;keyringResolved=!1;masterKey=null;constructor(e,t){this.secretsDir=e,this.keyring=t,t!==void 0&&(this.keyringResolved=!0)}async get(e){let t=await this.resolveKeyring();if(t)try{let n=t(Ar,e).getPassword();if(n!=null)return n}catch(n){vo(n)||this.disableKeyring()}return this.fileGet(e)}async set(e,t){let n=await this.resolveKeyring();if(n)try{n(Ar,e).setPassword(t),await this.fileDelete(e);return}catch{this.disableKeyring()}await this.fileSet(e,t)}async delete(e){let t=await this.resolveKeyring();if(t)try{t(Ar,e).deletePassword()}catch(n){vo(n)||this.disableKeyring()}await this.fileDelete(e)}disableKeyring(){this.keyring=null,this.keyringResolved=!0}async resolveKeyring(){if(this.keyringResolved)return this.keyring??null;this.keyringResolved=!0;try{let{Entry:e}=await import("@napi-rs/keyring"),t=(n,o)=>new e(n,o);return cd(t)?(this.keyring=t,t):(this.keyring=null,null)}catch{return this.keyring=null,null}}async fileGet(e){let n=(await this.readStore())[e];return n?this.decrypt(n):null}async fileSet(e,t){let n=await this.readStore();n[e]=await this.encrypt(t),await this.writeStore(n)}async fileDelete(e){let t=await this.readStore();e in t&&(delete t[e],await this.writeStore(t))}async readStore(){try{let e=await vs(this.storePath(),"utf8"),t=JSON.parse(e);if(t==null||typeof t!="object"||Array.isArray(t))throw new Error(`Corrupt secret store at ${this.storePath()}`);return t}catch(e){if(e.code==="ENOENT")return{};throw e}}async writeStore(e){await xs(this.secretsDir,{recursive:!0}),await Is(this.storePath(),JSON.stringify(e,null,2),{encoding:"utf8",mode:384})}async encrypt(e){let t=await this.loadOrCreateMasterKey(),n=Ss(od),o=rd(js,t,n),i=Buffer.concat([o.update(e,"utf8"),o.final()]);return{iv:n.toString("base64"),tag:o.getAuthTag().toString("base64"),ciphertext:i.toString("base64")}}async decrypt(e){let t=await this.loadOrCreateMasterKey(),n=nd(js,t,Buffer.from(e.iv,"base64"));return n.setAuthTag(Buffer.from(e.tag,"base64")),Buffer.concat([n.update(Buffer.from(e.ciphertext,"base64")),n.final()]).toString("utf8")}async loadOrCreateMasterKey(){if(this.masterKey)return this.masterKey;await xs(this.secretsDir,{recursive:!0});let e=this.masterKeyPath();try{let n=(await vs(e,"utf8")).trim(),o=Buffer.from(n,"hex");if(o.length!==bo)throw new Error(`Secret store master key at ${e} is not ${bo} bytes`);return this.masterKey=o,o}catch(n){if(n.code!=="ENOENT")throw n}let t=Ss(bo);return await Is(e,t.toString("hex"),{encoding:"utf8",mode:384}),this.masterKey=t,t}storePath(){return So(this.secretsDir,sd)}masterKeyPath(){return So(this.secretsDir,id)}};fe=Symbol("SECRET_STORE")});import{Module as ld}from"@nestjs/common";import{mkdirSync as dd}from"node:fs";var ud,Es,At,Io=l(()=>{"use strict";kr();Oe();ud=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Es=rr();dd(Es,{recursive:!0});At=class{};At=ud([ld({providers:[{provide:fe,useFactory:()=>_s({dataDir:Es})}],exports:[fe]})],At)});import{index as pd,sqliteTable as fd,text as ve}from"drizzle-orm/sqlite-core";var Ge,jo=l(()=>{"use strict";Ge=fd("workflow_definitions",{id:ve("id").primaryKey(),name:ve("name").notNull(),description:ve("description"),appliesTo:ve("applies_to",{mode:"json"}).$type().notNull(),subjectHandling:ve("subject_handling",{enum:["per-subject","collection"]}).notNull(),inputSchema:ve("input_schema",{mode:"json"}).$type().notNull(),steps:ve("steps",{mode:"json"}).$type().notNull(),notificationPolicy:ve("notification_policy",{mode:"json"}).$type().notNull(),createdAt:ve("created_at").notNull(),updatedAt:ve("updated_at").notNull()},r=>[pd("workflow_definitions_subject_handling_idx").on(r.subjectHandling)])});import{index as Ps,integer as md,sqliteTable as hd,text as ze}from"drizzle-orm/sqlite-core";var Ie,_o=l(()=>{"use strict";Ie=hd("subject_views",{id:ze("id").primaryKey(),name:ze("name").notNull(),subjectType:ze("subject_type").$type().notNull(),workflowId:ze("workflow_id").notNull(),query:ze("query",{mode:"json"}).$type().notNull(),description:ze("description"),queryTemplate:ze("query_template",{mode:"json"}).$type(),providerInstanceId:ze("provider_instance_id").notNull().default(""),order:md("order").notNull().default(0)},r=>[Ps("subject_views_subject_type_idx").on(r.subjectType),Ps("subject_views_subject_type_order_idx").on(r.subjectType,r.order)])});import{index as Rs,integer as yd,sqliteTable as gd,text as je}from"drizzle-orm/sqlite-core";var Qe,Cr=l(()=>{"use strict";Qe=gd("job_batches",{id:je("id").primaryKey(),workflowId:je("workflow_id").notNull(),selection:je("selection",{mode:"json"}).$type().notNull(),resolvedSubjects:je("resolved_subjects",{mode:"json"}).$type().notNull(),status:je("status",{enum:["running","completed","completed_with_issues","failed","cancelled"]}).notNull(),triggeredBy:je("triggered_by",{enum:["schedule","view_bulk","multiselect"]}).notNull(),scheduleId:je("schedule_id"),notificationOverride:je("notification_override",{mode:"json"}).$type(),notificationSent:yd("notification_sent",{mode:"boolean"}).notNull(),createdAt:je("created_at").notNull(),completedAt:je("completed_at")},r=>[Rs("job_batches_workflow_id_idx").on(r.workflowId),Rs("job_batches_schedule_id_idx").on(r.scheduleId)])});import{index as Tr,integer as wd,sqliteTable as bd,text as D}from"drizzle-orm/sqlite-core";var L,nr=l(()=>{"use strict";Cr();L=bd("jobs",{id:D("id").primaryKey(),workflowId:D("workflow_id").notNull(),status:D("status").$type().notNull(),selection:D("selection",{mode:"json"}).$type(),batchId:D("batch_id").references(()=>Qe.id),parentJobId:D("parent_job_id"),parentStepExecutionId:D("parent_step_execution_id"),fanOutIndex:wd("fan_out_index"),retryOf:D("retry_of"),workflowSnapshot:D("workflow_snapshot",{mode:"json"}).$type(),context:D("context",{mode:"json"}).$type().notNull(),worktreePath:D("worktree_path"),branch:D("branch"),worktreeDeletedAt:D("worktree_deleted_at"),currentStepId:D("current_step_id"),currentStepExecutionId:D("current_step_execution_id"),createdAt:D("created_at").notNull(),updatedAt:D("updated_at").notNull(),completedAt:D("completed_at")},r=>[Tr("jobs_workflow_id_idx").on(r.workflowId),Tr("jobs_status_idx").on(r.status),Tr("jobs_batch_id_idx").on(r.batchId),Tr("jobs_parent_job_id_idx").on(r.parentJobId)])});import{index as ks,sqliteTable as Sd,text as or}from"drizzle-orm/sqlite-core";var _e,Eo=l(()=>{"use strict";nr();_e=Sd("job_subjects",{id:or("id").primaryKey(),jobId:or("job_id").notNull().references(()=>L.id),subjectType:or("subject_type").$type().notNull(),subjectId:or("subject_id").notNull(),snapshot:or("snapshot",{mode:"json"}).$type().notNull()},r=>[ks("job_subjects_job_id_idx").on(r.jobId),ks("job_subjects_subject_lookup_idx").on(r.subjectType,r.subjectId)])});import{index as As,integer as xd,sqliteTable as vd,text as me}from"drizzle-orm/sqlite-core";var pt,Po=l(()=>{"use strict";nr();pt=vd("job_step_executions",{id:me("id").primaryKey(),jobId:me("job_id").notNull().references(()=>L.id),stepDefinitionId:me("step_definition_id").notNull(),type:me("type").$type().notNull(),status:me("status").$type().notNull(),startedAt:me("started_at"),completedAt:me("completed_at"),output:me("output",{mode:"json"}).$type(),error:me("error"),childJobIds:me("child_job_ids",{mode:"json"}).$type(),parentStepExecutionId:me("parent_step_execution_id").references(()=>pt.id),iterationIndex:xd("iteration_index")},r=>[As("job_step_executions_job_id_idx").on(r.jobId),As("job_step_executions_parent_idx").on(r.parentStepExecutionId)])});import{index as Id,integer as jd,sqliteTable as _d,text as Xe}from"drizzle-orm/sqlite-core";var Ye,Ro=l(()=>{"use strict";Ye=_d("schedules",{id:Xe("id").primaryKey(),viewId:Xe("view_id").notNull(),triggerType:Xe("trigger_type",{enum:["cron"]}).notNull(),cadence:Xe("cadence").notNull(),notificationOverride:Xe("notification_override",{mode:"json"}).$type(),missedFirePolicy:Xe("missed_fire_policy",{enum:["skip","catch_up"]}).notNull(),enabled:jd("enabled",{mode:"boolean"}).notNull(),lastFiredAt:Xe("last_fired_at"),createdAt:Xe("created_at").notNull()},r=>[Id("schedules_enabled_idx").on(r.enabled)])});import{integer as Ed,sqliteTable as Pd,text as ir}from"drizzle-orm/sqlite-core";var Ee,ko=l(()=>{"use strict";Ee=Pd("workflow_shortcuts",{id:ir("id").primaryKey(),name:ir("name").notNull(),workflowId:ir("workflow_id").notNull(),inputValues:ir("input_values",{mode:"json"}).$type().notNull(),lastJobId:ir("last_job_id"),order:Ed("order").notNull().default(0)})});import{sqliteTable as Rd,text as sr}from"drizzle-orm/sqlite-core";var Ze,Ao=l(()=>{"use strict";Ze=Rd("context_files",{id:sr("id").primaryKey(),name:sr("name").notNull(),description:sr("description"),tier:sr("tier").$type().notNull(),path:sr("path").notNull()})});import{sqliteTable as kd,text as Or}from"drizzle-orm/sqlite-core";var et,Co=l(()=>{"use strict";et=kd("local_repositories",{id:Or("id").primaryKey(),name:Or("name").notNull(),localPath:Or("local_path").notNull(),worktreeBasePath:Or("worktree_base_path")})});import{sqliteTable as Ad,text as Cs}from"drizzle-orm/sqlite-core";var ar,Ct,To=l(()=>{"use strict";ar="default",Ct=Ad("settings",{id:Cs("id").primaryKey(),data:Cs("data",{mode:"json"}).$type().notNull()})});import{defineRelations as Cd}from"drizzle-orm";var Td,Ts,Os=l(()=>{"use strict";jo();_o();nr();Eo();Po();Cr();Ro();ko();Ao();Co();To();Td={workflowDefinitions:Ge,subjectViews:Ie,jobs:L,jobSubjects:_e,jobStepExecutions:pt,jobBatches:Qe,schedules:Ye,workflowShortcuts:Ee,contextFiles:Ze,localRepositories:et,settings:Ct},Ts=Cd(Td,r=>({workflowDefinitions:{},subjectViews:{},schedules:{},workflowShortcuts:{},contextFiles:{},localRepositories:{},settings:{},jobs:{subjects:r.many.jobSubjects({from:r.jobs.id,to:r.jobSubjects.jobId}),stepExecutions:r.many.jobStepExecutions({from:r.jobs.id,to:r.jobStepExecutions.jobId}),batch:r.one.jobBatches({from:r.jobs.batchId,to:r.jobBatches.id})},jobSubjects:{job:r.one.jobs({from:r.jobSubjects.jobId,to:r.jobs.id})},jobStepExecutions:{job:r.one.jobs({from:r.jobStepExecutions.jobId,to:r.jobs.id}),parent:r.one.jobStepExecutions({from:r.jobStepExecutions.parentStepExecutionId,to:r.jobStepExecutions.id,alias:"job_step_executions_parent"}),children:r.many.jobStepExecutions({from:r.jobStepExecutions.id,to:r.jobStepExecutions.parentStepExecutionId,alias:"job_step_executions_children"})},jobBatches:{jobs:r.many.jobs({from:r.jobBatches.id,to:r.jobs.batchId})}}))});import{drizzle as Od}from"drizzle-orm/node-sqlite";import{DatabaseSync as ab}from"node:sqlite";function $s(r){return r.exec("PRAGMA foreign_keys = ON;"),Od({client:r,relations:Ts})}var qs=l(()=>{"use strict";Os()});import{existsSync as Bs,readdirSync as $d}from"node:fs";import{dirname as qd,join as Oo}from"node:path";import{fileURLToPath as Bd}from"node:url";function Ds(){let r=qd(Bd(import.meta.url)),e=[Oo(r,"persistence/migrations"),Oo(r,"migrations")];for(let t of e)if(Dd(t))return t;throw new Error(`Engine SQL migrations not found. Looked in: ${e.join(", ")}`)}function Dd(r){return Bs(r)?$d(r,{withFileTypes:!0}).some(e=>e.isDirectory()&&Bs(Oo(r,e.name,"migration.sql"))):!1}var Fs=l(()=>{"use strict"});import{migrate as Ns}from"drizzle-orm/node-sqlite/migrator";import{readMigrationFiles as Fd}from"drizzle-orm/migrator";function qo(r,e,t={}){let n=t.log??(()=>{}),o=Ds(),i=Fd({migrationsFolder:o});if(i.length===0)throw new he(`No SQL migrations in ${o}`);let s=Jd(i),a=lr(r,ft),u=Nd.filter(S=>lr(r,S));if(!a&&u.length===0){Ns(e,{migrationsFolder:o}),$o(r,s);return}if(!a){Wd(r,s,n),Vd(r,i),$o(r,s);return}Hd(r,i);let c=Ls(r,s),p=Us(r);if(p.length===0&&u.length>0)throw new he("migrations table exists but is empty while application tables are present \u2014 treating this as an interrupted update");let m=new Set(p.map(S=>S.name).filter(S=>S!=null&&S!==""));if(i.filter(S=>!m.has(S.name)).length===0&&c.length>0)throw new he(`migrations journal is present but the schema is incomplete (${c.join("; ")}) \u2014 treating this as an interrupted update`);Ns(e,{migrationsFolder:o}),$o(r,s)}function Jd(r){let e=[],t=[],n=[];for(let o of r)for(let i of o.sql){let s=i.trim().replace(/;+\s*$/,"");if(!s)continue;let a=Ld(s);if(a){e.push(a);continue}let u=Ud(s);if(u){n.push(u);continue}let c=Md(s);c&&t.push(c)}return{tables:e,indexes:t,alterColumns:n}}function Ld(r){let e=r.match(/^CREATE TABLE\s+(`[^`]+`|"[^"]+"|\w+)\s*\(/i);if(!e)return null;let t=r.indexOf("("),n=r.lastIndexOf(")");if(t<0||n<t)return null;let o=[];for(let i of r.slice(t+1,n).split(`
3
- `)){let s=i.trim().replace(/,+\s*$/,"");if(!s||/^(CONSTRAINT|PRIMARY KEY|UNIQUE|FOREIGN KEY|CHECK)\b/i.test(s))continue;let a=s.match(/^(`[^`]+`|"[^"]+"|\w+)\s+(\w+)/);a&&o.push({name:ur(a[1]),type:a[2]})}return{name:ur(e[1]),createSql:`${r};`,columns:o}}function Ud(r){let e=r.match(/^ALTER TABLE\s+(`[^`]+`|"[^"]+"|\w+)\s+ADD(?:\s+COLUMN)?\s+(`[^`]+`|"[^"]+"|\w+)\s+(\w+)/i);return e?{table:ur(e[1]),name:ur(e[2]),type:e[3]}:null}function Md(r){let e=r.match(/^CREATE INDEX\s+(?:IF NOT EXISTS\s+)?(`[^`]+`|"[^"]+"|\w+)/i);if(!e)return null;let t=/^CREATE INDEX\s+IF NOT EXISTS\b/i.test(r)?r:r.replace(/^CREATE INDEX\b/i,"CREATE INDEX IF NOT EXISTS");return{name:ur(e[1]),sql:`${t};`}}function ur(r){return r.replace(/^["`]|["`]$/g,"")}function cr(r){return`\`${r.replace(/`/g,"")}\``}function Wd(r,e,t){t("Legacy push-mode database detected (application tables present, no migration journal). Reconciling schema in place.");let n=[],o=[],i=[];r.exec("BEGIN");try{for(let s of e.tables){if(!lr(r,s.name)){r.exec(s.createSql),n.push(s.name);continue}let a=new Set($r(r,s.name));for(let u of s.columns)a.has(u.name)||(r.exec(`ALTER TABLE ${cr(s.name)} ADD COLUMN ${cr(u.name)} ${u.type}`),a.add(u.name),o.push(`${s.name}.${u.name}`))}for(let s of e.alterColumns)lr(r,s.table)&&($r(r,s.table).includes(s.name)||(r.exec(`ALTER TABLE ${cr(s.table)} ADD COLUMN ${cr(s.name)} ${s.type}`),o.push(`${s.table}.${s.name}`)));for(let s of e.indexes)Js(r,s.name)||(r.exec(s.sql),i.push(s.name));r.exec("COMMIT")}catch(s){throw r.exec("ROLLBACK"),s}for(let s of n)t(`Reconciliation: created table '${s}'`);for(let s of o)t(`Reconciliation: added column ${s}`);for(let s of i)t(`Reconciliation: created index '${s}'`);n.length===0&&o.length===0&&i.length===0&&t("Reconciliation: schema already matched the current baseline; nothing to add."),t("Reconciliation complete. Recording baseline as applied; future startups use normal migrations.")}function lr(r,e){return r.prepare("SELECT 1 AS ok FROM sqlite_master WHERE type = 'table' AND name = ?").get(e)!=null}function Js(r,e){return r.prepare("SELECT 1 AS ok FROM sqlite_master WHERE type = 'index' AND name = ?").get(e)!=null}function $r(r,e){return r.prepare(`PRAGMA table_info(${cr(e)})`).all().map(n=>n.name)}function Ls(r,e){let t=[],n=new Map;for(let o of e.tables)n.set(o.name,new Set(o.columns.map(i=>i.name)));for(let o of e.alterColumns){let i=n.get(o.table)??new Set;i.add(o.name),n.set(o.table,i)}for(let[o,i]of n){if(!lr(r,o)){t.push(`missing table '${o}'`);continue}let s=new Set($r(r,o));for(let a of i)s.has(a)||t.push(`table '${o}' is missing column '${a}'`)}for(let o of e.indexes)Js(r,o.name)||t.push(`missing index '${o.name}'`);return t}function $o(r,e){let t=Ls(r,e);if(t.length>0)throw new he(`schema is incomplete after migrate (${t.join("; ")})`)}function Us(r){let e=new Set($r(r,ft));if(!e.has("hash"))throw new he(`migrations table '${ft}' is missing required columns`);if(!e.has("name"))throw new he(`migrations table '${ft}' is missing column 'name' \u2014 journal is from an interrupted upgrade`);return r.prepare(`SELECT name, hash FROM ${ft}`).all()}function Hd(r,e){let t=new Map(e.map(n=>[n.name,n]));for(let n of Us(r)){if(n.name==null||n.name==="")throw new he("migrations journal has a row with no name \u2014 treating this as an interrupted update");let o=t.get(n.name);if(!o)throw new he(`database has unknown migration '${n.name}' that is not in this Engine build`);if(n.hash!=null&&n.hash!==o.hash)throw new he(`migration '${n.name}' hash does not match this Engine build \u2014 treating this as a corrupt or interrupted update`)}}function Vd(r,e){r.exec(`
4
- CREATE TABLE IF NOT EXISTS ${ft} (
2
+ var l=(n,e)=>()=>(n&&(e=n(n=0)),e);import{Controller as Rd,Get as kd}from"@nestjs/common";var $s,Co,on,qs=l(()=>{"use strict";$s=function(n,e,t,r){var o=arguments.length,i=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Co=function(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)},on=class{getHealth(){return{ok:!0,service:"kno-engine",timestamp:new Date().toISOString()}}};$s([kd(),Co("design:type",Function),Co("design:paramtypes",[]),Co("design:returntype",Object)],on.prototype,"getHealth",null);on=$s([Rd("health")],on)});import{Module as Cd}from"@nestjs/common";var Ad,Dn,Ds=l(()=>{"use strict";Ad=function(n,e,t,r){var o=arguments.length,i=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Dn=class{};Dn=Ad([Cd({})],Dn)});import{Module as Od}from"@nestjs/common";var Td,Bn,Bs=l(()=>{"use strict";Td=function(n,e,t,r){var o=arguments.length,i=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Bn=class{};Bn=Td([Od({})],Bn)});var sn,To=l(()=>{"use strict";sn=Symbol("NOTIFICATION_PROVIDER")});var Fn,Fs=l(()=>{"use strict";Fn=class{async send(e){console.log("[notification]",JSON.stringify(e))}}});import{existsSync as Ns}from"node:fs";import{dirname as $d,join as an}from"node:path";import{fileURLToPath as qd}from"node:url";function cn(){let n=$d(qd(import.meta.url)),e=an(n,"../data"),t=an(n,"../../data");return Ns(an(e,"kno.db"))?e:Ns(an(t,"kno.db"))?t:e}function Js(){return an(cn(),"kno.db")}var Nn=l(()=>{"use strict"});import{createCipheriv as Dd,createDecipheriv as Bd,randomBytes as Ls}from"node:crypto";import{mkdir as Us,readFile as Ms,writeFile as Ws}from"node:fs/promises";import{join as $o}from"node:path";function Bt(n){return`kno.${n}.apiKey`}function Ld(n){return $o(n,"secrets")}function Gs(n){return new qo(Ld(n.dataDir),n.keyring)}function Ud(n){try{return n(Jn,"__kno_probe__").getPassword(),!0}catch(e){return Do(e)}}function Do(n){let e=n instanceof Error?n.message:String(n);return/noentry|no matching entry|not found|no such/i.test(e)}var Jn,Hs,Fd,Oo,Nd,Jd,qo,he,Fe=l(()=>{"use strict";Jn="kno-flows";Hs="aes-256-gcm",Fd=12,Oo=32,Nd="master.key",Jd="store.json",qo=class{secretsDir;keyring;keyringResolved=!1;masterKey=null;constructor(e,t){this.secretsDir=e,this.keyring=t,t!==void 0&&(this.keyringResolved=!0)}async get(e){let t=await this.resolveKeyring();if(t)try{let r=t(Jn,e).getPassword();if(r!=null)return r}catch(r){Do(r)||this.disableKeyring()}return this.fileGet(e)}async set(e,t){let r=await this.resolveKeyring();if(r)try{r(Jn,e).setPassword(t),await this.fileDelete(e);return}catch{this.disableKeyring()}await this.fileSet(e,t)}async delete(e){let t=await this.resolveKeyring();if(t)try{t(Jn,e).deletePassword()}catch(r){Do(r)||this.disableKeyring()}await this.fileDelete(e)}disableKeyring(){this.keyring=null,this.keyringResolved=!0}async resolveKeyring(){if(this.keyringResolved)return this.keyring??null;this.keyringResolved=!0;try{let{Entry:e}=await import("@napi-rs/keyring"),t=(r,o)=>new e(r,o);return Ud(t)?(this.keyring=t,t):(this.keyring=null,null)}catch{return this.keyring=null,null}}async fileGet(e){let r=(await this.readStore())[e];return r?this.decrypt(r):null}async fileSet(e,t){let r=await this.readStore();r[e]=await this.encrypt(t),await this.writeStore(r)}async fileDelete(e){let t=await this.readStore();e in t&&(delete t[e],await this.writeStore(t))}async readStore(){try{let e=await Ms(this.storePath(),"utf8"),t=JSON.parse(e);if(t==null||typeof t!="object"||Array.isArray(t))throw new Error(`Corrupt secret store at ${this.storePath()}`);return t}catch(e){if(e.code==="ENOENT")return{};throw e}}async writeStore(e){await Us(this.secretsDir,{recursive:!0}),await Ws(this.storePath(),JSON.stringify(e,null,2),{encoding:"utf8",mode:384})}async encrypt(e){let t=await this.loadOrCreateMasterKey(),r=Ls(Fd),o=Dd(Hs,t,r),i=Buffer.concat([o.update(e,"utf8"),o.final()]);return{iv:r.toString("base64"),tag:o.getAuthTag().toString("base64"),ciphertext:i.toString("base64")}}async decrypt(e){let t=await this.loadOrCreateMasterKey(),r=Bd(Hs,t,Buffer.from(e.iv,"base64"));return r.setAuthTag(Buffer.from(e.tag,"base64")),Buffer.concat([r.update(Buffer.from(e.ciphertext,"base64")),r.final()]).toString("utf8")}async loadOrCreateMasterKey(){if(this.masterKey)return this.masterKey;await Us(this.secretsDir,{recursive:!0});let e=this.masterKeyPath();try{let r=(await Ms(e,"utf8")).trim(),o=Buffer.from(r,"hex");if(o.length!==Oo)throw new Error(`Secret store master key at ${e} is not ${Oo} bytes`);return this.masterKey=o,o}catch(r){if(r.code!=="ENOENT")throw r}let t=Ls(Oo);return await Ws(e,t.toString("hex"),{encoding:"utf8",mode:384}),this.masterKey=t,t}storePath(){return $o(this.secretsDir,Jd)}masterKeyPath(){return $o(this.secretsDir,Nd)}};he=Symbol("SECRET_STORE")});import{Module as Wd}from"@nestjs/common";import{mkdirSync as Hd}from"node:fs";var Md,Ks,Ft,Bo=l(()=>{"use strict";Nn();Fe();Md=function(n,e,t,r){var o=arguments.length,i=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Ks=cn();Hd(Ks,{recursive:!0});Ft=class{};Ft=Md([Wd({providers:[{provide:he,useFactory:()=>Gs({dataDir:Ks})}],exports:[he]})],Ft)});import{index as Gd,sqliteTable as Kd,text as Re}from"drizzle-orm/sqlite-core";var Ye,Fo=l(()=>{"use strict";Ye=Kd("workflow_definitions",{id:Re("id").primaryKey(),name:Re("name").notNull(),description:Re("description"),appliesTo:Re("applies_to",{mode:"json"}).$type().notNull(),subjectHandling:Re("subject_handling",{enum:["per-subject","collection"]}).notNull(),inputSchema:Re("input_schema",{mode:"json"}).$type().notNull(),steps:Re("steps",{mode:"json"}).$type().notNull(),notificationPolicy:Re("notification_policy",{mode:"json"}).$type().notNull(),createdAt:Re("created_at").notNull(),updatedAt:Re("updated_at").notNull()},n=>[Gd("workflow_definitions_subject_handling_idx").on(n.subjectHandling)])});import{index as Vs,integer as Vd,sqliteTable as Qd,text as Ze}from"drizzle-orm/sqlite-core";var ke,No=l(()=>{"use strict";ke=Qd("subject_views",{id:Ze("id").primaryKey(),name:Ze("name").notNull(),subjectType:Ze("subject_type").$type().notNull(),workflowId:Ze("workflow_id").notNull(),query:Ze("query",{mode:"json"}).$type().notNull(),description:Ze("description"),queryTemplate:Ze("query_template",{mode:"json"}).$type(),providerInstanceId:Ze("provider_instance_id").notNull().default(""),order:Vd("order").notNull().default(0)},n=>[Vs("subject_views_subject_type_idx").on(n.subjectType),Vs("subject_views_subject_type_order_idx").on(n.subjectType,n.order)])});import{index as Qs,integer as zd,sqliteTable as Xd,text as Ae}from"drizzle-orm/sqlite-core";var et,Ln=l(()=>{"use strict";et=Xd("job_batches",{id:Ae("id").primaryKey(),workflowId:Ae("workflow_id").notNull(),selection:Ae("selection",{mode:"json"}).$type().notNull(),resolvedSubjects:Ae("resolved_subjects",{mode:"json"}).$type().notNull(),status:Ae("status",{enum:["running","completed","completed_with_issues","failed","cancelled"]}).notNull(),triggeredBy:Ae("triggered_by",{enum:["schedule","view_bulk","multiselect"]}).notNull(),scheduleId:Ae("schedule_id"),notificationOverride:Ae("notification_override",{mode:"json"}).$type(),notificationSent:zd("notification_sent",{mode:"boolean"}).notNull(),createdAt:Ae("created_at").notNull(),completedAt:Ae("completed_at")},n=>[Qs("job_batches_workflow_id_idx").on(n.workflowId),Qs("job_batches_schedule_id_idx").on(n.scheduleId)])});import{index as Un,integer as Yd,sqliteTable as Zd,text as L}from"drizzle-orm/sqlite-core";var M,un=l(()=>{"use strict";Ln();M=Zd("jobs",{id:L("id").primaryKey(),workflowId:L("workflow_id").notNull(),status:L("status").$type().notNull(),selection:L("selection",{mode:"json"}).$type(),batchId:L("batch_id").references(()=>et.id),parentJobId:L("parent_job_id"),parentStepExecutionId:L("parent_step_execution_id"),fanOutIndex:Yd("fan_out_index"),retryOf:L("retry_of"),workflowSnapshot:L("workflow_snapshot",{mode:"json"}).$type(),context:L("context",{mode:"json"}).$type().notNull(),worktreePath:L("worktree_path"),branch:L("branch"),worktreeDeletedAt:L("worktree_deleted_at"),currentStepId:L("current_step_id"),currentStepExecutionId:L("current_step_execution_id"),createdAt:L("created_at").notNull(),updatedAt:L("updated_at").notNull(),completedAt:L("completed_at")},n=>[Un("jobs_workflow_id_idx").on(n.workflowId),Un("jobs_status_idx").on(n.status),Un("jobs_batch_id_idx").on(n.batchId),Un("jobs_parent_job_id_idx").on(n.parentJobId)])});import{index as zs,sqliteTable as ep,text as ln}from"drizzle-orm/sqlite-core";var Ce,Jo=l(()=>{"use strict";un();Ce=ep("job_subjects",{id:ln("id").primaryKey(),jobId:ln("job_id").notNull().references(()=>M.id),subjectType:ln("subject_type").$type().notNull(),subjectId:ln("subject_id").notNull(),snapshot:ln("snapshot",{mode:"json"}).$type().notNull()},n=>[zs("job_subjects_job_id_idx").on(n.jobId),zs("job_subjects_subject_lookup_idx").on(n.subjectType,n.subjectId)])});import{index as Xs,integer as tp,sqliteTable as np,text as ce}from"drizzle-orm/sqlite-core";var wt,Lo=l(()=>{"use strict";un();wt=np("job_step_executions",{id:ce("id").primaryKey(),jobId:ce("job_id").notNull().references(()=>M.id),stepDefinitionId:ce("step_definition_id").notNull(),type:ce("type").$type().notNull(),status:ce("status").$type().notNull(),startedAt:ce("started_at"),completedAt:ce("completed_at"),output:ce("output",{mode:"json"}).$type(),error:ce("error"),failureDetails:ce("failure_details",{mode:"json"}).$type(),childJobIds:ce("child_job_ids",{mode:"json"}).$type(),parentStepExecutionId:ce("parent_step_execution_id").references(()=>wt.id),iterationIndex:tp("iteration_index")},n=>[Xs("job_step_executions_job_id_idx").on(n.jobId),Xs("job_step_executions_parent_idx").on(n.parentStepExecutionId)])});import{index as rp,integer as op,sqliteTable as ip,text as tt}from"drizzle-orm/sqlite-core";var nt,Uo=l(()=>{"use strict";nt=ip("schedules",{id:tt("id").primaryKey(),viewId:tt("view_id").notNull(),triggerType:tt("trigger_type",{enum:["cron"]}).notNull(),cadence:tt("cadence").notNull(),notificationOverride:tt("notification_override",{mode:"json"}).$type(),missedFirePolicy:tt("missed_fire_policy",{enum:["skip","catch_up"]}).notNull(),enabled:op("enabled",{mode:"boolean"}).notNull(),lastFiredAt:tt("last_fired_at"),createdAt:tt("created_at").notNull()},n=>[rp("schedules_enabled_idx").on(n.enabled)])});import{integer as sp,sqliteTable as ap,text as dn}from"drizzle-orm/sqlite-core";var Te,Mo=l(()=>{"use strict";Te=ap("workflow_shortcuts",{id:dn("id").primaryKey(),name:dn("name").notNull(),workflowId:dn("workflow_id").notNull(),inputValues:dn("input_values",{mode:"json"}).$type().notNull(),lastJobId:dn("last_job_id"),order:sp("order").notNull().default(0)})});import{sqliteTable as cp,text as pn}from"drizzle-orm/sqlite-core";var rt,Wo=l(()=>{"use strict";rt=cp("context_files",{id:pn("id").primaryKey(),name:pn("name").notNull(),description:pn("description"),tier:pn("tier").$type().notNull(),path:pn("path").notNull()})});import{sqliteTable as up,text as fn}from"drizzle-orm/sqlite-core";var ot,Ho=l(()=>{"use strict";ot=up("local_repositories",{id:fn("id").primaryKey(),name:fn("name").notNull(),localPath:fn("local_path").notNull(),worktreeBasePath:fn("worktree_base_path"),defaultBranch:fn("default_branch")})});import{sqliteTable as lp,text as Ys}from"drizzle-orm/sqlite-core";var mn,Nt,Go=l(()=>{"use strict";mn="default",Nt=lp("settings",{id:Ys("id").primaryKey(),data:Ys("data",{mode:"json"}).$type().notNull()})});import{defineRelations as dp}from"drizzle-orm";var pp,Zs,ea=l(()=>{"use strict";Fo();No();un();Jo();Lo();Ln();Uo();Mo();Wo();Ho();Go();pp={workflowDefinitions:Ye,subjectViews:ke,jobs:M,jobSubjects:Ce,jobStepExecutions:wt,jobBatches:et,schedules:nt,workflowShortcuts:Te,contextFiles:rt,localRepositories:ot,settings:Nt},Zs=dp(pp,n=>({workflowDefinitions:{},subjectViews:{},schedules:{},workflowShortcuts:{},contextFiles:{},localRepositories:{},settings:{},jobs:{subjects:n.many.jobSubjects({from:n.jobs.id,to:n.jobSubjects.jobId}),stepExecutions:n.many.jobStepExecutions({from:n.jobs.id,to:n.jobStepExecutions.jobId}),batch:n.one.jobBatches({from:n.jobs.batchId,to:n.jobBatches.id})},jobSubjects:{job:n.one.jobs({from:n.jobSubjects.jobId,to:n.jobs.id})},jobStepExecutions:{job:n.one.jobs({from:n.jobStepExecutions.jobId,to:n.jobs.id}),parent:n.one.jobStepExecutions({from:n.jobStepExecutions.parentStepExecutionId,to:n.jobStepExecutions.id,alias:"job_step_executions_parent"}),children:n.many.jobStepExecutions({from:n.jobStepExecutions.id,to:n.jobStepExecutions.parentStepExecutionId,alias:"job_step_executions_children"})},jobBatches:{jobs:n.many.jobs({from:n.jobBatches.id,to:n.jobs.batchId})}}))});import{drizzle as fp}from"drizzle-orm/node-sqlite";import{DatabaseSync as mS}from"node:sqlite";function ta(n){return n.exec("PRAGMA foreign_keys = ON;"),fp({client:n,relations:Zs})}var na=l(()=>{"use strict";ea()});import{existsSync as ra,readdirSync as mp}from"node:fs";import{dirname as hp,join as Ko}from"node:path";import{fileURLToPath as gp}from"node:url";function oa(){let n=hp(gp(import.meta.url)),e=[Ko(n,"persistence/migrations"),Ko(n,"migrations")];for(let t of e)if(yp(t))return t;throw new Error(`Engine SQL migrations not found. Looked in: ${e.join(", ")}`)}function yp(n){return ra(n)?mp(n,{withFileTypes:!0}).some(e=>e.isDirectory()&&ra(Ko(n,e.name,"migration.sql"))):!1}var ia=l(()=>{"use strict"});import{migrate as sa}from"drizzle-orm/node-sqlite/migrator";import{readMigrationFiles as wp}from"drizzle-orm/migrator";function Qo(n,e,t={}){let r=t.log??(()=>{}),o=oa(),i=wp({migrationsFolder:o});if(i.length===0)throw new ge(`No SQL migrations in ${o}`);let s=Sp(i),a=yn(n,bt),u=bp.filter(S=>yn(n,S));if(!a&&u.length===0){sa(e,{migrationsFolder:o}),Vo(n,s);return}if(!a){_p(n,s,r),Ep(n,i),Vo(n,s);return}Ip(n,i);let c=ca(n,s),d=ua(n);if(d.length===0&&u.length>0)throw new ge("migrations table exists but is empty while application tables are present \u2014 treating this as an interrupted update");let m=new Set(d.map(S=>S.name).filter(S=>S!=null&&S!==""));if(i.filter(S=>!m.has(S.name)).length===0&&c.length>0)throw new ge(`migrations journal is present but the schema is incomplete (${c.join("; ")}) \u2014 treating this as an interrupted update`);sa(e,{migrationsFolder:o}),Vo(n,s)}function Sp(n){let e=[],t=[],r=[];for(let o of n)for(let i of o.sql){let s=i.trim().replace(/;+\s*$/,"");if(!s)continue;let a=xp(s);if(a){e.push(a);continue}let u=vp(s);if(u){r.push(u);continue}let c=jp(s);c&&t.push(c)}return{tables:e,indexes:t,alterColumns:r}}function xp(n){let e=n.match(/^CREATE TABLE\s+(`[^`]+`|"[^"]+"|\w+)\s*\(/i);if(!e)return null;let t=n.indexOf("("),r=n.lastIndexOf(")");if(t<0||r<t)return null;let o=[];for(let i of n.slice(t+1,r).split(`
3
+ `)){let s=i.trim().replace(/,+\s*$/,"");if(!s||/^(CONSTRAINT|PRIMARY KEY|UNIQUE|FOREIGN KEY|CHECK)\b/i.test(s))continue;let a=s.match(/^(`[^`]+`|"[^"]+"|\w+)\s+(\w+)/);a&&o.push({name:gn(a[1]),type:a[2]})}return{name:gn(e[1]),createSql:`${n};`,columns:o}}function vp(n){let e=n.match(/^ALTER TABLE\s+(`[^`]+`|"[^"]+"|\w+)\s+ADD(?:\s+COLUMN)?\s+(`[^`]+`|"[^"]+"|\w+)\s+(\w+)/i);return e?{table:gn(e[1]),name:gn(e[2]),type:e[3]}:null}function jp(n){let e=n.match(/^CREATE INDEX\s+(?:IF NOT EXISTS\s+)?(`[^`]+`|"[^"]+"|\w+)/i);if(!e)return null;let t=/^CREATE INDEX\s+IF NOT EXISTS\b/i.test(n)?n:n.replace(/^CREATE INDEX\b/i,"CREATE INDEX IF NOT EXISTS");return{name:gn(e[1]),sql:`${t};`}}function gn(n){return n.replace(/^["`]|["`]$/g,"")}function hn(n){return`\`${n.replace(/`/g,"")}\``}function _p(n,e,t){t("Legacy push-mode database detected (application tables present, no migration journal). Reconciling schema in place.");let r=[],o=[],i=[];n.exec("BEGIN");try{for(let s of e.tables){if(!yn(n,s.name)){n.exec(s.createSql),r.push(s.name);continue}let a=new Set(Mn(n,s.name));for(let u of s.columns)a.has(u.name)||(n.exec(`ALTER TABLE ${hn(s.name)} ADD COLUMN ${hn(u.name)} ${u.type}`),a.add(u.name),o.push(`${s.name}.${u.name}`))}for(let s of e.alterColumns)yn(n,s.table)&&(Mn(n,s.table).includes(s.name)||(n.exec(`ALTER TABLE ${hn(s.table)} ADD COLUMN ${hn(s.name)} ${s.type}`),o.push(`${s.table}.${s.name}`)));for(let s of e.indexes)aa(n,s.name)||(n.exec(s.sql),i.push(s.name));n.exec("COMMIT")}catch(s){throw n.exec("ROLLBACK"),s}for(let s of r)t(`Reconciliation: created table '${s}'`);for(let s of o)t(`Reconciliation: added column ${s}`);for(let s of i)t(`Reconciliation: created index '${s}'`);r.length===0&&o.length===0&&i.length===0&&t("Reconciliation: schema already matched the current baseline; nothing to add."),t("Reconciliation complete. Recording baseline as applied; future startups use normal migrations.")}function yn(n,e){return n.prepare("SELECT 1 AS ok FROM sqlite_master WHERE type = 'table' AND name = ?").get(e)!=null}function aa(n,e){return n.prepare("SELECT 1 AS ok FROM sqlite_master WHERE type = 'index' AND name = ?").get(e)!=null}function Mn(n,e){return n.prepare(`PRAGMA table_info(${hn(e)})`).all().map(r=>r.name)}function ca(n,e){let t=[],r=new Map;for(let o of e.tables)r.set(o.name,new Set(o.columns.map(i=>i.name)));for(let o of e.alterColumns){let i=r.get(o.table)??new Set;i.add(o.name),r.set(o.table,i)}for(let[o,i]of r){if(!yn(n,o)){t.push(`missing table '${o}'`);continue}let s=new Set(Mn(n,o));for(let a of i)s.has(a)||t.push(`table '${o}' is missing column '${a}'`)}for(let o of e.indexes)aa(n,o.name)||t.push(`missing index '${o.name}'`);return t}function Vo(n,e){let t=ca(n,e);if(t.length>0)throw new ge(`schema is incomplete after migrate (${t.join("; ")})`)}function ua(n){let e=new Set(Mn(n,bt));if(!e.has("hash"))throw new ge(`migrations table '${bt}' is missing required columns`);if(!e.has("name"))throw new ge(`migrations table '${bt}' is missing column 'name' \u2014 journal is from an interrupted upgrade`);return n.prepare(`SELECT name, hash FROM ${bt}`).all()}function Ip(n,e){let t=new Map(e.map(r=>[r.name,r]));for(let r of ua(n)){if(r.name==null||r.name==="")throw new ge("migrations journal has a row with no name \u2014 treating this as an interrupted update");let o=t.get(r.name);if(!o)throw new ge(`database has unknown migration '${r.name}' that is not in this Engine build`);if(r.hash!=null&&r.hash!==o.hash)throw new ge(`migration '${r.name}' hash does not match this Engine build \u2014 treating this as a corrupt or interrupted update`)}}function Ep(n,e){n.exec(`
4
+ CREATE TABLE IF NOT EXISTS ${bt} (
5
5
  id INTEGER PRIMARY KEY,
6
6
  hash text NOT NULL,
7
7
  created_at numeric,
8
8
  name text,
9
9
  applied_at TEXT
10
10
  )
11
- `);let t=r.prepare(`INSERT INTO ${ft} (hash, created_at, name, applied_at) VALUES (?, ?, ?, ?)`),n=new Date().toISOString();r.exec("BEGIN");try{for(let o of e)t.run(o.hash,o.folderMillis,o.name,n);r.exec("COMMIT")}catch(o){throw r.exec("ROLLBACK"),o}}var ft,he,Nd,Ms=l(()=>{"use strict";Fs();ft="__drizzle_migrations",he=class extends Error{constructor(e){super(`Engine database migration failed: ${e}`),this.name="DatabaseMigrationError"}},Nd=["workflow_definitions","subject_views","job_batches","jobs","job_subjects","job_step_executions","schedules","workflow_shortcuts","context_files","local_repositories","settings"]});import{Injectable as zd,Logger as Qd}from"@nestjs/common";import{mkdirSync as Xd}from"node:fs";import{dirname as Yd}from"node:path";import{DatabaseSync as Ws}from"node:sqlite";var Kd,Gd,Bo,Y,Hs=l(()=>{"use strict";kr();qs();Ms();Kd=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Gd=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},Y=Bo=class{logger=new Qd(Bo.name);sqlite;db;constructor(){let t=process.env.KNO_SQLITE_PATH??bs();t===":memory:"?this.sqlite=new Ws(":memory:"):(Xd(Yd(t),{recursive:!0}),this.sqlite=new Ws(t)),this.db=$s(this.sqlite),qo(this.sqlite,this.db,{log:n=>this.logger.log(n)})}async onModuleInit(){qo(this.sqlite,this.db,{log:e=>this.logger.log(e)})}getDb(){return this.db}getSqlite(){return this.sqlite}};Y=Bo=Kd([zd(),Gd("design:paramtypes",[])],Y)});import{Injectable as tp}from"@nestjs/common";import{eq as Vs}from"drizzle-orm";var Zd,ep,O,mt=l(()=>{"use strict";jo();Zd=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},ep=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},O=class{db;sqlite;constructor(e,t){this.db=e,this.sqlite=t}async create(e){let t=new Date().toISOString();return await this.db.insert(Ge).values({id:e.id,name:e.name,description:e.description??null,appliesTo:e.appliesTo,subjectHandling:e.subjectHandling,inputSchema:e.inputSchema,steps:e.steps,notificationPolicy:e.notificationPolicy,createdAt:t,updatedAt:t}),await this.get(e.id)}async get(e){let t=await this.db.query.workflowDefinitions.findFirst({where:{id:e}});return t?this.toDomain(t):null}async update(e,t){let n=await this.get(e);return n?(await this.db.update(Ge).set({name:t.name??n.name,description:t.description!==void 0?t.description??null:n.description??null,appliesTo:t.appliesTo??n.appliesTo,subjectHandling:t.subjectHandling??n.subjectHandling,inputSchema:t.inputSchema??n.inputSchema,steps:t.steps??n.steps,notificationPolicy:t.notificationPolicy??n.notificationPolicy,updatedAt:new Date().toISOString()}).where(Vs(Ge.id,e)),this.get(e)):null}async list(e={}){return(e.subjectHandling?await this.db.query.workflowDefinitions.findMany({where:{subjectHandling:e.subjectHandling}}):await this.db.query.workflowDefinitions.findMany()).map(n=>this.toDomain(n))}async delete(e){if(!await this.get(e))return!1;try{this.sqlite?.exec("PRAGMA foreign_keys = OFF"),await this.db.delete(Ge).where(Vs(Ge.id,e))}finally{this.sqlite?.exec("PRAGMA foreign_keys = ON")}return!0}toDomain(e){return{id:e.id,name:e.name,...e.description!=null?{description:e.description}:{},appliesTo:e.appliesTo,subjectHandling:e.subjectHandling,inputSchema:e.inputSchema,steps:e.steps,notificationPolicy:e.notificationPolicy}}};O=Zd([tp(),ep("design:paramtypes",[Object,Function])],O)});import{Injectable as op}from"@nestjs/common";import{eq as Do}from"drizzle-orm";var rp,np,Ks,ie,qr=l(()=>{"use strict";_o();rp=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},np=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},Ks=["ticket","pull_request","documentation"],ie=class{db;constructor(e){this.db=e}async create(e){let t=await this.nextOrder(e.subjectType);return await this.db.insert(Ie).values({id:e.id,name:e.name,subjectType:e.subjectType,workflowId:e.workflowId,query:e.query,description:e.description??null,queryTemplate:e.queryTemplate??null,providerInstanceId:e.providerInstanceId,order:t}),await this.get(e.id)}async get(e){let t=await this.db.query.subjectViews.findFirst({where:{id:e}});return t?this.toDomain(t):null}async update(e,t){let n=await this.get(e);if(!n)return null;let o=t.queryTemplate!==void 0?t.queryTemplate:t.query!==void 0?void 0:n.queryTemplate;return await this.db.update(Ie).set({name:t.name??n.name,subjectType:t.subjectType??n.subjectType,workflowId:t.workflowId??n.workflowId,query:t.query??n.query,description:t.description!==void 0?t.description??null:n.description??null,queryTemplate:o??null,providerInstanceId:t.providerInstanceId??n.providerInstanceId}).where(Do(Ie.id,e)),this.get(e)}async list(e={}){let t=e.subjectType?await this.db.query.subjectViews.findMany({where:{subjectType:e.subjectType}}):await this.db.query.subjectViews.findMany();return this.sortViews(t.map(n=>this.toDomain(n)))}async reorder(e){let t=[];for(let o of e){let i=await this.get(o);if(!i)return[];t.push(i)}let n=t[0].subjectType;if(!t.every(o=>o.subjectType===n))return[];for(let o=0;o<e.length;o+=1)await this.db.update(Ie).set({order:o}).where(Do(Ie.id,e[o]));return this.list({subjectType:n})}async delete(e){return await this.get(e)?(await this.db.delete(Ie).where(Do(Ie.id,e)),!0):!1}async nextOrder(e){let t=await this.db.query.subjectViews.findMany({where:{subjectType:e}});return t.length===0?0:Math.max(...t.map(n=>n.order))+1}sortViews(e){return[...e].sort((t,n)=>{let o=Ks.indexOf(t.subjectType)-Ks.indexOf(n.subjectType);return o!==0?o:t.order-n.order})}toDomain(e){return{id:e.id,name:e.name,subjectType:e.subjectType,workflowId:e.workflowId,providerInstanceId:e.providerInstanceId,query:e.query,order:e.order,...e.description!=null?{description:e.description}:{},...e.queryTemplate!=null?{queryTemplate:e.queryTemplate}:{}}}};ie=rp([op(),np("design:paramtypes",[Object])],ie)});import{Injectable as ap}from"@nestjs/common";import{and as cp,desc as up,eq as dr,inArray as lp}from"drizzle-orm";import{randomUUID as dp}from"node:crypto";function pp(r){return r?r.mode==="single"?[r.subject]:r.subjects:[]}function fp(r){if(r.length!==0)return r.length===1?{mode:"single",subject:r[0]}:{mode:"collection",subjects:r}}function zs(r,e,t=null,n=null){let o=[];for(let i of e)if(o.push({id:i.id,jobId:r,stepDefinitionId:i.stepDefinitionId,type:i.type,status:i.status,startedAt:i.startedAt??null,completedAt:i.completedAt??null,output:i.output??null,error:i.error??null,childJobIds:i.childJobIds??null,parentStepExecutionId:t,iterationIndex:n}),i.iterations)for(let s of i.iterations)o.push(...zs(r,s.stepExecutions,i.id,s.index));return o}function mp(r){let e=new Map;for(let o of r){let i=o.parentStepExecutionId,s=e.get(i)??[];s.push(o),e.set(i,s)}let t=o=>{let i=e.get(o)??[];if(i.length===0)return;let s=new Map;for(let a of i){if(a.iterationIndex==null)continue;let u=s.get(a.iterationIndex)??[];u.push(a),s.set(a.iterationIndex,u)}if(s.size!==0)return[...s.entries()].sort(([a],[u])=>a-u).map(([a,u])=>{let c=u.map(p=>Gs(p,t(p.id)));return{index:a,stepExecutions:c,startedAt:hp(c),...gp(c)?{completedAt:yp(c)}:{}}})};return(e.get(null)??[]).filter(o=>o.iterationIndex==null).map(o=>Gs(o,t(o.id)))}function Gs(r,e){return{id:r.id,stepDefinitionId:r.stepDefinitionId,type:r.type,status:r.status,...r.startedAt!=null?{startedAt:r.startedAt}:{},...r.completedAt!=null?{completedAt:r.completedAt}:{},...r.output!==null&&r.output!==void 0?{output:r.output}:{},...r.error!=null?{error:r.error}:{},...r.childJobIds!=null?{childJobIds:r.childJobIds}:{},...e&&e.length>0?{iterations:e}:{}}}function hp(r){let e=r.map(t=>t.startedAt).filter(t=>t!=null);return e.length===0?"":e.reduce((t,n)=>t<n?t:n)}function yp(r){return r.map(t=>t.completedAt).filter(t=>t!=null).reduce((t,n)=>t>n?t:n)}function gp(r){return r.length>0&&r.every(e=>e.completedAt!=null)}function wp(r){return r==="completed"||r==="failed"||r==="cancelled"}var ip,sp,z,pr=l(()=>{"use strict";nr();Eo();Po();ip=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},sp=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},z=class{db;sqlite;constructor(e,t){this.db=e,this.sqlite=t}async create(e){return await this.withoutForeignKeys(async()=>{await this.db.insert(L).values(this.jobToRow(e)),await this.replaceSubjects(e.id,e.subjectContext),await this.replaceStepExecutions(e.id,e.stepHistory)}),await this.get(e.id)}async get(e){let t=await this.db.query.jobs.findFirst({where:{id:e},with:{subjects:!0,stepExecutions:!0}});return t?this.toDomain(t,t.subjects,t.stepExecutions):null}async update(e,t){let n=await this.get(e);if(!n)return null;let o={...n,...t,id:e,context:t.context??n.context,stepHistory:t.stepHistory??n.stepHistory,updatedAt:t.updatedAt??new Date().toISOString()};return await this.withoutForeignKeys(async()=>{await this.db.update(L).set({workflowId:o.workflowId,status:o.status,selection:o.selection??null,batchId:o.batchId??null,parentJobId:o.parentJobId??null,parentStepExecutionId:o.parentStepExecutionId??null,fanOutIndex:o.fanOutIndex??null,retryOf:o.retryOf??null,workflowSnapshot:o.workflowSnapshot??null,context:o.context,worktreePath:o.worktreePath??null,branch:o.branch??null,worktreeDeletedAt:o.worktreeDeletedAt??null,currentStepId:o.currentStepId??null,currentStepExecutionId:o.currentStepExecutionId??null,createdAt:o.createdAt,updatedAt:o.updatedAt,completedAt:o.completedAt??null}).where(dr(L.id,e)),t.subjectContext!==void 0&&await this.replaceSubjects(e,t.subjectContext),t.stepHistory!==void 0&&await this.replaceStepExecutions(e,t.stepHistory)}),this.get(e)}async list(e={}){let t={};e.workflowId!==void 0&&(t.workflowId=e.workflowId),e.status!==void 0&&(t.status=e.status),e.batchId!==void 0&&(t.batchId=e.batchId),e.parentJobId!==void 0&&(t.parentJobId=e.parentJobId),e.parentStepExecutionId!==void 0&&(t.parentStepExecutionId=e.parentStepExecutionId);let o=(Object.keys(t).length>0?await this.db.query.jobs.findMany({where:t,with:{subjects:!0,stepExecutions:!0}}):await this.db.query.jobs.findMany({with:{subjects:!0,stepExecutions:!0}})).map(s=>this.toDomain(s,s.subjects,s.stepExecutions)),i=e.topLevelOnly?o.filter(s=>s.batchId==null&&s.parentJobId==null):o;return e.liveWorktree&&(i=i.filter(s=>s.worktreePath!=null&&s.worktreeDeletedAt==null)),e.terminal===void 0?i:i.filter(s=>wp(s.status)===e.terminal)}async latestBySubject(e,t){let n={};for(let c of t)n[c]=null;if(t.length===0)return n;let o=await this.db.select({subjectId:_e.subjectId,jobId:L.id,createdAt:L.createdAt}).from(_e).innerJoin(L,dr(_e.jobId,L.id)).where(cp(dr(L.workflowId,e),lp(_e.subjectId,t))).orderBy(up(L.createdAt)),i=new Map;for(let c of o)i.has(c.subjectId)||i.set(c.subjectId,c.jobId);let s=[...new Set(i.values())],a=await Promise.all(s.map(c=>this.get(c))),u=new Map(a.filter(c=>c!=null).map(c=>[c.id,c]));for(let[c,p]of i)n[c]=u.get(p)??null;return n}async withoutForeignKeys(e){if(!this.sqlite){await e();return}try{this.sqlite.exec("PRAGMA foreign_keys = OFF"),await e()}finally{this.sqlite.exec("PRAGMA foreign_keys = ON")}}jobToRow(e){return{id:e.id,workflowId:e.workflowId,status:e.status,selection:e.selection??null,batchId:e.batchId??null,parentJobId:e.parentJobId??null,parentStepExecutionId:e.parentStepExecutionId??null,fanOutIndex:e.fanOutIndex??null,retryOf:e.retryOf??null,workflowSnapshot:e.workflowSnapshot??null,context:e.context,worktreePath:e.worktreePath??null,branch:e.branch??null,worktreeDeletedAt:e.worktreeDeletedAt??null,currentStepId:e.currentStepId??null,currentStepExecutionId:e.currentStepExecutionId??null,createdAt:e.createdAt,updatedAt:e.updatedAt,completedAt:e.completedAt??null}}async replaceSubjects(e,t){await this.db.delete(_e).where(dr(_e.jobId,e));let n=pp(t);n.length!==0&&await this.db.insert(_e).values(n.map(o=>({id:dp(),jobId:e,subjectType:o.subjectType,subjectId:o.id,snapshot:o})))}async replaceStepExecutions(e,t){await this.db.delete(pt).where(dr(pt.jobId,e));let n=zs(e,t);n.length!==0&&await this.db.insert(pt).values(n)}toDomain(e,t,n){let o=fp(t.map(s=>s.snapshot)),i=mp(n);return{id:e.id,workflowId:e.workflowId,status:e.status,...o?{subjectContext:o}:{},...e.selection!=null?{selection:e.selection}:{},...e.batchId!=null?{batchId:e.batchId}:{},...e.parentJobId!=null?{parentJobId:e.parentJobId}:{},...e.parentStepExecutionId!=null?{parentStepExecutionId:e.parentStepExecutionId}:{},...e.fanOutIndex!=null?{fanOutIndex:e.fanOutIndex}:{},...e.retryOf!=null?{retryOf:e.retryOf}:{},...e.workflowSnapshot!=null?{workflowSnapshot:e.workflowSnapshot}:{},context:e.context,...e.worktreePath!=null?{worktreePath:e.worktreePath}:{},...e.branch!=null?{branch:e.branch}:{},...e.worktreeDeletedAt!=null?{worktreeDeletedAt:e.worktreeDeletedAt}:{},...e.currentStepId!=null?{currentStepId:e.currentStepId}:{},...e.currentStepExecutionId!=null?{currentStepExecutionId:e.currentStepExecutionId}:{},stepHistory:i,createdAt:e.createdAt,updatedAt:e.updatedAt,...e.completedAt!=null?{completedAt:e.completedAt}:{}}}};z=ip([ap(),sp("design:paramtypes",[Object,Function])],z)});import{Injectable as xp}from"@nestjs/common";import{eq as vp}from"drizzle-orm";var bp,Sp,se,Br=l(()=>{"use strict";Cr();bp=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Sp=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},se=class{db;constructor(e){this.db=e}async create(e){return await this.db.insert(Qe).values({id:e.id,workflowId:e.workflowId,selection:e.selection,resolvedSubjects:e.resolvedSubjects,status:e.status,triggeredBy:e.triggeredBy,scheduleId:e.scheduleId??null,notificationOverride:e.notificationOverride??null,notificationSent:e.notificationSent,createdAt:e.createdAt,completedAt:e.completedAt??null}),await this.get(e.id)}async get(e){let t=await this.db.query.jobBatches.findFirst({where:{id:e},with:{jobs:!0}});return t?this.toDomain(t,t.jobs.map(n=>n.id)):null}async update(e,t){let n=await this.get(e);return n?(await this.db.update(Qe).set({workflowId:t.workflowId??n.workflowId,selection:t.selection??n.selection,resolvedSubjects:t.resolvedSubjects??n.resolvedSubjects,status:t.status??n.status,triggeredBy:t.triggeredBy??n.triggeredBy,scheduleId:t.scheduleId!==void 0?t.scheduleId??null:n.scheduleId??null,notificationOverride:t.notificationOverride!==void 0?t.notificationOverride??null:n.notificationOverride??null,notificationSent:t.notificationSent??n.notificationSent,createdAt:t.createdAt??n.createdAt,completedAt:t.completedAt!==void 0?t.completedAt??null:n.completedAt??null}).where(vp(Qe.id,e)),this.get(e)):null}async list(e={}){return(e.workflowId?await this.db.query.jobBatches.findMany({where:{workflowId:e.workflowId},with:{jobs:!0}}):await this.db.query.jobBatches.findMany({with:{jobs:!0}})).map(n=>this.toDomain(n,n.jobs.map(o=>o.id)))}toDomain(e,t){return{id:e.id,workflowId:e.workflowId,selection:e.selection,resolvedSubjects:e.resolvedSubjects,jobIds:t,status:e.status,triggeredBy:e.triggeredBy,...e.scheduleId!=null?{scheduleId:e.scheduleId}:{},...e.notificationOverride!=null?{notificationOverride:e.notificationOverride}:{},notificationSent:e.notificationSent,createdAt:e.createdAt,...e.completedAt!=null?{completedAt:e.completedAt}:{}}}};se=bp([xp(),Sp("design:paramtypes",[Object])],se)});import{Injectable as _p}from"@nestjs/common";import{eq as Qs}from"drizzle-orm";var Ip,jp,$e,Fo=l(()=>{"use strict";Ro();Ip=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},jp=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},$e=class{db;constructor(e){this.db=e}async create(e){return await this.db.insert(Ye).values({id:e.id,viewId:e.viewId,triggerType:e.trigger.type,cadence:e.trigger.cadence,notificationOverride:e.notificationOverride??null,missedFirePolicy:e.missedFirePolicy,enabled:e.enabled,lastFiredAt:e.lastFiredAt??null,createdAt:e.createdAt}),await this.get(e.id)}async get(e){let t=await this.db.query.schedules.findFirst({where:{id:e}});return t?this.toDomain(t):null}async update(e,t){let n=await this.get(e);if(!n)return null;let o=t.trigger??n.trigger;return await this.db.update(Ye).set({viewId:t.viewId??n.viewId,triggerType:o.type,cadence:o.cadence,notificationOverride:t.notificationOverride!==void 0?t.notificationOverride??null:n.notificationOverride??null,missedFirePolicy:t.missedFirePolicy??n.missedFirePolicy,enabled:t.enabled??n.enabled,lastFiredAt:t.lastFiredAt!==void 0?t.lastFiredAt??null:n.lastFiredAt??null,createdAt:t.createdAt??n.createdAt}).where(Qs(Ye.id,e)),this.get(e)}async list(e={}){return(e.enabled!==void 0?await this.db.query.schedules.findMany({where:{enabled:e.enabled}}):await this.db.query.schedules.findMany()).map(n=>this.toDomain(n))}async delete(e){return await this.get(e)?(await this.db.delete(Ye).where(Qs(Ye.id,e)),!0):!1}async findDue(e){return(await this.list({enabled:!0})).filter(n=>n.lastFiredAt==null||n.lastFiredAt<e)}toDomain(e){return{id:e.id,viewId:e.viewId,trigger:{type:"cron",cadence:e.cadence},...e.notificationOverride!=null?{notificationOverride:e.notificationOverride}:{},missedFirePolicy:e.missedFirePolicy,enabled:e.enabled,...e.lastFiredAt!=null?{lastFiredAt:e.lastFiredAt}:{},createdAt:e.createdAt}}};$e=Ip([_p(),jp("design:paramtypes",[Object])],$e)});import{Injectable as Rp}from"@nestjs/common";import{eq as No}from"drizzle-orm";var Ep,Pp,qe,Jo=l(()=>{"use strict";ko();Ep=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Pp=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},qe=class{db;constructor(e){this.db=e}async create(e){let t=await this.nextOrder();return await this.db.insert(Ee).values({id:e.id,name:e.name,workflowId:e.workflowId,inputValues:e.inputValues,lastJobId:e.lastJobId??null,order:t}),await this.get(e.id)}async get(e){let t=await this.db.query.workflowShortcuts.findFirst({where:{id:e}});return t?this.toDomain(t):null}async update(e,t){let n=await this.get(e);return n?(await this.db.update(Ee).set({name:t.name??n.name,workflowId:t.workflowId??n.workflowId,inputValues:t.inputValues??n.inputValues,lastJobId:t.lastJobId!==void 0?t.lastJobId??null:n.lastJobId??null}).where(No(Ee.id,e)),this.get(e)):null}async list(){return(await this.db.query.workflowShortcuts.findMany()).map(t=>this.toDomain(t)).sort((t,n)=>t.order-n.order)}async reorder(e){let t=[];for(let n of e){let o=await this.get(n);if(!o)return[];t.push(o)}for(let n=0;n<e.length;n+=1)await this.db.update(Ee).set({order:n}).where(No(Ee.id,e[n]));return this.list()}async delete(e){return await this.get(e)?(await this.db.delete(Ee).where(No(Ee.id,e)),!0):!1}async nextOrder(){let e=await this.db.query.workflowShortcuts.findMany();return e.length===0?0:Math.max(...e.map(t=>t.order))+1}toDomain(e){return{id:e.id,name:e.name,workflowId:e.workflowId,inputValues:e.inputValues,order:e.order,...e.lastJobId!=null?{lastJobId:e.lastJobId}:{}}}};qe=Ep([Rp(),Pp("design:paramtypes",[Object])],qe)});import{Injectable as Cp}from"@nestjs/common";import{eq as Xs}from"drizzle-orm";var kp,Ap,ae,Dr=l(()=>{"use strict";Ao();kp=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Ap=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},ae=class{db;constructor(e){this.db=e}async create(e){return await this.db.insert(Ze).values({id:e.id,name:e.name,description:e.description??null,tier:e.tier,path:e.path}),await this.get(e.id)}async get(e){let t=await this.db.query.contextFiles.findFirst({where:{id:e}});return t?this.toDomain(t):null}async update(e,t){let n=await this.get(e);return n?(await this.db.update(Ze).set({name:t.name??n.name,description:t.description!==void 0?t.description??null:n.description??null,tier:t.tier??n.tier,path:t.path??n.path}).where(Xs(Ze.id,e)),this.get(e)):null}async list(){return(await this.db.query.contextFiles.findMany()).map(t=>this.toDomain(t)).sort((t,n)=>t.name.localeCompare(n.name))}async delete(e){return await this.get(e)?(await this.db.delete(Ze).where(Xs(Ze.id,e)),!0):!1}toDomain(e){return{id:e.id,name:e.name,tier:e.tier,path:e.path,...e.description!=null&&e.description!==""?{description:e.description}:{}}}};ae=kp([Cp(),Ap("design:paramtypes",[Object])],ae)});import{Injectable as $p}from"@nestjs/common";import{eq as Ys}from"drizzle-orm";var Tp,Op,ce,Fr=l(()=>{"use strict";Co();Tp=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Op=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},ce=class{db;constructor(e){this.db=e}async create(e){return await this.db.insert(et).values({id:e.id,name:e.name,localPath:e.localPath,worktreeBasePath:e.worktreeBasePath??null}),await this.get(e.id)}async get(e){let t=await this.db.query.localRepositories.findFirst({where:{id:e}});return t?this.toDomain(t):null}async findByLocalPath(e){let n=(await this.db.query.localRepositories.findMany()).find(o=>o.localPath===e);return n?this.toDomain(n):null}async update(e,t){let n=await this.get(e);return n?(await this.db.update(et).set({name:t.name??n.name,localPath:t.localPath??n.localPath,worktreeBasePath:t.worktreeBasePath!==void 0?t.worktreeBasePath??null:n.worktreeBasePath??null}).where(Ys(et.id,e)),this.get(e)):null}async list(){return(await this.db.query.localRepositories.findMany()).map(t=>this.toDomain(t)).sort((t,n)=>t.name.localeCompare(n.name))}async delete(e){return await this.get(e)?(await this.db.delete(et).where(Ys(et.id,e)),!0):!1}toDomain(e){return{id:e.id,name:e.name,localPath:e.localPath,...e.worktreeBasePath!=null&&e.worktreeBasePath!==""?{worktreeBasePath:e.worktreeBasePath}:{}}}};ce=Tp([$p(),Op("design:paramtypes",[Object])],ce)});import{z as E}from"zod";var Zs,ea,ta,Lo,Nr,ra,Uo=l(()=>{"use strict";Zs=E.object({name:E.string().min(1),label:E.string().min(1),type:E.enum(["string","select"]),options:E.array(E.string()).optional(),required:E.boolean()}),ea=E.object({id:E.string().min(1),label:E.string().min(1),params:E.array(Zs)}),ta=E.object({actionId:E.string().min(1),label:E.string().min(1),params:E.array(Zs)}),Lo=E.object({templateId:E.string().min(1),params:E.record(E.string(),E.unknown())}),Nr=E.object({params:E.record(E.string(),E.unknown())}),ra=E.object({query:E.record(E.string(),E.unknown())})});import{z as Z}from"zod";var re,Jr,Lr,Ur,Mr,Wr=l(()=>{"use strict";Uo();re=Z.enum(["ticket","pull_request","documentation"]),Jr=Z.object({id:Z.string().min(1),name:Z.string().min(1),subjectType:re,workflowId:Z.string().min(1),providerInstanceId:Z.string().min(1),query:Z.record(Z.string(),Z.unknown()),description:Z.string().optional(),queryTemplate:Lo.optional(),order:Z.number().int().nonnegative()}),Lr=Jr.omit({order:!0}),Ur=Jr.partial().omit({id:!0,order:!0}).extend({queryTemplate:Lo.nullable().optional()}),Mr=Z.object({viewIds:Z.array(Z.string().min(1)).min(1)})});var na=l(()=>{"use strict";Wr()});var oa=l(()=>{"use strict";Uo()});function qp(r){let e=r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"");return e.length>0?e:"step"}function ia(r,e){let t=e instanceof Set?e:new Set(e),n=qp(r);if(!t.has(n))return n;let o=2;for(;t.has(`${n}-${o}`);)o+=1;return`${n}-${o}`}function sa(r,e){for(let t of r)t.id&&e.push(t.id),t.type==="loop"&&Array.isArray(t.steps)&&sa(t.steps,e)}function aa(r){let e=[];sa(r,e);let t=new Map;for(let n of e)t.set(n,(t.get(n)??0)+1);return[...t.entries()].filter(([,n])=>n>1).map(([n])=>n)}function ca(r){let e=new Set,t=n=>{for(let o of n)o.id&&e.add(o.id),o.type==="loop"&&Array.isArray(o.steps)&&t(o.steps)};return t(r),e}var Mo=l(()=>{"use strict"});import{z as f}from"zod";function Jp(r){return!!(r.path?.trim()||r.pattern?.trim())}function Sa(r){let e=[];for(let t of r)e.push(t),t.type==="loop"&&e.push(...Sa(t.steps));return e}var Bp,fr,Dp,Be,ua,la,da,pa,fa,ma,ha,ya,Fp,Np,ga,wa,ba,ht,Lp,Up,Mp,Wp,Hp,Vp,Kp,Gp,xa,tt,va=l(()=>{"use strict";Wr();Mo();Bp=f.enum(["on_fail","on_complete","on_needs_input"]),fr=f.object({triggers:f.array(Bp),messageTemplate:f.string().optional()}),Dp=f.object({name:f.string().min(1),label:f.string().min(1),type:f.enum(["string","number","boolean","select","localRepository"]),options:f.array(f.string()).optional(),required:f.boolean(),defaultValue:f.unknown().optional()}),Be=f.string().min(1),ua=f.object({type:f.literal("agent"),id:f.string().min(1),name:Be,objective:f.string().min(1),contextFileIds:f.array(f.string().min(1)).optional(),outputFormat:f.enum(["questionnaire","confirmation","comment_suggestions","free_text"]),agentInstanceId:f.string().min(1).optional()}),la=f.object({type:f.literal("interaction"),id:f.string().min(1),name:Be,interaction:f.union([f.literal("questionnaire"),f.literal("confirmation"),f.literal("conversation")]),notify:f.boolean().optional()}),da=f.object({type:f.literal("shell"),id:f.string().min(1),name:Be,command:f.string().min(1)}),pa=f.object({type:f.literal("git"),id:f.string().min(1),name:Be,operation:f.enum(["create_worktree","checkout","create_branch","commit","push"]),params:f.record(f.string(),f.unknown())}),fa=f.object({type:f.literal("provider_action"),id:f.string().min(1),name:Be,action:f.enum(["get_subject","get_comments","post_comment","update_status","get_content"]),params:f.record(f.string(),f.unknown()).optional(),extendedAction:f.object({providerId:f.string().min(1),actionId:f.string().min(1),params:f.record(f.string(),f.unknown()).optional()}).optional(),target:f.object({subjectType:re,source:f.string().min(1),subjectId:f.string().min(1)}).optional()}),ma=f.object({type:f.literal("sub_workflow"),id:f.string().min(1),name:Be,workflowId:f.string().min(1),forEach:f.literal("selection")}),ha=f.discriminatedUnion("type",[f.object({type:f.literal("field_empty"),stepId:f.string().min(1),field:f.string().min(1)}),f.object({type:f.literal("field_equals"),stepId:f.string().min(1),field:f.string().min(1),value:f.unknown()})]),ya=f.discriminatedUnion("action",[f.object({action:f.literal("fail")}),f.object({action:f.literal("continue")}),f.object({action:f.literal("ask_human")})]),Fp=f.object({type:f.literal("loop"),id:f.string().min(1),name:Be,steps:f.array(f.lazy(()=>wa)),until:ha,maxIterations:f.number().int().nonnegative(),onMaxIterations:ya}),Np=f.enum(["fail","empty","ask_human"]),ga=f.object({type:f.literal("extract"),id:f.string().min(1),name:Be,source:f.string(),path:f.string().optional(),pattern:f.string().optional(),onNoMatch:Np}),wa=f.lazy(()=>f.discriminatedUnion("type",[pa,fa,da,ua,la,ma,Fp,ga])),ba=f.object({id:f.string().min(1),name:f.string().min(1),description:f.string().optional(),appliesTo:f.union([re,f.array(re),f.literal("none")]),subjectHandling:f.enum(["per-subject","collection"]),inputSchema:f.array(Dp),steps:f.array(wa),notificationPolicy:fr}),ht=ba.superRefine((r,e)=>{let t=aa(r.steps);t.length>0&&e.addIssue({code:"custom",path:["steps"],message:`Duplicate step id(s): ${t.join(", ")}`});for(let n of Sa(r.steps))n.type==="extract"&&(Jp(n)||e.addIssue({code:"custom",path:["steps"],message:`Extract step '${n.id}' must set at least one of path or pattern`}))});Lp=ua.extend({id:f.string().min(1).optional()}),Up=la.extend({id:f.string().min(1).optional()}),Mp=da.extend({id:f.string().min(1).optional()}),Wp=pa.extend({id:f.string().min(1).optional()}),Hp=fa.extend({id:f.string().min(1).optional()}),Vp=ma.extend({id:f.string().min(1).optional()}),Kp=f.object({type:f.literal("loop"),id:f.string().min(1).optional(),name:Be,steps:f.array(f.lazy(()=>xa)),until:ha,maxIterations:f.number().int().nonnegative(),onMaxIterations:ya}),Gp=ga.extend({id:f.string().min(1).optional()}),xa=f.lazy(()=>f.discriminatedUnion("type",[Wp,Hp,Mp,Lp,Up,Vp,Kp,Gp])),tt=ba.omit({id:!0,steps:!0}).extend({id:f.string().min(1).optional(),steps:f.array(xa)})});function Ia(r){return r==="none"?[]:Array.isArray(r)?r:[r]}function ja(r,e){return Ia(r).includes(e)}var Wo=l(()=>{"use strict"});var _a=l(()=>{"use strict"});var Ea=l(()=>{"use strict";Wo()});var Pa=l(()=>{"use strict";va();Mo();Wo();_a();Ea()});import{z as yt}from"zod";var zp,Hr,Vr,Kr,Ra=l(()=>{"use strict";zp=yt.enum(["user","organization","project"]),Hr=yt.object({id:yt.string().min(1),name:yt.string().min(1),description:yt.string().optional(),tier:zp,path:yt.string().min(1)}),Vr=Hr.omit({id:!0}).extend({id:yt.string().min(1).optional()}),Kr=Hr.partial().omit({id:!0})});var ka=l(()=>{"use strict";Ra()});import{z as Tt}from"zod";var Gr,zr,Qr,Aa=l(()=>{"use strict";Gr=Tt.object({id:Tt.string().min(1),name:Tt.string().min(1),localPath:Tt.string().min(1),worktreeBasePath:Tt.string().min(1).optional()}),zr=Gr.omit({id:!0}).extend({id:Tt.string().min(1).optional()}),Qr=Gr.partial().omit({id:!0})});var Ca=l(()=>{"use strict";Aa()});var Ta=l(()=>{"use strict"});var Oa=l(()=>{"use strict";Ta()});var $a=l(()=>{"use strict"});var qa=l(()=>{"use strict";$a()});import{z as ee}from"zod";var Ot,Ba=l(()=>{"use strict";Ot=ee.object({id:ee.string().min(1),viewId:ee.string().min(1),trigger:ee.object({type:ee.literal("cron"),cadence:ee.string().min(1)}),notificationOverride:ee.object({triggers:ee.array(ee.enum(["on_fail","on_complete","on_needs_input"])),messageTemplate:ee.string().optional()}).optional(),missedFirePolicy:ee.enum(["skip","catch_up"]),enabled:ee.boolean(),lastFiredAt:ee.string().optional(),createdAt:ee.string()})});var Da=l(()=>{"use strict";Ba()});import{z as ue}from"zod";var Xr,Yr,Zr,en,Fa=l(()=>{"use strict";Xr=ue.object({id:ue.string().min(1),name:ue.string().min(1),workflowId:ue.string().min(1),inputValues:ue.record(ue.string(),ue.unknown()),lastJobId:ue.string().min(1).optional(),order:ue.number().int().nonnegative()}),Yr=Xr.omit({order:!0}),Zr=Xr.partial().omit({id:!0,order:!0}),en=ue.object({shortcutIds:ue.array(ue.string().min(1)).min(1)})});var Na=l(()=>{"use strict";Fa()});import{z as x}from"zod";function gt(r){return r.kind==="subject"}function $t(r){return r.kind==="agent"}var Qp,Ja,La,Ua,Ma,tn,rn,nn,on,sn,an,Wa,Ha,Va=l(()=>{"use strict";Wr();Qp=x.enum(["jira","bitbucket","github","confluence","manual"]),Ja=x.enum(["claude","cursor"]),La={id:x.string().min(1),displayName:x.string().min(1),config:x.record(x.string(),x.unknown()),secretKey:x.string().min(1),expiresOn:x.string().min(1).optional()},Ua=x.object({...La,kind:x.literal("subject"),type:Qp,subjectType:re}),Ma=x.object({...La,kind:x.literal("agent"),type:Ja}),tn=x.discriminatedUnion("kind",[Ua,Ma]),rn=x.object({providerInstances:x.array(tn).default([]),defaultAgentInstanceId:x.string().min(1).optional()}),nn=x.object({providerInstances:x.array(tn).optional(),defaultAgentInstanceId:x.string().min(1).nullable().optional()}),on=x.discriminatedUnion("kind",[Ua.extend({defaultAgent:x.boolean().optional()}),Ma.extend({defaultAgent:x.boolean().optional()})]),sn=x.object({displayName:x.string().min(1).optional(),config:x.record(x.string(),x.unknown()).optional(),secretKey:x.string().min(1).optional(),expiresOn:x.union([x.string().min(1),x.null()]).optional(),defaultAgent:x.boolean().optional()}),an=x.object({type:Ja,apiKey:x.string().min(1).optional(),instanceId:x.string().min(1).optional()}),Wa=x.object({id:x.string().min(1),displayName:x.string().min(1)}),Ha={providerInstances:[]}});var Ka=l(()=>{"use strict";Va()});var Ga=l(()=>{"use strict"});var za=l(()=>{"use strict";Ga()});var C=l(()=>{"use strict";na();oa();Pa();ka();Ca();Oa();qa();Da();Na();Ka();za()});import{Injectable as Zp}from"@nestjs/common";import{eq as ef}from"drizzle-orm";function tf(r,e){let t=e.providerInstances!==void 0?e.providerInstances:r.providerInstances,n=e.defaultAgentInstanceId===null?void 0:e.defaultAgentInstanceId!==void 0?e.defaultAgentInstanceId:r.defaultAgentInstanceId;return Ho({providerInstances:t,...n?{defaultAgentInstanceId:n}:{}})}function Ho(r){return{providerInstances:r.providerInstances??Ha.providerInstances,...r.defaultAgentInstanceId?{defaultAgentInstanceId:r.defaultAgentInstanceId}:{}}}function Qa(r){return r.providerInstances!==void 0}var Xp,Yp,P,Pe=l(()=>{"use strict";C();To();Xp=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Yp=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},P=class{db;constructor(e){this.db=e}async get(){let e=await this.db.query.settings.findFirst({where:{id:ar}});return Ho(e?e.data:{})}async update(e){let t=tf(await this.get(),e);return await this.db.query.settings.findFirst({where:{id:ar}})?await this.db.update(Ct).set({data:t}).where(ef(Ct.id,ar)):await this.db.insert(Ct).values({id:ar,data:t}),t}async replaceProviderInstances(e){return this.update({providerInstances:e})}};P=Xp([Zp(),Yp("design:paramtypes",[Object])],P)});import{Module as nf}from"@nestjs/common";var rf,of,Re,mr=l(()=>{"use strict";Hs();mt();qr();pr();Br();Fo();Jo();Dr();Fr();Pe();rf=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},of=[O,ie,z,se,$e,qe,ae,ce,P],Re=class{};Re=rf([nf({providers:[Y,{provide:O,useFactory:r=>new O(r.getDb(),r.getSqlite()),inject:[Y]},{provide:ie,useFactory:r=>new ie(r.getDb()),inject:[Y]},{provide:z,useFactory:r=>new z(r.getDb(),r.getSqlite()),inject:[Y]},{provide:se,useFactory:r=>new se(r.getDb()),inject:[Y]},{provide:$e,useFactory:r=>new $e(r.getDb()),inject:[Y]},{provide:qe,useFactory:r=>new qe(r.getDb()),inject:[Y]},{provide:ae,useFactory:r=>new ae(r.getDb()),inject:[Y]},{provide:ce,useFactory:r=>new ce(r.getDb()),inject:[Y]},{provide:P,useFactory:r=>new P(r.getDb()),inject:[Y]}],exports:[Y,...of]})],Re)});import{Injectable as cf,Logger as uf,Inject as Ya}from"@nestjs/common";async function Za(r,e){let t=[];for(let n of e){let o=await r.get(n.secretKey);t.push({providerId:n.id,secretKey:n.secretKey,configured:typeof o=="string"&&o.length>0})}return t}async function lf(r,e,t){let n=await Za(r,e);for(let o of n)o.configured||t(`Provider instance '${o.providerId}' API key not configured (looked up as '${o.secretKey}'). GET /api/providers/status lists what's missing; store a key with: POST /api/secrets/${o.secretKey} or npm --workspace apps/engine run set-secret -- ${o.secretKey} <value>`)}var sf,af,Xa,Vo,rt,Ko=l(()=>{"use strict";Pe();Oe();sf=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},af=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},Xa=function(r,e){return function(t,n){e(t,n,r)}};rt=Vo=class{secrets;settings;logger=new uf(Vo.name);constructor(e,t){this.secrets=e,this.settings=t}async onModuleInit(){let e=await this.settings.get();await lf(this.secrets,e.providerInstances??[],t=>this.logger.warn(t))}async list(){let e=await this.settings.get();return Za(this.secrets,e.providerInstances??[])}};rt=Vo=sf([cf(),Xa(0,Ya(fe)),Xa(1,Ya(P)),af("design:paramtypes",[Function,P])],rt)});function cn(r,e=kt(r)){let t=mf[r]??r;return new Error(`${t} API key not configured \u2014 set '${e}' via the setup script`)}function ec(r){let e=new Map;for(let n of r){let o=n.content.trim();if(!o)continue;let i=e.get(n.tier)??[];i.push(o),e.set(n.tier,i)}let t=[];for(let n of pf){let o=e.get(n);o?.length&&t.push(`## ${df[n]}
11
+ `);let t=n.prepare(`INSERT INTO ${bt} (hash, created_at, name, applied_at) VALUES (?, ?, ?, ?)`),r=new Date().toISOString();n.exec("BEGIN");try{for(let o of e)t.run(o.hash,o.folderMillis,o.name,r);n.exec("COMMIT")}catch(o){throw n.exec("ROLLBACK"),o}}var bt,ge,bp,la=l(()=>{"use strict";ia();bt="__drizzle_migrations",ge=class extends Error{constructor(e){super(`Engine database migration failed: ${e}`),this.name="DatabaseMigrationError"}},bp=["workflow_definitions","subject_views","job_batches","jobs","job_subjects","job_step_executions","schedules","workflow_shortcuts","context_files","local_repositories","settings"]});import{Injectable as kp,Logger as Ap}from"@nestjs/common";import{mkdirSync as Cp}from"node:fs";import{dirname as Tp}from"node:path";import{DatabaseSync as da}from"node:sqlite";var Pp,Rp,zo,Z,pa=l(()=>{"use strict";Nn();na();la();Pp=function(n,e,t,r){var o=arguments.length,i=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Rp=function(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)},Z=zo=class{logger=new Ap(zo.name);sqlite;db;constructor(){let t=process.env.KNO_SQLITE_PATH??Js();t===":memory:"?this.sqlite=new da(":memory:"):(Cp(Tp(t),{recursive:!0}),this.sqlite=new da(t)),this.db=ta(this.sqlite),Qo(this.sqlite,this.db,{log:r=>this.logger.log(r)})}async onModuleInit(){Qo(this.sqlite,this.db,{log:e=>this.logger.log(e)})}getDb(){return this.db}getSqlite(){return this.sqlite}};Z=zo=Pp([kp(),Rp("design:paramtypes",[])],Z)});import{Injectable as qp}from"@nestjs/common";import{eq as fa}from"drizzle-orm";var Op,$p,D,St=l(()=>{"use strict";Fo();Op=function(n,e,t,r){var o=arguments.length,i=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},$p=function(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)},D=class{db;sqlite;constructor(e,t){this.db=e,this.sqlite=t}async create(e){let t=new Date().toISOString();return await this.db.insert(Ye).values({id:e.id,name:e.name,description:e.description??null,appliesTo:e.appliesTo,subjectHandling:e.subjectHandling,inputSchema:e.inputSchema,steps:e.steps,notificationPolicy:e.notificationPolicy,createdAt:t,updatedAt:t}),await this.get(e.id)}async get(e){let t=await this.db.query.workflowDefinitions.findFirst({where:{id:e}});return t?this.toDomain(t):null}async update(e,t){let r=await this.get(e);return r?(await this.db.update(Ye).set({name:t.name??r.name,description:t.description!==void 0?t.description??null:r.description??null,appliesTo:t.appliesTo??r.appliesTo,subjectHandling:t.subjectHandling??r.subjectHandling,inputSchema:t.inputSchema??r.inputSchema,steps:t.steps??r.steps,notificationPolicy:t.notificationPolicy??r.notificationPolicy,updatedAt:new Date().toISOString()}).where(fa(Ye.id,e)),this.get(e)):null}async list(e={}){return(e.subjectHandling?await this.db.query.workflowDefinitions.findMany({where:{subjectHandling:e.subjectHandling}}):await this.db.query.workflowDefinitions.findMany()).map(r=>this.toDomain(r))}async delete(e){if(!await this.get(e))return!1;try{this.sqlite?.exec("PRAGMA foreign_keys = OFF"),await this.db.delete(Ye).where(fa(Ye.id,e))}finally{this.sqlite?.exec("PRAGMA foreign_keys = ON")}return!0}toDomain(e){return{id:e.id,name:e.name,...e.description!=null?{description:e.description}:{},appliesTo:e.appliesTo,subjectHandling:e.subjectHandling,inputSchema:e.inputSchema,steps:e.steps,notificationPolicy:e.notificationPolicy}}};D=Op([qp(),$p("design:paramtypes",[Object,Function])],D)});import{Injectable as Fp}from"@nestjs/common";import{eq as Xo}from"drizzle-orm";var Dp,Bp,ma,ue,Wn=l(()=>{"use strict";No();Dp=function(n,e,t,r){var o=arguments.length,i=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Bp=function(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)},ma=["ticket","pull_request","documentation"],ue=class{db;constructor(e){this.db=e}async create(e){let t=await this.nextOrder(e.subjectType);return await this.db.insert(ke).values({id:e.id,name:e.name,subjectType:e.subjectType,workflowId:e.workflowId,query:e.query,description:e.description??null,queryTemplate:e.queryTemplate??null,providerInstanceId:e.providerInstanceId,order:t}),await this.get(e.id)}async get(e){let t=await this.db.query.subjectViews.findFirst({where:{id:e}});return t?this.toDomain(t):null}async update(e,t){let r=await this.get(e);if(!r)return null;let o=t.queryTemplate!==void 0?t.queryTemplate:t.query!==void 0?void 0:r.queryTemplate;return await this.db.update(ke).set({name:t.name??r.name,subjectType:t.subjectType??r.subjectType,workflowId:t.workflowId??r.workflowId,query:t.query??r.query,description:t.description!==void 0?t.description??null:r.description??null,queryTemplate:o??null,providerInstanceId:t.providerInstanceId??r.providerInstanceId}).where(Xo(ke.id,e)),this.get(e)}async list(e={}){let t=e.subjectType?await this.db.query.subjectViews.findMany({where:{subjectType:e.subjectType}}):await this.db.query.subjectViews.findMany();return this.sortViews(t.map(r=>this.toDomain(r)))}async reorder(e){let t=[];for(let o of e){let i=await this.get(o);if(!i)return[];t.push(i)}let r=t[0].subjectType;if(!t.every(o=>o.subjectType===r))return[];for(let o=0;o<e.length;o+=1)await this.db.update(ke).set({order:o}).where(Xo(ke.id,e[o]));return this.list({subjectType:r})}async delete(e){return await this.get(e)?(await this.db.delete(ke).where(Xo(ke.id,e)),!0):!1}async nextOrder(e){let t=await this.db.query.subjectViews.findMany({where:{subjectType:e}});return t.length===0?0:Math.max(...t.map(r=>r.order))+1}sortViews(e){return[...e].sort((t,r)=>{let o=ma.indexOf(t.subjectType)-ma.indexOf(r.subjectType);return o!==0?o:t.order-r.order})}toDomain(e){return{id:e.id,name:e.name,subjectType:e.subjectType,workflowId:e.workflowId,providerInstanceId:e.providerInstanceId,query:e.query,order:e.order,...e.description!=null?{description:e.description}:{},...e.queryTemplate!=null?{queryTemplate:e.queryTemplate}:{}}}};ue=Dp([Fp(),Bp("design:paramtypes",[Object])],ue)});import{Injectable as Lp}from"@nestjs/common";import{and as Up,desc as Mp,eq as wn,inArray as Wp}from"drizzle-orm";import{randomUUID as Hp}from"node:crypto";function Gp(n){return n?n.mode==="single"?[n.subject]:n.subjects:[]}function Kp(n){if(n.length!==0)return n.length===1?{mode:"single",subject:n[0]}:{mode:"collection",subjects:n}}function ga(n,e,t=null,r=null){let o=[];for(let i of e)if(o.push({id:i.id,jobId:n,stepDefinitionId:i.stepDefinitionId,type:i.type,status:i.status,startedAt:i.startedAt??null,completedAt:i.completedAt??null,output:i.output??null,error:i.error??null,failureDetails:i.failureDetails??null,childJobIds:i.childJobIds??null,parentStepExecutionId:t,iterationIndex:r}),i.iterations)for(let s of i.iterations)o.push(...ga(n,s.stepExecutions,i.id,s.index));return o}function Vp(n){let e=new Map;for(let o of n){let i=o.parentStepExecutionId,s=e.get(i)??[];s.push(o),e.set(i,s)}let t=o=>{let i=e.get(o)??[];if(i.length===0)return;let s=new Map;for(let a of i){if(a.iterationIndex==null)continue;let u=s.get(a.iterationIndex)??[];u.push(a),s.set(a.iterationIndex,u)}if(s.size!==0)return[...s.entries()].sort(([a],[u])=>a-u).map(([a,u])=>{let c=u.map(d=>ha(d,t(d.id)));return{index:a,stepExecutions:c,startedAt:Qp(c),...Xp(c)?{completedAt:zp(c)}:{}}})};return(e.get(null)??[]).filter(o=>o.iterationIndex==null).map(o=>ha(o,t(o.id)))}function ha(n,e){return{id:n.id,stepDefinitionId:n.stepDefinitionId,type:n.type,status:n.status,...n.startedAt!=null?{startedAt:n.startedAt}:{},...n.completedAt!=null?{completedAt:n.completedAt}:{},...n.output!==null&&n.output!==void 0?{output:n.output}:{},...n.error!=null?{error:n.error}:{},...n.failureDetails!=null?{failureDetails:n.failureDetails}:{},...n.childJobIds!=null?{childJobIds:n.childJobIds}:{},...e&&e.length>0?{iterations:e}:{}}}function Qp(n){let e=n.map(t=>t.startedAt).filter(t=>t!=null);return e.length===0?"":e.reduce((t,r)=>t<r?t:r)}function zp(n){return n.map(t=>t.completedAt).filter(t=>t!=null).reduce((t,r)=>t>r?t:r)}function Xp(n){return n.length>0&&n.every(e=>e.completedAt!=null)}function Yp(n){return n==="completed"||n==="failed"||n==="cancelled"}var Np,Jp,X,bn=l(()=>{"use strict";un();Jo();Lo();Np=function(n,e,t,r){var o=arguments.length,i=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Jp=function(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)},X=class{db;sqlite;constructor(e,t){this.db=e,this.sqlite=t}async create(e){return await this.withoutForeignKeys(async()=>{await this.db.insert(M).values(this.jobToRow(e)),await this.replaceSubjects(e.id,e.subjectContext),await this.replaceStepExecutions(e.id,e.stepHistory)}),await this.get(e.id)}async get(e){let t=await this.db.query.jobs.findFirst({where:{id:e},with:{subjects:!0,stepExecutions:!0}});return t?this.toDomain(t,t.subjects,t.stepExecutions):null}async update(e,t){let r=await this.get(e);if(!r)return null;let o={...r,...t,id:e,context:t.context??r.context,stepHistory:t.stepHistory??r.stepHistory,updatedAt:t.updatedAt??new Date().toISOString()};return await this.withoutForeignKeys(async()=>{await this.db.update(M).set({workflowId:o.workflowId,status:o.status,selection:o.selection??null,batchId:o.batchId??null,parentJobId:o.parentJobId??null,parentStepExecutionId:o.parentStepExecutionId??null,fanOutIndex:o.fanOutIndex??null,retryOf:o.retryOf??null,workflowSnapshot:o.workflowSnapshot??null,context:o.context,worktreePath:o.worktreePath??null,branch:o.branch??null,worktreeDeletedAt:o.worktreeDeletedAt??null,currentStepId:o.currentStepId??null,currentStepExecutionId:o.currentStepExecutionId??null,createdAt:o.createdAt,updatedAt:o.updatedAt,completedAt:o.completedAt??null}).where(wn(M.id,e)),t.subjectContext!==void 0&&await this.replaceSubjects(e,t.subjectContext),t.stepHistory!==void 0&&await this.replaceStepExecutions(e,t.stepHistory)}),this.get(e)}async list(e={}){let t={};e.workflowId!==void 0&&(t.workflowId=e.workflowId),e.status!==void 0&&(t.status=e.status),e.batchId!==void 0&&(t.batchId=e.batchId),e.parentJobId!==void 0&&(t.parentJobId=e.parentJobId),e.parentStepExecutionId!==void 0&&(t.parentStepExecutionId=e.parentStepExecutionId);let o=(Object.keys(t).length>0?await this.db.query.jobs.findMany({where:t,with:{subjects:!0,stepExecutions:!0}}):await this.db.query.jobs.findMany({with:{subjects:!0,stepExecutions:!0}})).map(s=>this.toDomain(s,s.subjects,s.stepExecutions)),i=e.topLevelOnly?o.filter(s=>s.batchId==null&&s.parentJobId==null):o;return e.liveWorktree&&(i=i.filter(s=>s.worktreePath!=null&&s.worktreeDeletedAt==null)),e.terminal===void 0?i:i.filter(s=>Yp(s.status)===e.terminal)}async latestBySubject(e,t){let r={};for(let c of t)r[c]=null;if(t.length===0)return r;let o=await this.db.select({subjectId:Ce.subjectId,jobId:M.id,createdAt:M.createdAt}).from(Ce).innerJoin(M,wn(Ce.jobId,M.id)).where(Up(wn(M.workflowId,e),Wp(Ce.subjectId,t))).orderBy(Mp(M.createdAt)),i=new Map;for(let c of o)i.has(c.subjectId)||i.set(c.subjectId,c.jobId);let s=[...new Set(i.values())],a=await Promise.all(s.map(c=>this.get(c))),u=new Map(a.filter(c=>c!=null).map(c=>[c.id,c]));for(let[c,d]of i)r[c]=u.get(d)??null;return r}async withoutForeignKeys(e){if(!this.sqlite){await e();return}try{this.sqlite.exec("PRAGMA foreign_keys = OFF"),await e()}finally{this.sqlite.exec("PRAGMA foreign_keys = ON")}}jobToRow(e){return{id:e.id,workflowId:e.workflowId,status:e.status,selection:e.selection??null,batchId:e.batchId??null,parentJobId:e.parentJobId??null,parentStepExecutionId:e.parentStepExecutionId??null,fanOutIndex:e.fanOutIndex??null,retryOf:e.retryOf??null,workflowSnapshot:e.workflowSnapshot??null,context:e.context,worktreePath:e.worktreePath??null,branch:e.branch??null,worktreeDeletedAt:e.worktreeDeletedAt??null,currentStepId:e.currentStepId??null,currentStepExecutionId:e.currentStepExecutionId??null,createdAt:e.createdAt,updatedAt:e.updatedAt,completedAt:e.completedAt??null}}async replaceSubjects(e,t){await this.db.delete(Ce).where(wn(Ce.jobId,e));let r=Gp(t);r.length!==0&&await this.db.insert(Ce).values(r.map(o=>({id:Hp(),jobId:e,subjectType:o.subjectType,subjectId:o.id,snapshot:o})))}async replaceStepExecutions(e,t){await this.db.delete(wt).where(wn(wt.jobId,e));let r=ga(e,t);r.length!==0&&await this.db.insert(wt).values(r)}toDomain(e,t,r){let o=Kp(t.map(s=>s.snapshot)),i=Vp(r);return{id:e.id,workflowId:e.workflowId,status:e.status,...o?{subjectContext:o}:{},...e.selection!=null?{selection:e.selection}:{},...e.batchId!=null?{batchId:e.batchId}:{},...e.parentJobId!=null?{parentJobId:e.parentJobId}:{},...e.parentStepExecutionId!=null?{parentStepExecutionId:e.parentStepExecutionId}:{},...e.fanOutIndex!=null?{fanOutIndex:e.fanOutIndex}:{},...e.retryOf!=null?{retryOf:e.retryOf}:{},...e.workflowSnapshot!=null?{workflowSnapshot:e.workflowSnapshot}:{},context:e.context,...e.worktreePath!=null?{worktreePath:e.worktreePath}:{},...e.branch!=null?{branch:e.branch}:{},...e.worktreeDeletedAt!=null?{worktreeDeletedAt:e.worktreeDeletedAt}:{},...e.currentStepId!=null?{currentStepId:e.currentStepId}:{},...e.currentStepExecutionId!=null?{currentStepExecutionId:e.currentStepExecutionId}:{},stepHistory:i,createdAt:e.createdAt,updatedAt:e.updatedAt,...e.completedAt!=null?{completedAt:e.completedAt}:{}}}};X=Np([Lp(),Jp("design:paramtypes",[Object,Function])],X)});import{Injectable as tf}from"@nestjs/common";import{eq as nf}from"drizzle-orm";var Zp,ef,le,Hn=l(()=>{"use strict";Ln();Zp=function(n,e,t,r){var o=arguments.length,i=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},ef=function(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)},le=class{db;constructor(e){this.db=e}async create(e){return await this.db.insert(et).values({id:e.id,workflowId:e.workflowId,selection:e.selection,resolvedSubjects:e.resolvedSubjects,status:e.status,triggeredBy:e.triggeredBy,scheduleId:e.scheduleId??null,notificationOverride:e.notificationOverride??null,notificationSent:e.notificationSent,createdAt:e.createdAt,completedAt:e.completedAt??null}),await this.get(e.id)}async get(e){let t=await this.db.query.jobBatches.findFirst({where:{id:e},with:{jobs:!0}});return t?this.toDomain(t,t.jobs.map(r=>r.id)):null}async update(e,t){let r=await this.get(e);return r?(await this.db.update(et).set({workflowId:t.workflowId??r.workflowId,selection:t.selection??r.selection,resolvedSubjects:t.resolvedSubjects??r.resolvedSubjects,status:t.status??r.status,triggeredBy:t.triggeredBy??r.triggeredBy,scheduleId:t.scheduleId!==void 0?t.scheduleId??null:r.scheduleId??null,notificationOverride:t.notificationOverride!==void 0?t.notificationOverride??null:r.notificationOverride??null,notificationSent:t.notificationSent??r.notificationSent,createdAt:t.createdAt??r.createdAt,completedAt:t.completedAt!==void 0?t.completedAt??null:r.completedAt??null}).where(nf(et.id,e)),this.get(e)):null}async list(e={}){return(e.workflowId?await this.db.query.jobBatches.findMany({where:{workflowId:e.workflowId},with:{jobs:!0}}):await this.db.query.jobBatches.findMany({with:{jobs:!0}})).map(r=>this.toDomain(r,r.jobs.map(o=>o.id)))}toDomain(e,t){return{id:e.id,workflowId:e.workflowId,selection:e.selection,resolvedSubjects:e.resolvedSubjects,jobIds:t,status:e.status,triggeredBy:e.triggeredBy,...e.scheduleId!=null?{scheduleId:e.scheduleId}:{},...e.notificationOverride!=null?{notificationOverride:e.notificationOverride}:{},notificationSent:e.notificationSent,createdAt:e.createdAt,...e.completedAt!=null?{completedAt:e.completedAt}:{}}}};le=Zp([tf(),ef("design:paramtypes",[Object])],le)});import{Injectable as sf}from"@nestjs/common";import{eq as ya}from"drizzle-orm";var rf,of,Ne,Yo=l(()=>{"use strict";Uo();rf=function(n,e,t,r){var o=arguments.length,i=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},of=function(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)},Ne=class{db;constructor(e){this.db=e}async create(e){return await this.db.insert(nt).values({id:e.id,viewId:e.viewId,triggerType:e.trigger.type,cadence:e.trigger.cadence,notificationOverride:e.notificationOverride??null,missedFirePolicy:e.missedFirePolicy,enabled:e.enabled,lastFiredAt:e.lastFiredAt??null,createdAt:e.createdAt}),await this.get(e.id)}async get(e){let t=await this.db.query.schedules.findFirst({where:{id:e}});return t?this.toDomain(t):null}async update(e,t){let r=await this.get(e);if(!r)return null;let o=t.trigger??r.trigger;return await this.db.update(nt).set({viewId:t.viewId??r.viewId,triggerType:o.type,cadence:o.cadence,notificationOverride:t.notificationOverride!==void 0?t.notificationOverride??null:r.notificationOverride??null,missedFirePolicy:t.missedFirePolicy??r.missedFirePolicy,enabled:t.enabled??r.enabled,lastFiredAt:t.lastFiredAt!==void 0?t.lastFiredAt??null:r.lastFiredAt??null,createdAt:t.createdAt??r.createdAt}).where(ya(nt.id,e)),this.get(e)}async list(e={}){return(e.enabled!==void 0?await this.db.query.schedules.findMany({where:{enabled:e.enabled}}):await this.db.query.schedules.findMany()).map(r=>this.toDomain(r))}async delete(e){return await this.get(e)?(await this.db.delete(nt).where(ya(nt.id,e)),!0):!1}async findDue(e){return(await this.list({enabled:!0})).filter(r=>r.lastFiredAt==null||r.lastFiredAt<e)}toDomain(e){return{id:e.id,viewId:e.viewId,trigger:{type:"cron",cadence:e.cadence},...e.notificationOverride!=null?{notificationOverride:e.notificationOverride}:{},missedFirePolicy:e.missedFirePolicy,enabled:e.enabled,...e.lastFiredAt!=null?{lastFiredAt:e.lastFiredAt}:{},createdAt:e.createdAt}}};Ne=rf([sf(),of("design:paramtypes",[Object])],Ne)});import{Injectable as uf}from"@nestjs/common";import{eq as Zo}from"drizzle-orm";var af,cf,Je,ei=l(()=>{"use strict";Mo();af=function(n,e,t,r){var o=arguments.length,i=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},cf=function(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)},Je=class{db;constructor(e){this.db=e}async create(e){let t=await this.nextOrder();return await this.db.insert(Te).values({id:e.id,name:e.name,workflowId:e.workflowId,inputValues:e.inputValues,lastJobId:e.lastJobId??null,order:t}),await this.get(e.id)}async get(e){let t=await this.db.query.workflowShortcuts.findFirst({where:{id:e}});return t?this.toDomain(t):null}async update(e,t){let r=await this.get(e);return r?(await this.db.update(Te).set({name:t.name??r.name,workflowId:t.workflowId??r.workflowId,inputValues:t.inputValues??r.inputValues,lastJobId:t.lastJobId!==void 0?t.lastJobId??null:r.lastJobId??null}).where(Zo(Te.id,e)),this.get(e)):null}async list(){return(await this.db.query.workflowShortcuts.findMany()).map(t=>this.toDomain(t)).sort((t,r)=>t.order-r.order)}async reorder(e){let t=[];for(let r of e){let o=await this.get(r);if(!o)return[];t.push(o)}for(let r=0;r<e.length;r+=1)await this.db.update(Te).set({order:r}).where(Zo(Te.id,e[r]));return this.list()}async delete(e){return await this.get(e)?(await this.db.delete(Te).where(Zo(Te.id,e)),!0):!1}async nextOrder(){let e=await this.db.query.workflowShortcuts.findMany();return e.length===0?0:Math.max(...e.map(t=>t.order))+1}toDomain(e){return{id:e.id,name:e.name,workflowId:e.workflowId,inputValues:e.inputValues,order:e.order,...e.lastJobId!=null?{lastJobId:e.lastJobId}:{}}}};Je=af([uf(),cf("design:paramtypes",[Object])],Je)});import{Injectable as pf}from"@nestjs/common";import{eq as wa}from"drizzle-orm";var lf,df,de,Gn=l(()=>{"use strict";Wo();lf=function(n,e,t,r){var o=arguments.length,i=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},df=function(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)},de=class{db;constructor(e){this.db=e}async create(e){return await this.db.insert(rt).values({id:e.id,name:e.name,description:e.description??null,tier:e.tier,path:e.path}),await this.get(e.id)}async get(e){let t=await this.db.query.contextFiles.findFirst({where:{id:e}});return t?this.toDomain(t):null}async update(e,t){let r=await this.get(e);return r?(await this.db.update(rt).set({name:t.name??r.name,description:t.description!==void 0?t.description??null:r.description??null,tier:t.tier??r.tier,path:t.path??r.path}).where(wa(rt.id,e)),this.get(e)):null}async list(){return(await this.db.query.contextFiles.findMany()).map(t=>this.toDomain(t)).sort((t,r)=>t.name.localeCompare(r.name))}async delete(e){return await this.get(e)?(await this.db.delete(rt).where(wa(rt.id,e)),!0):!1}toDomain(e){return{id:e.id,name:e.name,tier:e.tier,path:e.path,...e.description!=null&&e.description!==""?{description:e.description}:{}}}};de=lf([pf(),df("design:paramtypes",[Object])],de)});import{Injectable as hf}from"@nestjs/common";import{eq as ba}from"drizzle-orm";var ff,mf,pe,Kn=l(()=>{"use strict";Ho();ff=function(n,e,t,r){var o=arguments.length,i=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},mf=function(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)},pe=class{db;constructor(e){this.db=e}async create(e){return await this.db.insert(ot).values({id:e.id,name:e.name,localPath:e.localPath,worktreeBasePath:e.worktreeBasePath??null,defaultBranch:e.defaultBranch??null}),await this.get(e.id)}async get(e){let t=await this.db.query.localRepositories.findFirst({where:{id:e}});return t?this.toDomain(t):null}async findByLocalPath(e){let r=(await this.db.query.localRepositories.findMany()).find(o=>o.localPath===e);return r?this.toDomain(r):null}async update(e,t){let r=await this.get(e);return r?(await this.db.update(ot).set({name:t.name??r.name,localPath:t.localPath??r.localPath,worktreeBasePath:t.worktreeBasePath!==void 0?t.worktreeBasePath??null:r.worktreeBasePath??null,defaultBranch:t.defaultBranch!==void 0?t.defaultBranch??null:r.defaultBranch??null}).where(ba(ot.id,e)),this.get(e)):null}async list(){return(await this.db.query.localRepositories.findMany()).map(t=>this.toDomain(t)).sort((t,r)=>t.name.localeCompare(r.name))}async delete(e){return await this.get(e)?(await this.db.delete(ot).where(ba(ot.id,e)),!0):!1}toDomain(e){return{id:e.id,name:e.name,localPath:e.localPath,...e.worktreeBasePath!=null&&e.worktreeBasePath!==""?{worktreeBasePath:e.worktreeBasePath}:{},...e.defaultBranch!=null&&e.defaultBranch!==""?{defaultBranch:e.defaultBranch}:{}}}};pe=ff([hf(),mf("design:paramtypes",[Object])],pe)});import{z as A}from"zod";var Sa,xa,va,ti,Vn,ja,ni=l(()=>{"use strict";Sa=A.object({name:A.string().min(1),label:A.string().min(1),type:A.enum(["string","select"]),options:A.array(A.string()).optional(),required:A.boolean()}),xa=A.object({id:A.string().min(1),label:A.string().min(1),params:A.array(Sa)}),va=A.object({actionId:A.string().min(1),label:A.string().min(1),params:A.array(Sa)}),ti=A.object({templateId:A.string().min(1),params:A.record(A.string(),A.unknown())}),Vn=A.object({params:A.record(A.string(),A.unknown())}),ja=A.object({query:A.record(A.string(),A.unknown())})});import{z as ee}from"zod";var oe,Qn,zn,Xn,Yn,Zn=l(()=>{"use strict";ni();oe=ee.enum(["ticket","pull_request","documentation"]),Qn=ee.object({id:ee.string().min(1),name:ee.string().min(1),subjectType:oe,workflowId:ee.string().min(1),providerInstanceId:ee.string().min(1),query:ee.record(ee.string(),ee.unknown()),description:ee.string().optional(),queryTemplate:ti.optional(),order:ee.number().int().nonnegative()}),zn=Qn.omit({order:!0}),Xn=Qn.partial().omit({id:!0,order:!0}).extend({queryTemplate:ti.nullable().optional()}),Yn=ee.object({viewIds:ee.array(ee.string().min(1)).min(1)})});var _a=l(()=>{"use strict";Zn()});var Ia=l(()=>{"use strict";ni()});function ri(n){let e=n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"");return e.length>0?e:"step"}function Ea(n,e){let t=e instanceof Set?e:new Set(e),r=ri(n);if(!t.has(r))return r;let o=2;for(;t.has(`${r}-${o}`);)o+=1;return`${r}-${o}`}function Pa(n,e){for(let t of n)t.id&&e.push(t.id),t.type==="loop"&&Array.isArray(t.steps)&&Pa(t.steps,e)}function Ra(n){let e=[];Pa(n,e);let t=new Map;for(let r of e)t.set(r,(t.get(r)??0)+1);return[...t.entries()].filter(([,r])=>r>1).map(([r])=>r)}function ka(n){let e=new Set,t=r=>{for(let o of r)o.id&&e.add(o.id),o.type==="loop"&&Array.isArray(o.steps)&&t(o.steps)};return t(n),e}var oi=l(()=>{"use strict"});import{z as f}from"zod";function Sf(n){return!!(n.path?.trim()||n.pattern?.trim())}function xf(n,e){let t=e.sourceStepIds??[];if(t.length===0)return`comment_review step '${e.id}' requires sourceStepIds`;let r=ii(n),o=r.findIndex(s=>s.id===e.id),i=new Map((o>=0?r.slice(0,o):r).map(s=>[s.id,s]));for(let s of t){let a=i.get(s);if(!a||a.type!=="agent"||a.outputFormat!=="comment_suggestions")return`comment_review step '${e.id}' source '${s}' is not a prior comment_suggestions agent step`}return null}function ii(n){let e=[];for(let t of n)e.push(t),t.type==="loop"&&e.push(...ii(t.steps));return e}var gf,Sn,yf,Le,Aa,Ca,Ta,Oa,$a,qa,Da,Ba,wf,bf,Fa,er,Na,xn,vf,jf,_f,If,Ef,Pf,Rf,kf,Ja,it,La=l(()=>{"use strict";Zn();oi();gf=f.enum(["on_fail","on_complete","on_needs_input"]),Sn=f.object({triggers:f.array(gf),messageTemplate:f.string().optional()}),yf=f.object({name:f.string().min(1),label:f.string().min(1),type:f.enum(["string","number","boolean","select","localRepository"]),options:f.array(f.string()).optional(),required:f.boolean(),defaultValue:f.unknown().optional()}),Le=f.string().min(1),Aa=f.object({type:f.literal("agent"),id:f.string().min(1),name:Le,objective:f.string().min(1),contextFileIds:f.array(f.string().min(1)).optional(),outputFormat:f.enum(["questionnaire","confirmation","comment_suggestions","free_text"]),agentInstanceId:f.string().min(1).optional()}),Ca=f.object({type:f.literal("interaction"),id:f.string().min(1),name:Le,interaction:f.union([f.literal("questionnaire"),f.literal("confirmation"),f.literal("conversation"),f.literal("comment_review")]),notify:f.boolean().optional(),sourceStepIds:f.array(f.string().min(1)).optional()}),Ta=f.object({type:f.literal("shell"),id:f.string().min(1),name:Le,command:f.string().min(1)}),Oa=f.object({type:f.literal("git"),id:f.string().min(1),name:Le,operation:f.enum(["create_worktree","checkout","create_branch","commit","push"]),params:f.record(f.string(),f.unknown())}),$a=f.object({type:f.literal("provider_action"),id:f.string().min(1),name:Le,action:f.enum(["get_subject","get_comments","post_comment","update_status","get_content"]),params:f.record(f.string(),f.unknown()).optional(),extendedAction:f.object({providerId:f.string().min(1),actionId:f.string().min(1),params:f.record(f.string(),f.unknown()).optional()}).optional(),target:f.object({subjectType:oe,source:f.string().min(1),subjectId:f.string().min(1)}).optional()}),qa=f.object({type:f.literal("sub_workflow"),id:f.string().min(1),name:Le,workflowId:f.string().min(1),forEach:f.literal("selection")}),Da=f.discriminatedUnion("type",[f.object({type:f.literal("field_empty"),stepId:f.string().min(1),field:f.string().min(1)}),f.object({type:f.literal("field_equals"),stepId:f.string().min(1),field:f.string().min(1),value:f.unknown()})]),Ba=f.discriminatedUnion("action",[f.object({action:f.literal("fail")}),f.object({action:f.literal("continue")}),f.object({action:f.literal("ask_human")})]),wf=f.object({type:f.literal("loop"),id:f.string().min(1),name:Le,steps:f.array(f.lazy(()=>er)),until:Da,maxIterations:f.number().int().nonnegative(),onMaxIterations:Ba}),bf=f.enum(["fail","empty","ask_human"]),Fa=f.object({type:f.literal("extract"),id:f.string().min(1),name:Le,source:f.string(),path:f.string().optional(),pattern:f.string().optional(),onNoMatch:bf}),er=f.lazy(()=>f.discriminatedUnion("type",[Oa,$a,Ta,Aa,Ca,qa,wf,Fa])),Na=f.object({id:f.string().min(1),name:f.string().min(1),description:f.string().optional(),appliesTo:f.union([oe,f.array(oe),f.literal("none")]),subjectHandling:f.enum(["per-subject","collection"]),inputSchema:f.array(yf),steps:f.array(er),notificationPolicy:Sn}),xn=Na.superRefine((n,e)=>{let t=Ra(n.steps);t.length>0&&e.addIssue({code:"custom",path:["steps"],message:`Duplicate step id(s): ${t.join(", ")}`});for(let r of ii(n.steps))if(r.type==="extract"&&!Sf(r)&&e.addIssue({code:"custom",path:["steps"],message:`Extract step '${r.id}' must set at least one of path or pattern`}),r.type==="interaction"&&r.interaction==="comment_review"){let o=xf(n.steps,r);o&&e.addIssue({code:"custom",path:["steps"],message:o})}});vf=Aa.extend({id:f.string().min(1).optional()}),jf=Ca.extend({id:f.string().min(1).optional()}),_f=Ta.extend({id:f.string().min(1).optional()}),If=Oa.extend({id:f.string().min(1).optional()}),Ef=$a.extend({id:f.string().min(1).optional()}),Pf=qa.extend({id:f.string().min(1).optional()}),Rf=f.object({type:f.literal("loop"),id:f.string().min(1).optional(),name:Le,steps:f.array(f.lazy(()=>Ja)),until:Da,maxIterations:f.number().int().nonnegative(),onMaxIterations:Ba}),kf=Fa.extend({id:f.string().min(1).optional()}),Ja=f.lazy(()=>f.discriminatedUnion("type",[If,Ef,_f,vf,jf,Pf,Rf,kf])),it=Na.omit({id:!0,steps:!0}).extend({id:f.string().min(1).optional(),steps:f.array(Ja)})});function si(n){return n==="none"?[]:Array.isArray(n)?n:[n]}function Ua(n,e){return si(n).includes(e)}var ai=l(()=>{"use strict"});var Ma=l(()=>{"use strict"});function Wa(n,e="none"){switch(n.type){case"agent":return Cf(n.outputFormat);case"shell":return{isScalar:!1,fields:["exitCode","stdout","stderr"]};case"git":return Of(n);case"provider_action":return Tf(n,e);case"interaction":return n.interaction==="comment_review"?{isScalar:!1,fields:["finalComments"]}:{isScalar:!1,opaque:!0};case"sub_workflow":return{isScalar:!1,fields:["fanOutIndex","jobId","output"],isArray:!0};case"loop":return{isScalar:!1};case"extract":return{isScalar:!0}}}function Ha(n,e){let t=[];return Ga(n,e,t,!1)?t:[]}function Cf(n){switch(n){case"free_text":return{isScalar:!0};case"questionnaire":return{isScalar:!1,fields:["questions"]};case"confirmation":return{isScalar:!1,fields:["approved"]};case"comment_suggestions":return{isScalar:!1,fields:["suggestions"],isArray:!1}}}function Tf(n,e){if(n.extendedAction)return{isScalar:!1,opaque:!0};switch(n.action){case"get_subject":{let t=n.target?.subjectType;if(t)return{isScalar:!1,fields:vn[t]};let r=si(e),o=[],i=new Set;for(let s of r)for(let a of vn[s])i.has(a)||(i.add(a),o.push(a));return{isScalar:!1,fields:o,...r.length>1?{fieldsDependOnSubjectType:!0}:{}}}case"get_comments":return{isScalar:!1,fields:[...Af],isArray:!0};case"get_content":return{isScalar:!0};case"post_comment":case"update_status":return{isScalar:!1,fields:[]}}}function Of(n){switch(n.operation){case"create_worktree":return{isScalar:!1,fields:["worktreePath","branch"]};case"commit":return{isScalar:!1,fields:["sha"]};case"checkout":case"create_branch":case"push":return{isScalar:!1,fields:[]}}}function $f(n,e){if(n===e)return!0;let t="_key"in n?n._key:void 0,r="_key"in e?e._key:void 0;return typeof t=="string"&&t.length>0&&t===r}function Ga(n,e,t,r){for(let o of n){if($f(o,e))return!0;if(o.type==="loop"&&Array.isArray(o.steps)){if(Ga(o.steps,e,t,!0))return!0}else t.push({step:o,inLoop:r})}return!1}var vn,Af,ci=l(()=>{"use strict";ai();vn={ticket:["id","source","title","description","status","assignee","url"],pull_request:["id","source","title","description","sourceBranch","targetBranch","author","url"],documentation:["id","source","title","url"]},Af=["id","subjectId","author","body","createdAt"]});function Ka(n){if(!n||typeof n!="object"||Array.isArray(n))return null;let e=n;return typeof e.id!="string"||e.id.trim()===""||typeof e.file!="string"||e.file.trim()===""||typeof e.line!="number"||!Number.isInteger(e.line)||typeof e.body!="string"?null:{id:e.id.trim(),file:e.file.trim(),line:e.line,body:e.body}}function qf(n){if(Array.isArray(n)){let r=[];for(let o of n){let i=Ka(o);if(!i)return null;r.push(i)}return r}if(!n||typeof n!="object")return null;let e=n.suggestions;if(!Array.isArray(e))return null;let t=[];for(let r of e){let o=Ka(r);if(!o)return null;t.push(o)}return t}function Df(n){let e=[];for(let t of n)for(let r of t.suggestions)e.push({...r,id:`${t.stepId}-${r.id}`});return e}function Bf(n,e){return Ha(n,e).map(t=>t.step).filter(t=>t.type==="agent"&&"outputFormat"in t&&t.outputFormat==="comment_suggestions")}function Va(n,e,t){if(n.interaction!=="comment_review")throw new Error(`Step '${n.id}' is not a comment_review interaction`);let r=n.sourceStepIds??[];if(r.length===0)throw new Error(`comment_review step '${n.id}' requires sourceStepIds`);let o=new Set(Bf(e,n).map(s=>s.id)),i=[];for(let s of r){if(!o.has(s))throw new Error(`comment_review step '${n.id}' source '${s}' is not a prior comment_suggestions agent step`);if(!Object.prototype.hasOwnProperty.call(t,s))throw new Error(`comment_review step '${n.id}' source '${s}' has no stored output`);let a=qf(t[s]);if(!a)throw new Error(`comment_review step '${n.id}' source '${s}' output is not comment_suggestions-shaped`);i.push({stepId:s,suggestions:a})}return Df(i)}function Qa(n){if(!n||typeof n!="object"||Array.isArray(n))return null;let e=n.finalComments;if(!Array.isArray(e))return null;let t=[];for(let r of e){if(!r||typeof r!="object"||Array.isArray(r))return null;let o=r;if(typeof o.file!="string"||o.file.trim()===""||typeof o.line!="number"||!Number.isInteger(o.line)||typeof o.body!="string")return null;t.push({file:o.file.trim(),line:o.line,body:o.body})}return{finalComments:t}}var za=l(()=>{"use strict";ci()});var Xa=l(()=>{"use strict";La();oi();ai();Ma();ci();za()});import{z as xt}from"zod";var Ff,tr,nr,rr,Ya=l(()=>{"use strict";Ff=xt.enum(["user","organization","project"]),tr=xt.object({id:xt.string().min(1),name:xt.string().min(1),description:xt.string().optional(),tier:Ff,path:xt.string().min(1)}),nr=tr.omit({id:!0}).extend({id:xt.string().min(1).optional()}),rr=tr.partial().omit({id:!0})});var Za=l(()=>{"use strict";Ya()});import{z as vt}from"zod";var or,ir,sr,ec=l(()=>{"use strict";or=vt.object({id:vt.string().min(1),name:vt.string().min(1),localPath:vt.string().min(1),worktreeBasePath:vt.string().min(1).optional(),defaultBranch:vt.string().min(1).optional()}),ir=or.omit({id:!0}).extend({id:vt.string().min(1).optional()}),sr=or.partial().omit({id:!0})});var tc=l(()=>{"use strict";ec()});var nc=l(()=>{"use strict"});function Nf(n){if(!n||typeof n!="object"||Array.isArray(n))return null;let e=n;return typeof e.file!="string"||e.file.trim()===""||typeof e.line!="number"||!Number.isInteger(e.line)||typeof e.body!="string"?null:{file:e.file.trim(),line:e.line,body:e.body}}function rc(n){let e=n;if(typeof e=="string"){let r=e.trim();if(!r)return[];try{e=JSON.parse(r)}catch{return null}}if(!Array.isArray(e))return null;let t=[];for(let r of e){let o=Nf(r);if(!o)return null;t.push(o)}return t}function oc(n,e){if(!n||typeof n!="object"||!e?.failureDetails)return!1;let t=n;if(t.type!=="provider_action"||t.action!=="post_comment")return!1;let r=t.params;return r!=null&&typeof r=="object"&&!Array.isArray(r)&&Object.prototype.hasOwnProperty.call(r,"comments")}var ic=l(()=>{"use strict"});var sc=l(()=>{"use strict";nc();ic()});var ac=l(()=>{"use strict"});var cc=l(()=>{"use strict";ac()});import{z as te}from"zod";var Jt,uc=l(()=>{"use strict";Jt=te.object({id:te.string().min(1),viewId:te.string().min(1),trigger:te.object({type:te.literal("cron"),cadence:te.string().min(1)}),notificationOverride:te.object({triggers:te.array(te.enum(["on_fail","on_complete","on_needs_input"])),messageTemplate:te.string().optional()}).optional(),missedFirePolicy:te.enum(["skip","catch_up"]),enabled:te.boolean(),lastFiredAt:te.string().optional(),createdAt:te.string()})});var lc=l(()=>{"use strict";uc()});import{z as fe}from"zod";var ar,cr,ur,lr,dc=l(()=>{"use strict";ar=fe.object({id:fe.string().min(1),name:fe.string().min(1),workflowId:fe.string().min(1),inputValues:fe.record(fe.string(),fe.unknown()),lastJobId:fe.string().min(1).optional(),order:fe.number().int().nonnegative()}),cr=ar.omit({order:!0}),ur=ar.partial().omit({id:!0,order:!0}),lr=fe.object({shortcutIds:fe.array(fe.string().min(1)).min(1)})});var pc=l(()=>{"use strict";dc()});import{z as x}from"zod";function jt(n){return n.kind==="subject"}function Oe(n){return n.kind==="agent"}function bc(n){return n.maxConcurrent??jn}var Jf,fc,mc,hc,jn,gc,dr,pr,fr,mr,hr,gr,yc,wc,Sc=l(()=>{"use strict";Zn();Jf=x.enum(["jira","bitbucket","github","confluence","manual"]),fc=x.enum(["claude","cursor"]),mc={id:x.string().min(1),displayName:x.string().min(1),config:x.record(x.string(),x.unknown()),secretKey:x.string().min(1),expiresOn:x.string().min(1).optional()},hc=x.object({...mc,kind:x.literal("subject"),type:Jf,subjectType:oe}),jn=2,gc=x.object({...mc,kind:x.literal("agent"),type:fc,maxConcurrent:x.number().int().min(1).optional()}),dr=x.discriminatedUnion("kind",[hc,gc]),pr=x.object({providerInstances:x.array(dr).default([]),defaultAgentInstanceId:x.string().min(1).optional()}),fr=x.object({providerInstances:x.array(dr).optional(),defaultAgentInstanceId:x.string().min(1).nullable().optional()}),mr=x.discriminatedUnion("kind",[hc.extend({defaultAgent:x.boolean().optional()}),gc.extend({defaultAgent:x.boolean().optional()})]),hr=x.object({displayName:x.string().min(1).optional(),config:x.record(x.string(),x.unknown()).optional(),secretKey:x.string().min(1).optional(),expiresOn:x.union([x.string().min(1),x.null()]).optional(),defaultAgent:x.boolean().optional(),maxConcurrent:x.number().int().min(1).optional()}),gr=x.object({type:fc,apiKey:x.string().min(1).optional(),instanceId:x.string().min(1).optional()}),yc=x.object({id:x.string().min(1),displayName:x.string().min(1)}),wc={providerInstances:[]}});var xc=l(()=>{"use strict";Sc()});var vc=l(()=>{"use strict"});function jc(n,e){switch(n){case"questionnaire":return ui(e);case"confirmation":return Lf(e);case"conversation":return Uf(e);case"comment_review":return Mf(e);default:return n}}function ui(n){if(typeof n=="string"&&n.trim())return[n.trim()];if(!n||typeof n!="object")return[];let e=n.questions;return Array.isArray(e)?e.map(t=>typeof t=="string"?t.trim():t&&typeof t=="object"&&"prompt"in t?String(t.prompt).trim():"").filter(Boolean):[]}function Lf(n){if(typeof n=="string"&&n.trim())return[n.trim()];if(!n||typeof n!="object")return[];let e=n;for(let t of["prompt","message","summary","question"]){let r=e[t];if(typeof r=="string"&&r.trim())return[r.trim()]}return"approved"in e&&!("questions"in e)?[]:ui(n)}function Uf(n){if(typeof n=="string"&&n.trim())return[n.trim()];if(!n||typeof n!="object")return[];let e=n;for(let t of["prompt","message","text"]){let r=e[t];if(typeof r=="string"&&r.trim())return[r.trim()]}return"suggestions"in e?[]:"questions"in e?ui(n):[]}function Mf(n){if(!n||typeof n!="object")return[];let e=Array.isArray(n)?n:n.suggestions;return Array.isArray(e)?e.map(t=>{if(!t||typeof t!="object")return"";let r=t;return typeof r.file!="string"||r.file.trim()===""||typeof r.line!="number"||!Number.isInteger(r.line)?"":`${r.file.trim()}:${r.line}`}).filter(Boolean):[]}var _c=l(()=>{"use strict"});var Ic=l(()=>{"use strict";vc();_c()});var C=l(()=>{"use strict";_a();Ia();Xa();Za();tc();sc();cc();lc();pc();xc();Ic()});import{Injectable as Gf}from"@nestjs/common";import{eq as Kf}from"drizzle-orm";function Vf(n,e){let t=e.providerInstances!==void 0?e.providerInstances:n.providerInstances,r=e.defaultAgentInstanceId===null?void 0:e.defaultAgentInstanceId!==void 0?e.defaultAgentInstanceId:n.defaultAgentInstanceId;return li({providerInstances:t,...r?{defaultAgentInstanceId:r}:{}})}function li(n){return{providerInstances:(n.providerInstances??wc.providerInstances).map(Qf),...n.defaultAgentInstanceId?{defaultAgentInstanceId:n.defaultAgentInstanceId}:{}}}function Qf(n){return!Oe(n)||n.maxConcurrent!=null?n:{...n,maxConcurrent:jn}}function Ec(n){return n.providerInstances!==void 0}var Wf,Hf,E,ye=l(()=>{"use strict";C();Go();Wf=function(n,e,t,r){var o=arguments.length,i=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Hf=function(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)},E=class{db;constructor(e){this.db=e}async get(){let e=await this.db.query.settings.findFirst({where:{id:mn}});return li(e?e.data:{})}async update(e){let t=Vf(await this.get(),e);return await this.db.query.settings.findFirst({where:{id:mn}})?await this.db.update(Nt).set({data:t}).where(Kf(Nt.id,mn)):await this.db.insert(Nt).values({id:mn,data:t}),t}async replaceProviderInstances(e){return this.update({providerInstances:e})}};E=Wf([Gf(),Hf("design:paramtypes",[Object])],E)});import{Module as Xf}from"@nestjs/common";var zf,Yf,$e,_n=l(()=>{"use strict";pa();St();Wn();bn();Hn();Yo();ei();Gn();Kn();ye();zf=function(n,e,t,r){var o=arguments.length,i=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Yf=[D,ue,X,le,Ne,Je,de,pe,E],$e=class{};$e=zf([Xf({providers:[Z,{provide:D,useFactory:n=>new D(n.getDb(),n.getSqlite()),inject:[Z]},{provide:ue,useFactory:n=>new ue(n.getDb()),inject:[Z]},{provide:X,useFactory:n=>new X(n.getDb(),n.getSqlite()),inject:[Z]},{provide:le,useFactory:n=>new le(n.getDb()),inject:[Z]},{provide:Ne,useFactory:n=>new Ne(n.getDb()),inject:[Z]},{provide:Je,useFactory:n=>new Je(n.getDb()),inject:[Z]},{provide:de,useFactory:n=>new de(n.getDb()),inject:[Z]},{provide:pe,useFactory:n=>new pe(n.getDb()),inject:[Z]},{provide:E,useFactory:n=>new E(n.getDb()),inject:[Z]}],exports:[Z,...Yf]})],$e)});import{Injectable as tm,Logger as nm,Inject as Rc}from"@nestjs/common";async function kc(n,e){let t=[];for(let r of e){let o=await n.get(r.secretKey);t.push({providerId:r.id,secretKey:r.secretKey,configured:typeof o=="string"&&o.length>0})}return t}async function rm(n,e,t){let r=await kc(n,e);for(let o of r)o.configured||t(`Provider instance '${o.providerId}' API key not configured (looked up as '${o.secretKey}'). GET /api/providers/status lists what's missing; store a key with: POST /api/secrets/${o.secretKey} or npm --workspace apps/engine run set-secret -- ${o.secretKey} <value>`)}var Zf,em,Pc,di,st,pi=l(()=>{"use strict";ye();Fe();Zf=function(n,e,t,r){var o=arguments.length,i=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},em=function(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)},Pc=function(n,e){return function(t,r){e(t,r,n)}};st=di=class{secrets;settings;logger=new nm(di.name);constructor(e,t){this.secrets=e,this.settings=t}async onModuleInit(){let e=await this.settings.get();await rm(this.secrets,e.providerInstances??[],t=>this.logger.warn(t))}async list(){let e=await this.settings.get();return kc(this.secrets,e.providerInstances??[])}};st=di=Zf([tm(),Pc(0,Rc(he)),Pc(1,Rc(E)),em("design:paramtypes",[Function,E])],st)});function yr(n,e=Bt(n)){let t=am[n]??n;return new Error(`${t} API key not configured \u2014 set '${e}' via the setup script`)}function Ac(n){let e=new Map;for(let r of n){let o=r.content.trim();if(!o)continue;let i=e.get(r.tier)??[];i.push(o),e.set(r.tier,i)}let t=[];for(let r of im){let o=e.get(r);o?.length&&t.push(`## ${om[r]}
12
12
  ${o.join(`
13
13
 
14
14
  `)}`)}return t.join(`
15
15
 
16
- `)}function hr(r){let e=[],t=ec(r.knowledge);return t&&e.push(t),e.push(`# Objective
17
- ${r.objective}`),e.push(`# Output format
18
- ${ff[r.outputFormat]}`),e.join(`
16
+ `)}function In(n){let e=[],t=Ac(n.knowledge);return t&&e.push(t),e.push(`# Objective
17
+ ${n.objective}`),e.push(`# Output format
18
+ ${sm[n.outputFormat]}`),e.join(`
19
19
 
20
- `)}function yr(r,e){return e==="free_text"?r:tc(r)}function tc(r){let e=[...r.matchAll(/```json\s*([\s\S]*?)```/gi)].map(o=>o[1].trim()),t=[...r.matchAll(/```\s*([\s\S]*?)```/g)].map(o=>o[1].trim()),n=[...e].reverse();n.length===0&&n.push(...[...t].reverse()),n.push(r.trim());for(let o of n)if(o)try{return JSON.parse(o)}catch{continue}throw new Error("No valid JSON block found in agent response")}var df,pf,ff,mf,un=l(()=>{"use strict";Oe();df={user:"User preferences",organization:"Organization guidelines",project:"Project context"},pf=["user","organization","project"],ff={questionnaire:'Respond with a single fenced JSON block matching this shape exactly: {"questions":[{"id":"<string>","prompt":"<string>"}]}. No other prose outside the fence.',confirmation:'Respond with a single fenced JSON block matching this shape exactly: {"approved":<boolean>}. No other prose outside the fence.',comment_suggestions:'Respond with a single fenced JSON block matching this shape exactly: {"suggestions":[{"body":"<string>"}]}. No other prose outside the fence.',free_text:"Respond in plain text. Do not wrap the answer in a JSON object."},mf={anthropic:"Anthropic",cursor:"Cursor"}});async function*yf(r){let{query:e}=await import("@anthropic-ai/claude-agent-sdk"),t=r.options;yield*e({prompt:r.prompt,options:{permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,...t?.cwd?{cwd:t.cwd}:{},...t?.resume?{resume:t.resume}:{},...t?.model?{model:t.model}:{},...t?.env?{env:t.env}:{}}})}var hf,ln,rc=l(()=>{"use strict";un();Oe();un();hf=kt("anthropic"),ln=class{secrets;options;constructor(e,t={}){this.secrets=e,this.options=t}async run(e){let t=await this.requireApiKey(),n=hr(e),o={permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,env:{...process.env,ANTHROPIC_API_KEY:t}};e.cwd&&(o.cwd=e.cwd),e.sessionId&&(o.resume=e.sessionId),this.options.model&&(o.model=this.options.model);let i=this.options.queryFn??yf,s,a,u;for await(let c of i({prompt:n,options:o}))c.session_id&&(s=c.session_id),c.type==="result"&&(c.subtype==="success"&&typeof c.result=="string"?a=c.result:u=c.errors?.join("; ")||c.subtype||"Claude agent returned an error result");if(u)throw new Error(`Claude agent failed: ${u}`);if(a==null)throw new Error("Claude agent returned no result text");if(!s)throw new Error("Claude agent returned no session id");return{raw:a,parsed:yr(a,e.outputFormat),sessionId:s}}async requireApiKey(){let e=this.options.secretKey?.trim()||hf,t=await this.secrets.get(e);if(!t)throw cn("anthropic",e);return t}}});function wf(r,e,t){return{apiKey:r,...t?{model:{id:t}}:{},local:{...e?{cwd:e}:{},settingSources:[]}}}async function bf(){let{Agent:r}=await import("@cursor/sdk");return{create:e=>r.create({apiKey:e.apiKey,...e.model?{model:e.model}:{},local:{...e.local?.cwd?{cwd:e.local.cwd}:{},settingSources:[]}}),resume:(e,t)=>r.resume(e,{apiKey:t.apiKey,...t.model?{model:t.model}:{},local:{...t.local?.cwd?{cwd:t.local.cwd}:{},settingSources:[]}})}}var gf,dn,nc=l(()=>{"use strict";un();Oe();gf=kt("cursor"),dn=class{secrets;options;constructor(e,t={}){this.secrets=e,this.options=t}async run(e){let t=await this.requireApiKey(),n=hr(e),o=this.options.sdk??await bf(),i=wf(t,e.cwd,this.options.model),s=e.sessionId?await o.resume(e.sessionId,i):await o.create(i);try{let u=await(await s.send(n)).wait();if(u.status!=="finished")throw new Error(u.error?.message||`Cursor agent ended with status '${u.status}'`);let c=u.result??"";return{raw:c,parsed:yr(c,e.outputFormat),sessionId:s.agentId}}finally{await s[Symbol.asyncDispose]?.()}}async requireApiKey(){let e=this.options.secretKey?.trim()||gf,t=await this.secrets.get(e);if(!t)throw cn("cursor",e);return t}}});function oc(r){return typeof r=="object"&&r!=null&&typeof r.listExtendedActions=="function"&&typeof r.executeExtendedAction=="function"}function pn(r,e){let t=r.params.filter(n=>n.required).filter(n=>{let o=e[n.name];return o==null||typeof o=="string"&&o.trim()===""}).map(n=>n.name);if(t.length>0)throw new Error(`Extended action '${r.actionId}' is missing required params: ${t.join(", ")}`)}function qt(r){return r.length===0?"none":r.map(e=>e.actionId).join(", ")}var fn=l(()=>{"use strict"});function gr(r){return r==null?"":typeof r=="string"?r:ic(r).replace(/\n+$/,"")}function mn(r){return{version:1,type:"doc",content:r.split(`
21
- `).map(t=>({type:"paragraph",content:t.length===0?[]:[{type:"text",text:t}]}))}}function ic(r){if(r==null||typeof r!="object")return"";let e=r;if(e.type==="text")return e.text??"";if(e.type==="hardBreak")return`
22
- `;let t=(e.content??[]).map(ic).join("");return e.type==="paragraph"||e.type==="heading"||e.type==="blockquote"||e.type==="listItem"?`${t}
23
- `:t}var Go=l(()=>{"use strict"});function If(r,e){return e.startsWith("http://")||e.startsWith("https://")?e:`${r.replace(/\/$/,"")}${e.startsWith("/")?e:`/${e}`}`}function ac(r){return{representation:"atlas_doc_format",value:JSON.stringify(mn(r))}}function uc(r){return gr(jf(r))}function jf(r){if(r==null||typeof r!="object")return r;let e=r.atlas_doc_format;if(e!=null){if(typeof e=="object"&&e!==null&&"value"in e){let t=e.value;if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t}return e}}function cc(r,e,t){return{id:String(r.id??""),source:t,title:String(r.title??""),url:_f(e,r),raw:r}}function _f(r,e){let t=r.replace(/\/$/,""),n=e._links?.webui?.trim();if(n)return n.startsWith("http://")||n.startsWith("https://")?n:n.startsWith("/wiki")?`${t}${n}`:`${t}/wiki${n.startsWith("/")?n:`/${n}`}`;let o=e.id!=null?String(e.id):"";return o?`${t}/wiki/pages/${encodeURIComponent(o)}`:t}function Ef(r,e){return{id:String(r.id??""),subjectId:e,body:uc(r.body),createdAt:r.version?.createdAt??r.createdAt??"",raw:r}}var Sf,xf,vf,sc,hn,yn,zo=l(()=>{"use strict";fn();Go();Sf="kno.confluence.apiToken",xf=50,vf=10,sc=500,hn=[{actionId:"create_page",label:"Create Confluence page",params:[{name:"spaceKey",label:"Space key",type:"string",required:!0},{name:"title",label:"Title",type:"string",required:!0},{name:"content",label:"Content",type:"string",required:!0}]}],yn=class{secrets;fetchFn;instanceId;baseUrl;email;secretKey;constructor(e,t,n=fetch){this.secrets=e,this.fetchFn=n,this.instanceId=t.instanceId,this.baseUrl=t.baseUrl?.trim()||void 0,this.email=t.email?.trim()||void 0,this.secretKey=t.secretKey?.trim()||Sf}async get(e){let{baseUrl:t}=await this.requireConfig(),n=await this.request("GET",`/wiki/api/v2/pages/${encodeURIComponent(e)}`);return cc(n,t,this.instanceId)}async getContent(e){await this.requireConfig();let t=await this.request("GET",`/wiki/api/v2/pages/${encodeURIComponent(e)}?body-format=atlas_doc_format`);return uc(t.body)}async query(e){let t=e.pageIds;if(!Array.isArray(t))throw new Error("Documentation query requires { pageIds: string[] }");let n=[];for(let o of t)n.push(await this.get(String(o)));return n}async getComments(e){await this.requireConfig();let t=[],n=`/wiki/api/v2/pages/${encodeURIComponent(e)}/footer-comments?body-format=atlas_doc_format&limit=${xf}`,o=new Set;for(let i=0;i<vf&&t.length<sc&&!(!n||o.has(n));i++){o.add(n);let s=await this.request("GET",n),a=Array.isArray(s.results)?s.results:[];for(let c of a){if(t.length>=sc)break;t.push(Ef(c,e))}let u=typeof s._links?.next=="string"?s._links.next:void 0;if(!u||a.length===0)break;n=u}return t}async postComment(e,t){await this.requireConfig(),await this.request("POST","/wiki/api/v2/footer-comments",{body:{pageId:e,body:ac(t)}})}listExtendedActions(){return hn}async executeExtendedAction(e,t){if(e==="create_page")return this.createPage(t);throw new Error(`Provider 'confluence' has no extended action '${e}'. Available: ${qt(this.listExtendedActions())}`)}async createPage(e){let t=hn[0];pn(t,e);let n=String(e.spaceKey).trim(),o=String(e.title).trim(),i=String(e.content),{baseUrl:s}=await this.requireConfig(),a=await this.resolveSpaceId(n),u=await this.request("POST","/wiki/api/v2/pages",{body:{spaceId:a,status:"current",title:o,body:ac(i)}});return cc(u,s,this.instanceId)}async resolveSpaceId(e){let t=await this.request("GET",`/wiki/api/v2/spaces?keys=${encodeURIComponent(e)}`),n=Array.isArray(t.results)?t.results:[],o=n.find(s=>(s.key??"").toLowerCase()===e.toLowerCase())??n[0],i=o?.id!=null?String(o.id):"";if(!i)throw new Error(`Confluence space '${e}' was not found`);return i}async requireConfig(){let e=this.baseUrl,t=this.email,n=await this.secrets.get(this.secretKey);if(!e||!t||!n){let o=[];throw e||o.push("config.baseUrl"),t||o.push("config.email"),n||o.push(`SecretStore '${this.secretKey}'`),new Error(`Confluence instance '${this.instanceId}' is not configured \u2014 missing ${o.join(", ")}. Set baseUrl and email on the provider instance, and store the API token with: POST /api/secrets/${this.secretKey} or npm --workspace apps/engine run set-secret -- ${this.secretKey} <value>`)}return{baseUrl:e,email:t,token:n}}async request(e,t,n={}){let{baseUrl:o,email:i,token:s}=await this.requireConfig(),a=If(o,t),u={Authorization:`Basic ${Buffer.from(`${i}:${s}`).toString("base64")}`,Accept:"application/json"};n.body!==void 0&&(u["Content-Type"]="application/json");let c=await this.fetchFn(a,{method:e,headers:u,...n.body!==void 0?{body:JSON.stringify(n.body)}:{}});if(!c.ok){let m=await c.text().catch(()=>"");throw new Error(`Confluence ${e} ${t} failed (${c.status}): ${m||c.statusText}`)}if(c.status===204)return;let p=await c.text();if(p)return JSON.parse(p)}}});import{randomUUID as Pf}from"node:crypto";var Rf,gn,lc=l(()=>{"use strict";Rf=new Set(["github_wiki","gitlab_wiki","azure_wiki","web"]),gn=class{pages;contentById;comments;instanceId;type;constructor(e=[],t){this.pages=new Map,this.contentById=new Map,this.comments=new Map,this.instanceId=t?.instanceId,this.type=t?.type;for(let n of e){let{content:o,...i}=n;this.pages.set(i.id,structuredClone(i)),o!==void 0&&this.contentById.set(i.id,o)}}async get(e){let t=this.pages.get(e);if(!t)throw new Error(`Documentation page not found: ${e}`);return this.withSource(structuredClone(t))}async getContent(e){await this.get(e);let t=this.contentById.get(e);if(t===void 0)throw new Error(`Documentation content not found: ${e}`);return t}async query(e){let t=e.pageIds;if(!Array.isArray(t))throw new Error("Documentation query requires { pageIds: string[] }");let n=[];for(let o of t)n.push(await this.get(String(o)));return n}async getComments(e){let t=await this.get(e);return this.assertCommentsSupported(t),structuredClone(this.comments.get(e)??[])}async postComment(e,t){let n=await this.get(e);this.assertCommentsSupported(n);let o=this.comments.get(e)??[];o.push({id:Pf(),subjectId:e,body:t,createdAt:new Date().toISOString()}),this.comments.set(e,o)}assertCommentsSupported(e){let t=this.type??e.source;if(Rf.has(t))throw new Error(`Comments are not supported for documentation source '${t}'`)}withSource(e){return this.instanceId?{...e,source:this.instanceId}:e}}});function Qo(){return Af.replace(/\/$/,"")}function wr(r){let e=r.trim(),t=e.lastIndexOf("#");if(t<=0||t===e.length-1)throw new Error(`Bitbucket pull request id must be '{repoSlug}#{prNumber}' (e.g. 'kno-engine#42'), got '${r}'`);let n=e.slice(0,t),o=e.slice(t+1);if(!/^\d+$/.test(o))throw new Error(`Bitbucket pull request id must be '{repoSlug}#{prNumber}' with a numeric PR number, got '${r}'`);return{repoSlug:n,prNumber:o}}function Cf(r,e){return`${r}#${e}`}function Tf(r){let e=r.repoSlug;if(typeof e!="string"||e.trim().length===0)throw new Error("Bitbucket query requires filter.repoSlug or filter.role \u2014 repo-scoped listing needs repoSlug; workspace-wide listing needs role (author|reviewer)");return e.trim()}function Of(r){if(typeof r.repoSlug=="string"&&r.repoSlug.trim().length>0||!fc(r.role))return;let e=String(r.role).trim().toLowerCase();if(e!=="author"&&e!=="reviewer")throw new Error(`Bitbucket query filter.role must be 'author' or 'reviewer', got '${String(r.role)}'`);return e}function pc(r){if(!fc(r))return;let e=String(r).trim().toUpperCase();if(e!=="OPEN"&&e!=="MERGED"&&e!=="DECLINED")throw new Error(`Bitbucket query filter.state must be OPEN, MERGED, or DECLINED, got '${String(r)}'`);return e}function $f(r){if(typeof r.q=="string"&&r.q.trim().length>0)return r.q;let e=pc(r.state);if(e)return`state="${e}"`}function qf(r){let e=r.destination?.repository?.name;if(typeof e=="string"&&e.trim().length>0)return e.trim();let t=r.destination?.repository?.full_name;if(typeof t=="string"&&t.includes("/"))return t.slice(t.lastIndexOf("/")+1);throw new Error("Bitbucket workspace pull request is missing destination.repository slug")}function Bf(r){let e=r.trim().toLowerCase();if(e==="approved")return"approve";if(e==="declined"||e==="rejected")return"decline";if(e==="merged")return"merge";throw new Error(`No Bitbucket action for status '${r}'. Accepted: approved, declined/rejected, merged`)}function fc(r){return r!=null&&r!==""}function Zo(...r){for(let e of r)if(typeof e=="string"&&e.trim().length>0)return e.trim()}function wn(r,e,t){let n=String(r.id??""),o=typeof r.description=="string"?r.description:"";return{id:Cf(e,n),source:t,title:String(r.title??""),...o?{description:o}:{},sourceBranch:String(r.source?.branch?.name??""),targetBranch:String(r.destination?.branch?.name??""),...r.author?.display_name?{author:r.author.display_name}:{},...r.links?.html?.href?{url:r.links.html.href}:{},raw:r}}function Df(r,e){let t=r.user?.display_name??r.author?.display_name;return{id:String(r.id??""),subjectId:e,body:r.content?.raw??"",...t?{author:t}:{},createdAt:r.created_on??"",raw:r}}var kf,Af,Xo,dc,Yo,ei,bn,ti=l(()=>{"use strict";fn();kf="kno.bitbucket.apiToken",Af="https://api.bitbucket.org/2.0";Xo=50,dc=10,Yo=500,ei=[{actionId:"add_reviewer",label:"Add reviewer",params:[{name:"username",label:"Reviewer username",type:"string",required:!0}]}],bn=class{secrets;fetchFn;instanceId;email;workspace;secretKey;constructor(e,t,n=fetch){this.secrets=e,this.fetchFn=n,this.instanceId=t.instanceId,this.email=t.email?.trim()||void 0,this.workspace=t.workspace?.trim()||void 0,this.secretKey=t.secretKey?.trim()||kf}async get(e){let{repoSlug:t,prNumber:n}=wr(e),{workspace:o}=await this.requireConfig(),i=await this.request("GET",this.prPath(o,t,n));return wn(i,t,this.instanceId)}async query(e){let t=Of(e);if(t)return this.queryWorkspacePullRequests(t,e);let n=Tf(e),{workspace:o}=await this.requireConfig(),i=$f(e),s=new URLSearchParams({pagelen:String(Xo)});i&&s.set("q",i);let a=`${Qo()}/repositories/${encodeURIComponent(o)}/${encodeURIComponent(n)}/pullrequests?${s.toString()}`;return this.collectPullRequests(a,n)}async queryWorkspacePullRequests(e,t){let{workspace:n}=await this.requireConfig(),o=await this.selectedUser(),i=new URLSearchParams({pagelen:String(Xo)}),s=pc(t.state);s&&i.set("state",s),e==="reviewer"&&i.set("role","REVIEWER");let a=`${Qo()}/workspaces/${encodeURIComponent(n)}/pullrequests/${encodeURIComponent(o)}?${i.toString()}`;return this.collectPullRequests(a)}selectedUserCache;async selectedUser(){let{email:e}=await this.requireConfig();if(this.selectedUserCache?.email===e)return this.selectedUserCache.id;let t=await this.request("GET","/user"),n=Zo(t.uuid,t.account_id,t.username);if(!n)throw new Error("Bitbucket GET /user did not return uuid, account_id, or username \u2014 cannot list workspace pull requests");return this.selectedUserCache={email:e,id:n},n}async collectPullRequests(e,t){let n=[],o=new Set,i=e;for(let s=0;s<dc&&n.length<Yo&&!(!i||o.has(i));s++){o.add(i);let a=await this.request("GET",i),u=Array.isArray(a.values)?a.values:[];for(let p of u){if(n.length>=Yo)break;n.push(wn(p,t??qf(p),this.instanceId))}let c=typeof a.next=="string"&&a.next.length>0?a.next:void 0;if(!c||u.length===0)break;i=c}return n}async getComments(e){let{repoSlug:t,prNumber:n}=wr(e),{workspace:o}=await this.requireConfig(),i=[],s=new Set,a=`${this.prPath(o,t,n)}/comments?pagelen=${Xo}`;for(let u=0;u<dc&&i.length<Yo&&!(!a||s.has(a));u++){s.add(a);let c=await this.request("GET",a),p=Array.isArray(c.values)?c.values:[];for(let b of p)i.push(Df(b,e));let m=typeof c.next=="string"&&c.next.length>0?c.next:void 0;if(!m||p.length===0)break;a=m}return i}async postComment(e,t){let{repoSlug:n,prNumber:o}=wr(e),{workspace:i}=await this.requireConfig();await this.request("POST",`${this.prPath(i,n,o)}/comments`,{body:{content:{raw:t}}})}async updateStatus(e,t){let{repoSlug:n,prNumber:o}=wr(e),{workspace:i}=await this.requireConfig(),s=Bf(t);await this.request("POST",`${this.prPath(i,n,o)}/${s}`)}listExtendedActions(){return ei}async executeExtendedAction(e,t){if(e==="add_reviewer")return this.addReviewer(t);throw new Error(`Provider 'bitbucket' has no extended action '${e}'. Available: ${qt(this.listExtendedActions())}`)}async addReviewer(e){let t=typeof e.subjectId=="string"?e.subjectId.trim():"";if(!t)throw new Error("Bitbucket action 'add_reviewer' requires params.subjectId");let n=typeof e.username=="string"?e.username.trim():"";if(!n)throw new Error("Bitbucket action 'add_reviewer' requires params.username");let{repoSlug:o,prNumber:i}=wr(t),{workspace:s}=await this.requireConfig(),a=await this.request("GET",this.prPath(s,o,i)),u=await this.request("GET",`/users/${encodeURIComponent(n)}`),c=Zo(u.uuid),p=Zo(u.account_id);if(!c&&!p)throw new Error(`Bitbucket user '${n}' has no uuid or account_id`);let m=Array.isArray(a.reviewers)?a.reviewers:[];if(m.some(N=>c!=null&&N.uuid===c||p!=null&&N.account_id===p))return wn(a,o,this.instanceId);let S=[...m.map(N=>N.uuid?{uuid:N.uuid}:{account_id:N.account_id}),c?{uuid:c}:{account_id:p}],j=await this.request("PUT",this.prPath(s,o,i),{body:{title:a.title??"",reviewers:S}});return wn(j,o,this.instanceId)}prPath(e,t,n){return`/repositories/${encodeURIComponent(e)}/${encodeURIComponent(t)}/pullrequests/${encodeURIComponent(n)}`}async requireConfig(){let e=this.email,t=this.workspace,n=await this.secrets.get(this.secretKey);if(!e||!t||!n){let o=[];throw e||o.push("config.email"),t||o.push("config.workspace"),n||o.push(`SecretStore '${this.secretKey}'`),new Error(`Bitbucket instance '${this.instanceId}' is not configured \u2014 missing ${o.join(", ")}. Set email and workspace on the provider instance, and store the API token with: POST /api/secrets/${this.secretKey} or npm --workspace apps/engine run set-secret -- ${this.secretKey} <value>`)}return{email:e,workspace:t,token:n}}async request(e,t,n={}){let{email:o,token:i}=await this.requireConfig(),s=t.startsWith("http://")||t.startsWith("https://")?t:`${Qo()}${t.startsWith("/")?t:`/${t}`}`,a={Authorization:`Basic ${Buffer.from(`${o}:${i}`).toString("base64")}`,Accept:"application/json"};n.body!==void 0&&(a["Content-Type"]="application/json");let u=await this.fetchFn(s,{method:e,headers:a,...n.body!==void 0?{body:JSON.stringify(n.body)}:{}});if(!u.ok){let p=await u.text().catch(()=>"");throw new Error(`Bitbucket ${e} ${t} failed (${u.status}): ${p||u.statusText}`)}if(u.status===204)return;let c=await u.text();if(c)return JSON.parse(c)}}});import{randomUUID as Ff}from"node:crypto";function Nf(r,e){return Object.entries(e).every(([t,n])=>t==="status"?r.raw?.status===n:r[t]===n)}var Sn,mc=l(()=>{"use strict";Sn=class{pullRequests;comments;instanceId;constructor(e=[],t){this.pullRequests=new Map(e.map(n=>[n.id,structuredClone(n)])),this.comments=new Map,this.instanceId=t}async get(e){let t=this.pullRequests.get(e);if(!t)throw new Error(`Pull request not found: ${e}`);return this.withSource(structuredClone(t))}async query(e){return[...this.pullRequests.values()].filter(t=>Nf(t,e)).map(t=>this.withSource(structuredClone(t)))}async getComments(e){return await this.get(e),structuredClone(this.comments.get(e)??[])}async postComment(e,t){await this.get(e);let n=this.comments.get(e)??[];n.push({id:Ff(),subjectId:e,body:t,createdAt:new Date().toISOString()}),this.comments.set(e,n)}async updateStatus(e,t){let n=this.pullRequests.get(e);if(!n)throw new Error(`Pull request not found: ${e}`);n.raw={...n.raw??{},status:t}}withSource(e){return this.instanceId?{...e,source:this.instanceId}:e}}});function ri(r){return r.pull_request!=null}function xn(r){let e=r.trim(),t=e.lastIndexOf("#");if(t<=0||t===e.length-1)throw new Error(`GitHub issue id must be '{owner}/{repo}#{issueNumber}' (e.g. 'acme/kno#42'), got '${r}'`);let n=e.slice(0,t),o=e.slice(t+1),{owner:i,name:s}=hc(n);if(!/^\d+$/.test(o))throw new Error(`GitHub issue id must be '{owner}/{repo}#{issueNumber}' (e.g. 'acme/kno#42'), got '${r}'`);return{owner:i,repo:s,issueNumber:o}}function Wf(r,e,t){return`${r}/${e}#${t}`}function hc(r){let e=r.trim(),t=e.indexOf("/");if(t<=0||t===e.length-1||e.indexOf("/",t+1)!==-1)throw new Error(`GitHub repo must be '{owner}/{name}', got '${r}'`);return{owner:e.slice(0,t),name:e.slice(t+1)}}function Hf(r){let e=r.role;if(e==="assignee"||e==="creator")return e}function Vf(r,e){return r==="creator"?`author:${e}`:`assignee:${e}`}function Kf(r){let e=r.trim().toLowerCase();if(e==="open")return{state:"open"};if(e==="closed"||e==="done"||e==="completed")return{state:"closed",state_reason:"completed"};if(e==="not_planned"||e==="wontfix")return{state:"closed",state_reason:"not_planned"};throw new Error(`No GitHub Issues mapping for status '${r}'. Accepted: ${Mf.join(", ")}`)}function Gf(r){let e=r.repository?.full_name;if(typeof e=="string"&&e.includes("/"))return e;let t=r.repository_url;if(typeof t=="string"){let n="/repos/",o=t.lastIndexOf(n);if(o>=0){let i=t.slice(o+n.length);if(i.includes("/"))return i}}throw new Error("GitHub search result is missing repository full_name")}function ni(r,e,t){let n=String(r.number??""),[o,i]=t.split("/"),s=typeof r.body=="string"?r.body:"";return{id:Wf(o??"",i??"",n),source:e,title:String(r.title??""),...s?{description:s}:{},status:String(r.state??""),...r.assignee?.login?{assignee:r.assignee.login}:{},...r.html_url?{url:r.html_url}:{},raw:r}}function zf(r,e){return{id:String(r.id??""),subjectId:e,body:r.body??"",...r.user?.login?{author:r.user.login}:{},createdAt:r.created_at??""}}function vn(r){return r!=null&&r!==""}var Jf,Lf,Uf,Mf,In,yc=l(()=>{"use strict";Jf="2026-03-10",Lf="https://api.github.com",Uf="kno.github.apiToken",Mf=["open","closed/done/completed","not_planned/wontfix"],In=class{secrets;fetchFn;instanceId;username;secretKey;constructor(e,t,n=fetch){this.secrets=e,this.fetchFn=n,this.instanceId=t.instanceId,this.username=t.username?.trim()||void 0,this.secretKey=t.secretKey?.trim()||Uf}async get(e){let{owner:t,repo:n,issueNumber:o}=xn(e),i=await this.request("GET",`/repos/${encodeURIComponent(t)}/${encodeURIComponent(n)}/issues/${encodeURIComponent(o)}`);if(ri(i))throw new Error(`Ticket not found: ${e}`);return ni(i,this.instanceId,`${t}/${n}`)}async query(e){let t=typeof e.repo=="string"?e.repo.trim():"";if(t)return this.queryRepoIssues(t,e);let n=Hf(e);if(n)return this.querySearch(n,e);throw new Error("GitHub Issues query requires filter.repo ('owner/name') or filter.role ('assignee' | 'creator')")}async getComments(e){let{owner:t,repo:n,issueNumber:o}=xn(e),i=await this.request("GET",`/repos/${encodeURIComponent(t)}/${encodeURIComponent(n)}/issues/${encodeURIComponent(o)}/comments`);return(Array.isArray(i)?i:[]).map(a=>zf(a,e))}async postComment(e,t){let{owner:n,repo:o,issueNumber:i}=xn(e);await this.request("POST",`/repos/${encodeURIComponent(n)}/${encodeURIComponent(o)}/issues/${encodeURIComponent(i)}/comments`,{body:{body:t}})}async updateStatus(e,t){let{owner:n,repo:o,issueNumber:i}=xn(e);await this.request("PATCH",`/repos/${encodeURIComponent(n)}/${encodeURIComponent(o)}/issues/${encodeURIComponent(i)}`,{body:Kf(t)})}async queryRepoIssues(e,t){let{owner:n,name:o}=hc(e),i=[],s=new URLSearchParams;s.set("per_page",String(100)),vn(t.state)&&s.set("state",String(t.state)),vn(t.labels)&&s.set("labels",String(t.labels)),vn(t.assignee)&&s.set("assignee",String(t.assignee));for(let a=1;a<=10&&i.length<500;a++){s.set("page",String(a));let u=await this.request("GET",`/repos/${encodeURIComponent(n)}/${encodeURIComponent(o)}/issues?${s.toString()}`),c=Array.isArray(u)?u:[];if(c.length===0)break;for(let p of c)if(!ri(p)){if(i.length>=500)break;i.push(ni(p,this.instanceId,`${n}/${o}`))}if(c.length<100)break}return i}async querySearch(e,t){let n=this.requireUsername(),o=[Vf(e,n),"is:issue"];vn(t.state)&&o.push(`is:${String(t.state).trim().toLowerCase()}`);let i=o.join(" "),s=[];for(let a=1;a<=10&&s.length<500;a++){let u=new URLSearchParams({q:i,per_page:String(100),page:String(a)}),c=await this.request("GET",`/search/issues?${u.toString()}`),p=Array.isArray(c.items)?c.items:[];if(p.length===0)break;for(let m of p)if(!ri(m)){if(s.length>=500)break;s.push(ni(m,this.instanceId,Gf(m)))}if(p.length<100)break}return s}requireUsername(){if(!this.username)throw new Error(`GitHub Issues instance '${this.instanceId}' is not configured \u2014 missing config.username`);return this.username}async requireToken(){let e=await this.secrets.get(this.secretKey);if(!e)throw new Error(`GitHub Issues instance '${this.instanceId}' is not configured \u2014 missing SecretStore '${this.secretKey}'. Store the token with: POST /api/secrets/${this.secretKey} or npm --workspace apps/engine run set-secret -- ${this.secretKey} <value>`);return e}async request(e,t,n={}){let o=await this.requireToken(),i=`${Lf}${t}`,s={Authorization:`Bearer ${o}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":Jf};n.body!==void 0&&(s["Content-Type"]="application/json");let a=await this.fetchFn(i,{method:e,headers:s,...n.body!==void 0?{body:JSON.stringify(n.body)}:{}});if(!a.ok){let c=await a.text().catch(()=>"");throw new Error(`GitHub ${e} ${t} failed (${a.status}): ${c||a.statusText}`)}if(a.status===204)return;let u=await a.text();if(u)return JSON.parse(u)}}});var wt,y,h,J,R=l(()=>{"use strict";wt=class extends Error{constructor(e){super(e),this.name=this.constructor.name}},y=class extends wt{httpStatus=404},h=class extends wt{httpStatus=400},J=class extends wt{httpStatus=409}});function Zf(r){if(typeof r.jql=="string"&&r.jql.trim().length>0)return r.jql;let e=[];if(_n(r.project)&&e.push(`project = ${En(r.project)}`),_n(r.status)&&e.push(`status = ${En(r.status)}`),_n(r.assignee)&&e.push(`assignee = ${En(r.assignee)}`),_n(r.sprintId)){let t=r.sprintId;e.push(typeof t=="number"||/^\d+$/.test(String(t))?`sprint = ${Number(t)}`:`sprint = ${En(t)}`)}if(e.length===0)throw new h("Jira query requires jql or at least one of project, status, assignee, sprintId");return e.join(" AND ")}function _n(r){return r!=null&&r!==""}function En(r){return`"${String(r).replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function gc(r,e,t){let n=String(r.key??r.id??""),o=r.fields??{},i=gr(o.description);return{id:n,source:t,title:String(o.summary??""),...i?{description:i}:{},status:String(o.status?.name??""),...o.assignee?.displayName?{assignee:String(o.assignee.displayName)}:{},url:`${e.replace(/\/$/,"")}/browse/${n}`,raw:r}}var Qf,Xf,Yf,jn,Pn,wc=l(()=>{"use strict";R();Go();Qf="kno.jira.apiToken",Xf=50,Yf=10,jn=500,Pn=class{secrets;fetchFn;instanceId;baseUrl;email;secretKey;constructor(e,t,n=fetch){this.secrets=e,this.fetchFn=n,this.instanceId=t.instanceId,this.baseUrl=t.baseUrl?.trim()||void 0,this.email=t.email?.trim()||void 0,this.secretKey=t.secretKey?.trim()||Qf}async get(e){let{baseUrl:t}=await this.requireConfig(),n=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}`);return gc(n,t,this.instanceId)}async query(e){let{baseUrl:t}=await this.requireConfig(),n=Zf(e),o=[],i,s=new Set;for(let a=0;a<Yf&&o.length<jn;a++){let u={jql:n,maxResults:Math.min(Xf,jn-o.length),fields:["summary","description","status","assignee"]};i&&(u.nextPageToken=i);let c=await this.request("POST","/rest/api/3/search/jql",{body:u}),p=Array.isArray(c.issues)?c.issues:[];for(let b of p){if(o.length>=jn)break;o.push(gc(b,t,this.instanceId))}let m=typeof c.nextPageToken=="string"?c.nextPageToken:void 0;if(c.isLast===!0||!m||p.length===0||m===i||s.has(m))break;s.add(m),i=m}return o}async getComments(e){let t=[],n=0,o=100,i=jn;for(;t.length<i;){let s=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}/comment?startAt=${n}&maxResults=${o}`),a=Array.isArray(s.comments)?s.comments:[];for(let u of a)t.push({id:String(u.id??""),subjectId:e,body:gr(u.body),...u.author?.displayName?{author:u.author.displayName}:{},createdAt:u.created??"",raw:u});if(n+=a.length,a.length===0||typeof s.total=="number"&&n>=s.total||a.length<o)break}return t}async postComment(e,t){await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(e)}/comment`,{body:{body:mn(t)}})}async updateStatus(e,t){let n=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}/transitions`),o=Array.isArray(n.transitions)?n.transitions:[],i=t.trim().toLowerCase(),s=o.find(a=>(a.to?.name??"").trim().toLowerCase()===i);if(!s?.id){let a=o.map(c=>c.to?.name).filter(c=>typeof c=="string"&&c.length>0),u=a.length>0?a.join(", "):"(none)";throw new Error(`No Jira transition to status '${t}' from the current state. Available: ${u}`)}await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(e)}/transitions`,{body:{transition:{id:s.id}}})}async requireConfig(){let e=this.baseUrl,t=this.email,n=await this.secrets.get(this.secretKey);if(!e||!t||!n){let o=[];throw e||o.push("config.baseUrl"),t||o.push("config.email"),n||o.push(`SecretStore '${this.secretKey}'`),new Error(`Jira instance '${this.instanceId}' is not configured \u2014 missing ${o.join(", ")}. Set baseUrl and email on the provider instance, and store the API token with: POST /api/secrets/${this.secretKey} or npm --workspace apps/engine run set-secret -- ${this.secretKey} <value>`)}return{baseUrl:e,email:t,token:n}}async request(e,t,n={}){let{baseUrl:o,email:i,token:s}=await this.requireConfig(),a=`${o.replace(/\/$/,"")}${t}`,u={Authorization:`Basic ${Buffer.from(`${i}:${s}`).toString("base64")}`,Accept:"application/json"};n.body!==void 0&&(u["Content-Type"]="application/json");let c=await this.fetchFn(a,{method:e,headers:u,...n.body!==void 0?{body:JSON.stringify(n.body)}:{}});if(!c.ok){let m=await c.text().catch(()=>"");throw new Error(`Jira ${e} ${t} failed (${c.status}): ${m||c.statusText}`)}if(c.status===204)return;let p=await c.text();if(p)return JSON.parse(p)}}});import{randomUUID as em}from"node:crypto";function tm(r,e){return Object.entries(e).every(([t,n])=>r[t]===n)}var Rn,bc=l(()=>{"use strict";Rn=class{tickets;comments;instanceId;constructor(e=[],t){this.tickets=new Map(e.map(n=>[n.id,structuredClone(n)])),this.comments=new Map,this.instanceId=t}async get(e){let t=this.tickets.get(e);if(!t)throw new Error(`Ticket not found: ${e}`);return this.withSource(structuredClone(t))}async query(e){return[...this.tickets.values()].filter(t=>tm(t,e)).map(t=>this.withSource(structuredClone(t)))}async getComments(e){return await this.get(e),structuredClone(this.comments.get(e)??[])}async postComment(e,t){await this.get(e);let n=this.comments.get(e)??[];n.push({id:em(),subjectId:e,body:t,createdAt:new Date().toISOString()}),this.comments.set(e,n)}async updateStatus(e,t){let n=this.tickets.get(e);if(!n)throw new Error(`Ticket not found: ${e}`);n.status=t}withSource(e){return this.instanceId?{...e,source:this.instanceId}:e}}});function De(r,e){let t=r[e];return typeof t=="string"&&t.trim().length>0?t.trim():void 0}function kn(r){return new Error(`This workflow requires provider instance '${r}', which isn't configured`)}function rm(r){return r==="jira"||r==="github"?"ticket":r==="bitbucket"?"pull_request":r==="confluence"?"documentation":"any"}var Rv,F,Bt=l(()=>{"use strict";C();rc();nc();zo();lc();ti();mc();yc();wc();bc();Rv=Symbol("PROVIDER_REGISTRY");F=class r{tickets=new Map;repos=new Map;documentation=new Map;agents=new Map;instances=[];constructor(){}static fromSettings(e,t){let n=new r;return n.load(e,t),n}static fromMaps(e){let t=new r;for(let[n,o]of Object.entries(e.tickets??{}))t.tickets.set(n,o);for(let[n,o]of Object.entries(e.repos??{}))t.repos.set(n,o);for(let[n,o]of Object.entries(e.documentation??{}))t.documentation.set(n,o);for(let[n,o]of Object.entries(e.agents??{}))t.agents.set(n,o);return t.instances.push(...e.instances??[]),t}load(e,t){let n=new Set;for(let o of e){if(n.has(o.id))throw new Error(`Duplicate provider instance id '${o.id}'`);n.add(o.id),this.instances.push(o),this.instantiate(o,t)}}instantiate(e,t){if($t(e)){let o=De(e.config,"model");if(e.type==="claude"){this.agents.set(e.id,new ln(t,{secretKey:e.secretKey,model:o}));return}this.agents.set(e.id,new dn(t,{secretKey:e.secretKey,model:o}));return}if(!gt(e))throw new Error(`Unknown provider instance kind on '${e.id}'`);let n=rm(e.type);if(n!=="any"&&e.subjectType!==n)throw new Error(`Provider instance '${e.id}' type '${e.type}' cannot serve subjectType '${e.subjectType}'`);if(e.type==="jira"){this.tickets.set(e.id,new Pn(t,{instanceId:e.id,baseUrl:De(e.config,"baseUrl"),email:De(e.config,"email"),secretKey:e.secretKey}));return}if(e.type==="github"){this.tickets.set(e.id,new In(t,{instanceId:e.id,username:De(e.config,"username"),secretKey:e.secretKey}));return}if(e.type==="bitbucket"){this.repos.set(e.id,new bn(t,{instanceId:e.id,email:De(e.config,"email"),workspace:De(e.config,"workspace"),secretKey:e.secretKey}));return}if(e.type==="confluence"){this.documentation.set(e.id,new yn(t,{instanceId:e.id,baseUrl:De(e.config,"baseUrl"),email:De(e.config,"email"),secretKey:e.secretKey}));return}if(e.subjectType==="ticket"){this.tickets.set(e.id,new Rn([],e.id));return}if(e.subjectType==="pull_request"){this.repos.set(e.id,new Sn([],e.id));return}this.documentation.set(e.id,new gn([],{instanceId:e.id,type:De(e.config,"type")}))}getTicketProvider(e){let t=this.tickets.get(e);if(!t)throw kn(e);return t}getRepoProvider(e){let t=this.repos.get(e);if(!t)throw kn(e);return t}getDocumentationProvider(e){let t=this.documentation.get(e);if(!t)throw kn(e);return t}getAgentProvider(e){let t=this.agents.get(e);if(!t)throw kn(e);return t}getInstance(e){return this.instances.find(t=>t.id===e)}listInstances(e){return e==null?[...this.instances]:this.instances.filter(t=>gt(t)&&t.subjectType===e)}ticketInstanceIds(){return[...this.tickets.keys()]}repoInstanceIds(){return[...this.repos.keys()]}documentationInstanceIds(){return[...this.documentation.keys()]}}});function xc(r,e){switch(r){case"my-open-prs":return{role:"author",state:"OPEN"};case"reviewing":return{role:"reviewer",state:"OPEN"};case"repo-open-prs":{let t=typeof e.repoSlug=="string"?e.repoSlug.trim():"";if(!t)throw new h("Bitbucket template 'repo-open-prs' requires params.repoSlug");return{repoSlug:t,state:"OPEN"}}default:throw new y(`Unknown Bitbucket query template: ${r}`)}}var Sc,vc=l(()=>{"use strict";R();Sc=[{id:"my-open-prs",label:"My open pull requests",params:[]},{id:"reviewing",label:"Pull requests I'm reviewing",params:[]},{id:"repo-open-prs",label:"Open pull requests in a repository",params:[{name:"repoSlug",label:"Repository",type:"string",required:!0}]}]});function jc(r,e){switch(r){case"my-open-issues":return{role:"assignee",state:"open"};case"created-by-me":return{role:"creator",state:"open"};case"repo-open-issues":{let t=typeof e.repo=="string"?e.repo.trim():"";if(!t)throw new h("GitHub template 'repo-open-issues' requires params.repo");return{repo:t,state:"open"}}default:throw new y(`Unknown GitHub query template: ${r}`)}}var Ic,_c=l(()=>{"use strict";R();Ic=[{id:"my-open-issues",label:"My open issues",params:[]},{id:"created-by-me",label:"Issues I created",params:[]},{id:"repo-open-issues",label:"Open issues in a repository",params:[{name:"repo",label:"Repository (owner/name)",type:"string",required:!0}]}]});function Ac(r,e){switch(r){case"my-open-tickets":return{jql:"assignee = currentUser() AND statusCategory != Done"};case"created-by-me":return{jql:"reporter = currentUser() AND statusCategory != Done"};case"project-open-tickets":return{jql:`project = ${Rc(Pc(r,e))} AND statusCategory != Done`};case"current-sprint-tickets":return{jql:`project = ${Rc(Pc(r,e))} AND sprint in openSprints() AND statusCategory != Done`};default:throw new y(`Unknown Jira query template: ${r}`)}}function Pc(r,e){let t=typeof e.project=="string"?e.project.trim():"";if(!t)throw new h(`Jira template '${r}' requires params.project`);return t}function Rc(r){return`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}var Ec,kc,Cc=l(()=>{"use strict";R();Ec={name:"project",label:"Project key",type:"string",required:!0},kc=[{id:"my-open-tickets",label:"My open tickets",params:[]},{id:"created-by-me",label:"Tickets I created",params:[]},{id:"project-open-tickets",label:"Open tickets in a project",params:[Ec]},{id:"current-sprint-tickets",label:"Tickets in the current sprint",params:[Ec]}]});import{Inject as Oc,Injectable as im}from"@nestjs/common";var nm,om,Tc,$c,nt,oi=l(()=>{"use strict";C();R();Pe();Bt();vc();_c();Cc();nm=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},om=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},Tc=function(r,e){return function(t,n){e(t,n,r)}},$c={bitbucket:{list:()=>Sc,resolve:xc},github:{list:()=>Ic,resolve:jc},jira:{list:()=>kc,resolve:Ac}},nt=class{settings;registry;constructor(e,t){this.settings=e,this.registry=t}async list(e){let t=await this.providerType(e);return t?$c[t]?.list()??[]:[]}async resolve(e,t,n){let o=await this.providerType(e),i=o?$c[o]:void 0;if(!i)throw new y(`No query templates for provider instance '${e}'`);let s=i.list().find(a=>a.id===t);if(!s)throw new y(`Unknown query template '${t}' for provider instance '${e}'`);for(let a of s.params){if(!a.required)continue;let u=n[a.name];if(u==null||typeof u=="string"&&u.trim()==="")throw new h(`Template '${t}' requires params.${a.name}`)}return i.resolve(t,n)}async providerType(e){let n=(await this.settings.get()).providerInstances?.find(o=>o.id===e)??this.registry.getInstance(e);if(!(!n||!gt(n)))return n.type}};nt=nm([im(),Tc(0,Oc(P)),Tc(1,Oc(F)),om("design:paramtypes",[P,F])],nt)});import{Inject as Bc,Injectable as cm}from"@nestjs/common";var sm,am,qc,um,ot,ii=l(()=>{"use strict";C();Pe();zo();ti();Bt();sm=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},am=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},qc=function(r,e){return function(t,n){e(t,n,r)}},um={bitbucket:()=>ei,confluence:()=>hn},ot=class{settings;registry;constructor(e,t){this.settings=e,this.registry=t}async list(e){let n=(await this.settings.get()).providerInstances?.find(o=>o.id===e)??this.registry.getInstance(e);return!n||!gt(n)?[]:um[n.type]?.()??[]}};ot=sm([cm(),qc(0,Bc(P)),qc(1,Bc(F)),am("design:paramtypes",[P,F])],ot)});async function Dc(r){let e=r.fetchFn??fetch;return r.type==="claude"?fm(r.apiKey,e):mm(r.apiKey,e)}async function fm(r,e){let t=await e(lm,{method:"GET",headers:{"x-api-key":r,"anthropic-version":pm}});if(!t.ok)throw Fc("Claude",t.status);let n=await t.json();return(Array.isArray(n.data)?n.data:[]).flatMap(i=>{if(!i||typeof i!="object")return[];let s=i,a=typeof s.id=="string"?s.id:"";if(!a)return[];let u=typeof s.display_name=="string"&&s.display_name.trim()?s.display_name:a;return[{id:a,displayName:u}]})}async function mm(r,e){let t=await e(dm,{method:"GET",headers:{Authorization:`Basic ${Buffer.from(`${r}:`).toString("base64")}`}});if(!t.ok)throw Fc("Cursor",t.status);let n=await t.json();return(Array.isArray(n.items)?n.items:[]).flatMap(i=>{if(!i||typeof i!="object")return[];let s=i,a=typeof s.id=="string"?s.id:"";if(!a)return[];let u=typeof s.displayName=="string"&&s.displayName.trim()?s.displayName:a;return[{id:a,displayName:u}]})}function Fc(r,e){let t=new Error(`${r} rejected the API key (HTTP ${e}). Check the key and try again.`);return t.name="PreviewModelsAuthError",t}var lm,dm,pm,Nc=l(()=>{"use strict";lm="https://api.anthropic.com/v1/models",dm="https://api.cursor.com/v1/models",pm="2023-06-01"});import{Inject as ai,Injectable as gm}from"@nestjs/common";var hm,ym,si,An,it,ci=l(()=>{"use strict";C();Pe();Oe();R();Nc();hm=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},ym=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},si=function(r,e){return function(t,n){e(t,n,r)}},An="PREVIEW_MODELS_FETCH",it=class{settings;secrets;fetchFn;constructor(e,t,n){this.settings=e,this.secrets=t,this.fetchFn=n}async preview(e){let t=e.apiKey?.trim();if(t)return this.lookup(e.type,t);let n=e.instanceId?.trim();if(!n)throw new h("Provide apiKey or instanceId to preview models");let o=(await this.settings.get()).providerInstances?.find(s=>s.id===n);if(!o)throw new y(`Provider instance not found: ${n}`);if(!$t(o)||o.type!==e.type)throw new h(`Provider instance '${n}' is not a ${e.type} agent`);let i=await this.secrets.get(o.secretKey);if(!i)throw new h(`No API key stored for instance '${n}'. Enter a key to fetch models.`);return this.lookup(e.type,i)}async lookup(e,t){try{return await Dc({type:e,apiKey:t,fetchFn:this.fetchFn})}catch(n){throw n instanceof Error&&n.name==="PreviewModelsAuthError"?new h(n.message):new h(n instanceof Error?n.message:"Failed to fetch available models")}}};it=hm([gm(),si(0,ai(P)),si(1,ai(fe)),si(2,ai(An)),ym("design:paramtypes",[P,Function,Function])],it)});import{Module as bm}from"@nestjs/common";var wm,st,Cn=l(()=>{"use strict";wo();gs();Io();Oe();mr();Pe();Ko();Bt();oi();ii();ci();wm=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},st=class{};st=wm([bm({imports:[At,Re],providers:[{provide:F,useFactory:async(r,e)=>{let t=await r.get();return F.fromSettings(t.providerInstances??[],e)},inject:[P,fe]},{provide:er,useClass:Rr},rt,nt,ot,{provide:An,useValue:(r,e)=>fetch(r,e)},it],exports:[F,er,rt,nt,ot,it,An]})],st)});import{Injectable as xm}from"@nestjs/common";var Sm,ye,Tn=l(()=>{"use strict";Sm=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},ye=class{listeners=new Set;emit(e){for(let t of this.listeners)t(e)}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}};ye=Sm([xm()],ye)});import{Global as Im,Module as jm}from"@nestjs/common";var vm,at,On=l(()=>{"use strict";Tn();vm=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},at=class{};at=vm([Im(),jm({providers:[ye],exports:[ye]})],at)});import{Injectable as Pm}from"@nestjs/common";import{execFile as Rm}from"node:child_process";import{mkdirSync as ui,rmSync as km}from"node:fs";import{dirname as Am,join as $n,resolve as Jc}from"node:path";import{promisify as Cm}from"node:util";function Lc(r){return r==null?"":typeof r=="string"?r:r.toString("utf8")}function Uc(r){return $n(r,"worktrees")}function Om(r){let e=[],t;for(let n of r.split(/\r?\n/)){let o=n.trimEnd();if(o===""){t&&e.push(t),t=void 0;continue}if(o.startsWith("worktree ")){t&&e.push(t),t={path:o.slice(9)};continue}if(t&&o.startsWith("branch ")){let i=o.slice(7);t.branch=i.startsWith("refs/heads/")?i.slice(11):i}}return t&&e.push(t),e}var _m,Em,Tm,Fe,li=l(()=>{"use strict";_m=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Em=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},Tm=Cm(Rm),Fe=class{worktreesRoot;constructor(e){this.worktreesRoot=e,ui(this.worktreesRoot,{recursive:!0})}async createWorktree(e,t){let n=t.worktreePath??$n(this.worktreesRoot,e);return ui($n(n,".."),{recursive:!0}),await this.git(t.repoPath,["worktree","add","-b",t.branchName,n,t.baseBranch]),{worktreePath:n,branch:t.branchName}}async addWorktreeForExistingBranch(e){ui($n(e.worktreePath,".."),{recursive:!0});try{await this.git(e.repoPath,["fetch","origin",e.branch])}catch{}let t=await this.existingBranchStartPoint(e.repoPath,e.branch);return t.kind==="local"?await this.git(e.repoPath,["worktree","add",e.worktreePath,e.branch]):await this.git(e.repoPath,["worktree","add","--track","-b",e.branch,e.worktreePath,t.ref]),{worktreePath:e.worktreePath,branch:e.branch}}async listWorktrees(e){let{stdout:t}=await this.git(e,["worktree","list","--porcelain"]);return Om(t)}async resetWorktreeToRemote(e,t){try{await this.git(e,["fetch","origin",t])}catch{}let n=`origin/${t}`;try{await this.git(e,["rev-parse","--verify",n]),await this.git(e,["reset","--hard",n])}catch{await this.git(e,["reset","--hard",t])}await this.git(e,["clean","-fd"])}async removeWorktree(e){let t=Jc(e);try{let{stdout:n}=await this.git(t,["rev-parse","--git-common-dir"]),o=Jc(t,n.trim()),i=o.endsWith(".git")?Am(o):o;await this.git(i,["worktree","remove","--force",t])}catch{km(t,{recursive:!0,force:!0})}}async existingBranchStartPoint(e,t){try{return await this.git(e,["rev-parse","--verify",`refs/heads/${t}`]),{kind:"local"}}catch{let n=`origin/${t}`;return await this.git(e,["rev-parse","--verify",n]),{kind:"remote",ref:n}}}async checkout(e,t){await this.git(e,["checkout",t.branch])}async createBranch(e,t){t.baseBranch?await this.git(e,["checkout","-b",t.branchName,t.baseBranch]):await this.git(e,["checkout","-b",t.branchName])}async commit(e,t){return t.addAll!==!1&&await this.git(e,["add","-A"]),await this.git(e,["commit","-m",t.message]),{sha:(await this.git(e,["rev-parse","HEAD"])).stdout.trim()}}async push(e,t={}){let n=t.remote??"origin";t.branch?await this.git(e,["push",n,t.branch]):await this.git(e,["push",n,"HEAD"])}async git(e,t){try{let n=await Tm("git",t,{cwd:e,encoding:"utf8",windowsHide:!0});return{stdout:n.stdout??"",stderr:n.stderr??""}}catch(n){let o=n,i=Lc(o.stderr),s=Lc(o.stdout),a=i||s||o.message||"unknown git error";throw new Error(`git ${t.join(" ")} failed (cwd=${e}, code=${String(o.code??"?")}): ${a}`)}}};Fe=_m([Pm(),Em("design:paramtypes",[String])],Fe)});import{Module as qm}from"@nestjs/common";import{mkdirSync as Bm}from"node:fs";var $m,Mc,qn,Wc=l(()=>{"use strict";kr();li();$m=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Mc=rr();Bm(Mc,{recursive:!0});qn=class{};qn=$m([qm({providers:[{provide:Fe,useFactory:()=>new Fe(Uc(Mc))}],exports:[Fe]})],qn)});function Ft(r,e){return r.replace(/\{\{\s*([^}]+?)\s*\}\}/g,(t,n)=>{let o=di(e,n.trim());return o==null?"":typeof o=="string"?o:JSON.stringify(o)})}function di(r,e){let t=e.split(".").filter(Boolean),n=r;for(let o of t){if(n==null||typeof n!="object")return;n=n[o]}return n}function Dt(r,e){return typeof r=="string"?Ft(r,e):Array.isArray(r)?r.map(t=>Dt(t,e)):r&&typeof r=="object"?Object.fromEntries(Object.entries(r).map(([t,n])=>[t,Dt(n,e)])):r}var pi=l(()=>{"use strict"});function Vc(r){let e=r.path?.trim()||void 0,t=r.pattern?.trim()||void 0,n=r.source,o=r.source;if(e){if(r.source.trim()==="")return{kind:"no_match",sourceValue:r.source};let i;try{i=JSON.parse(r.source)}catch(a){let u=a instanceof Error?a.message:String(a);throw new Error(`Extract source is not valid JSON (required when path is set): ${u}`)}let s=Dm(i,e);if(n=s??i,s==null)return{kind:"no_match",sourceValue:n};o=s}if(t){let i=Hc(o),s;try{s=new RegExp(t)}catch(c){let p=c instanceof Error?c.message:String(c);throw new Error(`Invalid extract pattern: ${p}`)}let a=i.match(s);return a?{kind:"match",value:a[1]!==void 0?a[1]:a[0],sourceValue:n}:{kind:"no_match",sourceValue:n}}return{kind:"match",value:Hc(o),sourceValue:n}}function Dm(r,e){if(!(r==null||typeof r!="object"))return di(r,e)}function Hc(r){return typeof r=="string"?r:typeof r=="number"||typeof r=="boolean"||typeof r=="bigint"?String(r):r==null?"":JSON.stringify(r)}var Kc=l(()=>{"use strict";pi()});function Gc(r,e){switch(r){case"questionnaire":return fi(e);case"confirmation":return Fm(e);case"conversation":return Nm(e);default:return r}}function fi(r){if(typeof r=="string"&&r.trim())return[r.trim()];if(!r||typeof r!="object")return[];let e=r.questions;return Array.isArray(e)?e.map(t=>typeof t=="string"?t.trim():t&&typeof t=="object"&&"prompt"in t?String(t.prompt).trim():"").filter(Boolean):[]}function Fm(r){if(typeof r=="string"&&r.trim())return[r.trim()];if(!r||typeof r!="object")return[];let e=r;for(let t of["prompt","message","summary","question"]){let n=e[t];if(typeof n=="string"&&n.trim())return[n.trim()]}return"approved"in e&&!("questions"in e)?[]:fi(r)}function Nm(r){if(typeof r=="string"&&r.trim())return[r.trim()];if(!r||typeof r!="object")return[];let e=r;for(let t of["prompt","message","text"]){let n=e[t];if(typeof n=="string"&&n.trim())return[n.trim()]}return"suggestions"in e?[]:"questions"in e?fi(r):[]}var zc=l(()=>{"use strict"});function ct(r,e){for(let t of r){if(t.id===e)return t;if(t.iterations)for(let n of t.iterations){let o=ct(n.stepExecutions,e);if(o)return o}}}function bt(r,e,t,n){for(let o=0;o<r.length;o++){let i=r[o];if(i.id===e)return{execution:i,siblings:r,index:o,parentLoopExecutionId:t,iterationIndex:n};if(i.iterations)for(let s of i.iterations){let a=bt(s.stepExecutions,e,i.id,s.index);if(a)return a}}}function Q(r,e,t){return r.map(n=>n.id===e?t(n):n.iterations?{...n,iterations:n.iterations.map(o=>({...o,stepExecutions:Q(o.stepExecutions,e,t)}))}:n)}function mi(r,e,t,n){return t==null?[...r,e]:r.map(o=>{if(o.id===t){let i=[...o.iterations??[]],s=i.find(a=>a.index===n);if(s){let a={...s,stepExecutions:[...s.stepExecutions,e]},u=i.findIndex(c=>c.index===n);i[u]=a}else{let a={index:n,stepExecutions:[e],startedAt:e.startedAt??new Date().toISOString()};i.push(a),i.sort((u,c)=>u.index-c.index)}return{...o,iterations:i}}return o.iterations?{...o,iterations:o.iterations.map(i=>({...i,stepExecutions:mi(i.stepExecutions,e,t,n)}))}:o})}function Nt(r,e){for(let t of r){if(t.id===e)return t;if(t.type==="loop"){let n=Nt(t.steps,e);if(n)return n}}}function Qc(r,e,t){return Q(r,e,n=>{let o=(n.iterations??[]).map(i=>{if(i.index!==t)return i;let s=i.stepExecutions.every(a=>a.completedAt)?i.stepExecutions.map(a=>a.completedAt).reduce((a,u)=>a>u?a:u):void 0;return{...i,...s?{completedAt:s}:{}}});return{...n,iterations:o}})}function hi(r){let e=[];for(let t of r){t.childJobIds&&e.push(...t.childJobIds);for(let n of t.iterations??[])e.push(...hi(n.stepExecutions))}return e}var Xc=l(()=>{"use strict"});import{z as le}from"zod";function Yc(r,e){let t=Wm[r].safeParse(e);if(!t.success){let n=t.error.issues.map(o=>`${o.path.length?o.path.join("."):"(root)"}: ${o.message}`).join("; ");throw new Error(`Agent output failed validation for format '${r}': ${n}`)}return t.data}var Jm,Lm,Um,Mm,Wm,Zc=l(()=>{"use strict";Jm=le.object({questions:le.array(le.object({id:le.string(),prompt:le.string()}))}),Lm=le.object({approved:le.boolean()}),Um=le.object({suggestions:le.array(le.object({body:le.string()}))}),Mm=le.string(),Wm={questionnaire:Jm,confirmation:Lm,comment_suggestions:Um,free_text:Mm}});function ge(r){return r==="completed"||r==="failed"||r==="cancelled"}function yi(r,e){let t=new Map;for(let o of r){let i=e(o);if(i==null)continue;let s=t.get(i)??[];s.push(o),t.set(i,s)}if(t.size===0)return null;let n=[];for(let o of t.values()){let i=new Set(o.map(a=>a.retryOf).filter(a=>a!=null)),s=o.find(a=>!i.has(a.id));if(!s)return null;n.push(s)}return{activeJobs:n,allTerminal:n.every(o=>ge(o.status)),groupCount:t.size}}function eu(r){let e=r.every(n=>n.status==="completed"),t=r.every(n=>n.status==="failed"||n.status==="cancelled");return e?"completed":t?"failed":"completed_with_issues"}var gi=l(()=>{"use strict"});async function Bn(r,e,t){let n=await e.get(r);if(!n)throw new y(`SubjectView not found: ${r}`);if(!n.providerInstanceId)throw new h(`SubjectView '${r}' has no providerInstanceId \u2014 reconfigure the View to pick a provider instance`);if(n.subjectType==="ticket")return(await t.getTicketProvider(n.providerInstanceId).query(n.query)).map(i=>({subjectType:"ticket",...i}));if(n.subjectType==="pull_request")return(await t.getRepoProvider(n.providerInstanceId).query(n.query)).map(i=>({subjectType:"pull_request",...i}));if(n.subjectType==="documentation")return(await t.getDocumentationProvider(n.providerInstanceId).query(n.query)).map(i=>({subjectType:"documentation",...i}));throw new h(`Unsupported subjectType on view: ${n.subjectType}`)}var wi=l(()=>{"use strict";R()});import{Injectable as Vm}from"@nestjs/common";var Hm,St,bi=l(()=>{"use strict";Hm=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},St=class{requested=new Set;requestCancellation(e){this.requested.add(e)}isCancellationRequested(e){return this.requested.has(e)}clear(e){this.requested.delete(e)}};St=Hm([Vm()],St)});import{Logger as Km}from"@nestjs/common";import{readFile as Gm}from"node:fs/promises";async function tu(r,e,t=new Km("resolveContextFiles"),n=o=>Gm(o,"utf8")){let o=[];for(let i of r){let s=await e.get(i);if(!s){t.warn(`Context file '${i}' is no longer in the catalog; skipping`);continue}try{let a=await n(s.path);o.push({tier:s.tier,content:a,sourceRef:s.path})}catch(a){let u=a instanceof Error?a.message:String(a);throw new Error(`Cannot read context file '${s.name}' at ${s.path}: ${u}`)}}return o}var ru=l(()=>{"use strict"});import{basename as zm,dirname as Qm,join as Xm,resolve as br,sep as nu}from"node:path";function Ym(r){return r.replace(/-/g,"").slice(0,4)}function ou(r,e){return`${r}-${Ym(e)}`}function Si(r){return r.replace(/[\\/:*?"<>|]/g,"-")}function Dn(r){let e=br(r);return Xm(Qm(e),`${zm(e)}-worktrees`)}function Fn(r,e){let t=br(r),n=br(e);if(ut(t,n))return!0;let o=t.endsWith(nu)?t:t+nu,i=process.platform==="win32"?n.toLowerCase():n,s=process.platform==="win32"?o.toLowerCase():o;return i.startsWith(s)}function ut(r,e){let t=br(r),n=br(e);return process.platform==="win32"?t.toLowerCase()===n.toLowerCase():t===n}var xi=l(()=>{"use strict"});import{join as iu}from"node:path";async function su(r,e,t){let n={...e},o=await t.list();for(let i of r){if(i.type!=="localRepository")continue;let s=n[i.name];if(s==null||s==="")continue;let a=String(s),u=o.find(m=>m.id===a),c=o.find(m=>ut(m.localPath,a)),p=u??c;if(!p)throw new h(`Unknown local repository: ${a}`);n[i.name]=p.localPath}return n}async function au(r){let{job:e,params:t,git:n,jobs:o,localRepositories:i}=r,s=Nn(t,"repoPath"),a=t.mode==="existing-branch"?"existing-branch":"new-branch",u=(await i.list()).find(S=>ut(S.localPath,s)),c=u?.worktreeBasePath?.trim()?u.worktreeBasePath.trim():Dn(s);if(Fn(s,c)&&!ut(s,c))throw new Error(`Worktree base '${c}' must not be inside the repository at '${s}'`);if(a==="existing-branch")return Zm({job:e,repoPath:s,branch:Nn(t,"branch"),worktreeBase:c,explicitPath:typeof t.worktreePath=="string"?t.worktreePath:void 0,git:n,jobs:o});let p=Nn(t,"branchName"),m=ou(p,e.id),b=typeof t.worktreePath=="string"&&t.worktreePath.trim()!==""?t.worktreePath:iu(c,Si(m));return n.createWorktree(e.id,{repoPath:s,baseBranch:Nn(t,"baseBranch"),branchName:m,worktreePath:b})}async function Zm(r){let{job:e,repoPath:t,branch:n,worktreeBase:o,git:i,jobs:s}=r,a=await i.listWorktrees(t),u=a.filter(b=>b.branch===n&&!ut(b.path,t)),c=a.find(b=>b.branch===n&&ut(b.path,t));if(u.length===0){if(c)throw new Error(`branch ${n} is checked out in the repository working copy; refusing to reuse the main clone`);let b=r.explicitPath&&r.explicitPath.trim()!==""?r.explicitPath:iu(o,Si(n));return i.addWorktreeForExistingBranch({repoPath:t,branch:n,worktreePath:b})}let p=u[0].path,m=await eh(s,p);if(m&&!ge(m.status))throw new Error(`branch ${n} already has an active worktree in use by Job ${m.id}`);return m&&m.id!==e.id&&await s.update(m.id,{worktreeDeletedAt:new Date().toISOString()}),await i.resetWorktreeToRemote(p,n),{worktreePath:p,branch:n}}async function eh(r,e){let n=(await r.list({liveWorktree:!0})).filter(o=>o.worktreePath!=null&&ut(o.worktreePath,e));return n.find(o=>!ge(o.status))??n.sort((o,i)=>i.updatedAt.localeCompare(o.updatedAt))[0]}function Nn(r,e){let t=r[e];if(typeof t!="string"||t.trim()==="")throw new Error(`git step missing required param '${e}'`);return t}var cu=l(()=>{"use strict";R();xi();gi()});import{Inject as pe,Injectable as nh,Logger as oh}from"@nestjs/common";import{randomUUID as vi}from"node:crypto";import{exec as ih}from"node:child_process";import{promisify as sh}from"node:util";async function Ii(r,e,t){if(r.length===0)throw new Error(t);let n;for(let o of r)try{return await e(o)}catch(i){n=i}throw n instanceof Error?n:new Error(t)}function uu(r,e){let t=e[r.stepId];if(t==null||typeof t!="object")return r.type==="field_empty";let n=t[r.field];return r.type==="field_empty"?n==null?!0:typeof n=="string"||Array.isArray(n)?n.length===0:!1:n===r.value}function uh(r,e){let t=o=>{let i=[];for(let s of o)i.push(s),s.type==="loop"&&i.push(...t(s.steps));return i},n=o=>{let i=o.findIndex(s=>s.id===e);if(i>=0){for(let s=i-1;s>=0;s--)if(o[s].type==="agent")return o[s].id;return}for(let s of o)if(s.type==="loop"){let a=n(s.steps);if(a!==void 0||s.steps.some(u=>u.id===e))return a}};return n(r.steps)}function xt(r){let e={...r.context};return r.subjectContext?.mode==="single"&&(e.subject=r.subjectContext.subject),r.worktreePath&&(e.worktreePath=r.worktreePath),r.branch&&(e.branch=r.branch),e}function lh(r){if(r===null||typeof r!="object"||Array.isArray(r))throw new Error("Extract resume payload must be an object with an action");let e=r;if(e.action==="provide_value"){if(typeof e.value!="string")throw new Error("Extract resume action 'provide_value' requires a string value");return{action:"provide_value",value:e.value}}if(e.action==="continue"||e.action==="cancel")return{action:e.action};throw new Error(`Unknown extract resume action: ${String(e.action)}`)}function Jn(r){if(!r.worktreePath)throw new Error(`Job ${r.id} has no worktreePath; run create_worktree first`);return r.worktreePath}function vt(r,e){let t=r[e];if(typeof t!="string"||t.length===0)throw new Error(`Missing required string param '${e}'`);return t}function dh(r){if(r==="none")throw new Error("normalizeAppliesTo called with none");if(Array.isArray(r)){if(r.length!==1)throw new Error(`Workflow Runner requires appliesTo to be a single SubjectType (got ${JSON.stringify(r)})`);return r[0]}return r}function lu(r,e){for(let t of r)if(t.required&&(e[t.name]===void 0||e[t.name]===null))throw new h(`Missing required input: ${t.name}`)}var th,rh,de,ji,ah,ch,we,Ln=l(()=>{"use strict";mt();pr();Br();qr();Tn();li();Pe();Dr();Fr();Bt();wo();fn();R();pi();Kc();zc();Xc();Zc();gi();wi();bi();ru();cu();th=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},rh=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},de=function(r,e){return function(t,n){e(t,n,r)}},ah=sh(ih),ch=new Set(["agent","shell","git","provider_action"]),we=ji=class{workflows;jobs;batches;views;events;providers;notifications;contextFiles;localRepositories;git;settings;cancellation;logger=new oh(ji.name);childTerminalLocks=new Set;batchTerminalLocks=new Set;constructor(e,t,n,o,i,s,a,u,c,p,m,b){this.workflows=e,this.jobs=t,this.batches=n,this.views=o,this.events=i,this.providers=s,this.notifications=a,this.contextFiles=u,this.localRepositories=c,this.git=p,this.settings=m,this.cancellation=b,this.events.subscribe(S=>{let j=S;(j.type==="job_completed"||j.type==="job_failed"||j.type==="job_cancelled")&&this.onChildTerminal(j.jobId)})}async start(e){let t=await this.createJob(e);return this.emit({type:"job_started",jobId:t.id,timestamp:new Date().toISOString()}),this.runJob(t.id)}async launch(e){let t=await this.requireWorkflow(e.workflowId);if(t.subjectHandling!=="per-subject"&&t.subjectHandling!=="collection")throw new h(`Unsupported subjectHandling: ${String(t.subjectHandling)}`);lu(t.inputSchema,e.inputValues);let n=await this.resolveSelection(e.selection);if(t.subjectHandling==="collection"){let a=await this.createJob({workflowId:t.id,subjectContext:{mode:"collection",subjects:n},selection:e.selection,inputValues:e.inputValues});return this.emit({type:"job_started",jobId:a.id,timestamp:new Date().toISOString()}),this.runJob(a.id)}let o=new Date().toISOString(),i=await this.batches.create({id:vi(),workflowId:t.id,selection:e.selection,resolvedSubjects:n,status:"running",triggeredBy:e.triggeredBy,...e.notificationOverride?{notificationOverride:e.notificationOverride}:{},notificationSent:!1,createdAt:o}),s=[];for(let a=0;a<n.length;a++){let u=n[a],c=await this.createJob({workflowId:t.id,subjectContext:{mode:"single",subject:u},selection:e.selection,batchId:i.id,fanOutIndex:a,inputValues:e.inputValues});s.push(c)}for(let a of s)this.emit({type:"job_started",jobId:a.id,timestamp:new Date().toISOString()}),await this.runJob(a.id);return await this.batches.get(i.id)}async createJob(e){let t=e.workflowSnapshot?structuredClone(e.workflowSnapshot):await this.workflows.get(e.workflowId);if(!t)throw new y(`Workflow not found: ${e.workflowId}`);if(!e.subjectContext&&t.subjectHandling!=="per-subject")throw new h(`Workflow Runner only supports subjectHandling 'per-subject' at start() without an explicit subjectContext (got '${t.subjectHandling}')`);let n=await su(t.inputSchema,e.inputValues,this.localRepositories);lu(t.inputSchema,n);let o=e.subjectContext??await this.resolveSubjectContext(t,e.subjectId),i=new Date().toISOString();return this.jobs.create({id:vi(),workflowId:t.id,status:"pending",...o?{subjectContext:o}:{},...e.selection?{selection:e.selection}:{},...e.batchId?{batchId:e.batchId}:{},...e.parentJobId?{parentJobId:e.parentJobId}:{},...e.parentStepExecutionId?{parentStepExecutionId:e.parentStepExecutionId}:{},...e.fanOutIndex!=null?{fanOutIndex:e.fanOutIndex}:{},...e.retryOf?{retryOf:e.retryOf}:{},workflowSnapshot:structuredClone(t),context:{...n},stepHistory:[],createdAt:i,updatedAt:i})}async deleteWorktrees(e){if(e.length===0)throw new h("jobIds is required");let t=[];for(let s of e){let a=await this.jobs.get(s);if(!a)throw new y(`Job not found: ${s}`);t.push(a)}let n=t.find(s=>!ge(s.status));if(n)throw new J(`Cannot delete worktree for active Job ${n.id}`);let o=new Date().toISOString(),i=[];for(let s of t){s.worktreePath&&!s.worktreeDeletedAt&&await this.git.removeWorktree(s.worktreePath);let a=await this.jobs.update(s.id,{worktreeDeletedAt:o,updatedAt:o});i.push(a)}return i}async runJob(e){let t=await this.jobs.get(e);if(!t)throw new y(`Job not found: ${e}`);if(ge(t.status))return t;let n=await this.workflowForJob(t);if(t.status==="pending"&&(t=await this.persistJob({...t,status:"planning",updatedAt:new Date().toISOString()}),t.status==="cancelled"))return t;let o=await this.executeStepSequence(t,n,n.steps,void 0,void 0,0);return o.outcome!=="completed"?o.job:this.completeJob(o.job,n)}async resume(e,t){let n=await this.jobs.get(e);if(!n)throw new y(`Job not found: ${e}`);if(n.status!=="waiting_for_human")throw new J(`Job ${e} is not waiting for human input (status: ${n.status})`);let o=await this.workflowForJob(n),i=n.currentStepExecutionId;if(!i)throw new Error(`Job ${e} is waiting_for_human but has no currentStepExecutionId`);let s=ct(n.stepHistory,i);if(!s)throw new Error(`Paused execution ${i} not found on job ${e}`);if(s.type==="loop")return this.resumeAskHuman(n,o,s,t);if(s.type==="extract")return this.resumeExtract(n,o,s,t);if(s.type!=="interaction")throw new Error(`Paused execution ${i} has type '${s.type}'; expected interaction, extract, or loop`);let a=new Date().toISOString(),u=Q(n.stepHistory,i,j=>({...j,status:"completed",completedAt:a,output:t})),c=t!==null&&typeof t=="object"&&!Array.isArray(t)?t:{response:t};n=await this.persistJob({...n,status:"planning",context:{...n.context,[s.stepDefinitionId]:t},stepHistory:u,currentStepId:void 0,currentStepExecutionId:void 0,updatedAt:a}),this.emit({type:"human_answered",jobId:n.id,answers:c,timestamp:a});let p=bt(n.stepHistory,i);if(!p)throw new Error(`Could not locate frame for execution ${i}`);let m=this.sequenceForFrameOnJob(n,o,p),b=p.index+1,S=await this.executeStepSequence(n,o,m,p.parentLoopExecutionId,p.iterationIndex,b);return S.outcome!=="completed"?S.job:p.parentLoopExecutionId!=null&&p.iterationIndex!=null?this.continueLoopAfterBody(S.job,o,p.parentLoopExecutionId,p.iterationIndex):this.completeJob(S.job,o)}async retryFailedJob(e){let t=await this.jobs.get(e);if(!t)throw new y(`Job not found: ${e}`);if(t.status!=="failed")throw new J(`Job ${e} is not failed (status: ${t.status})`);let n=t.parentJobId!=null&&t.parentStepExecutionId!=null&&t.fanOutIndex!=null,o=t.batchId!=null&&t.fanOutIndex!=null;if(n){let a=await this.jobs.get(t.parentJobId);if(!a)throw new y(`Parent job not found: ${t.parentJobId}`);let u=await this.createJob({workflowId:t.workflowId,subjectContext:t.subjectContext,inputValues:{},parentJobId:t.parentJobId,parentStepExecutionId:t.parentStepExecutionId,fanOutIndex:t.fanOutIndex,retryOf:t.id,workflowSnapshot:t.workflowSnapshot}),c=Q(a.stepHistory,t.parentStepExecutionId,p=>({...p,status:"waiting_for_children",error:void 0,completedAt:void 0,childJobIds:[...p.childJobIds??[],u.id]}));return a=await this.persistJob({...a,status:"waiting_for_children",stepHistory:c,completedAt:void 0,updatedAt:new Date().toISOString()}),this.emitRetryLaunch(u.id,t.id),this.runJob(u.id),u}if(o){let a=await this.batches.get(t.batchId);if(!a)throw new y(`JobBatch not found: ${t.batchId}`);a.status!=="running"&&await this.batches.update(a.id,{status:"running",completedAt:null,notificationSent:!1});let u=await this.createJob({workflowId:t.workflowId,subjectContext:t.subjectContext,selection:t.selection,batchId:t.batchId,fanOutIndex:t.fanOutIndex,inputValues:{},retryOf:t.id,workflowSnapshot:t.workflowSnapshot});return this.emitRetryLaunch(u.id,t.id),this.runJob(u.id),u}let i=await this.workflowForJob(t),s=await this.createJob({workflowId:t.workflowId,subjectContext:t.subjectContext,selection:t.selection,inputValues:this.inputValuesFromContext(t.context,i),retryOf:t.id,workflowSnapshot:t.workflowSnapshot});return this.emitRetryLaunch(s.id,t.id),this.runJob(s.id),s}async retryFailedStep(e){let t=await this.jobs.get(e);if(!t)throw new y(`Job not found: ${e}`);if(t.status!=="failed")throw new J(`Job ${e} is not failed (status: ${t.status})`);let n=t.currentStepExecutionId;if(!n)throw new J(`Job ${e} has no currentStepExecutionId; cannot retry the failed step`);let o=ct(t.stepHistory,n);if(!o)throw new J(`Job ${e} currentStepExecutionId ${n} was not found in stepHistory`);if(o.type==="sub_workflow")throw new J("Step-level retry is not available for sub_workflow steps. Retry the specific failed child job instead.");if(!ch.has(o.type))throw new J(`Step-level retry is not available for '${o.type}' steps`);let i=await this.workflowForJob(t),s=bt(t.stepHistory,n);if(!s)throw new J(`Could not locate execution frame for ${n} on job ${e}`);let a=this.sequenceForFrameOnJob(t,i,s),u=a[s.index];if(!u||u.id!==o.stepDefinitionId)throw new J(`Failed step '${o.stepDefinitionId}' does not match sequence position ${s.index}`);let c=new Date().toISOString(),p={...t.context};delete p[o.stepDefinitionId];let m=await this.persistJob({...t,status:"planning",context:p,completedAt:void 0,currentStepId:o.stepDefinitionId,currentStepExecutionId:o.id,stepHistory:Q(t.stepHistory,o.id,S=>({...S,status:"running",error:void 0,completedAt:void 0,output:void 0,startedAt:c})),updatedAt:c}),b=await this.executeStepSequence(m,i,a,s.parentLoopExecutionId,s.iterationIndex,s.index,o.id);return b.outcome!=="completed"?b.job:s.parentLoopExecutionId!=null&&s.iterationIndex!=null?this.continueLoopAfterBody(b.job,i,s.parentLoopExecutionId,s.iterationIndex):this.completeJob(b.job,i)}async cancelJob(e){let t=await this.jobs.get(e);if(!t)throw new y(`Job not found: ${e}`);if(ge(t.status))throw new J(`Job ${e} is already terminal (status: ${t.status})`);for(let i of hi(t.stepHistory)){let s=await this.jobs.get(i);s&&!ge(s.status)&&await this.cancelJob(i)}let n=await this.jobs.get(e);if(ge(n.status))return n;this.cancellation.requestCancellation(e);let o=await this.persistCancelled(n);return(n.status==="waiting_for_human"||n.status==="waiting_for_children")&&this.cancellation.clear(e),await this.onBatchMemberTerminal(o.id),o}async cancelBatch(e){let t=await this.batches.get(e);if(!t)throw new y(`JobBatch not found: ${e}`);if(t.status!=="running")throw new J(`JobBatch ${e} is already terminal (status: ${t.status})`);let n=await this.jobs.list({batchId:e});for(let s of n)ge(s.status)||await this.cancelJob(s.id);let o=new Date().toISOString(),i=await this.batches.update(e,{status:"cancelled",completedAt:o});if(!i)throw new Error(`Failed to persist cancelled batch ${e}`);return this.emit({type:"batch_cancelled",batchId:i.id,timestamp:o}),i}async executeStepSequence(e,t,n,o,i,s,a){let u=e;for(let c=s;c<n.length;c++){let p=await this.stopIfCancelled(u);if(p)return{outcome:"cancelled",job:p};let m=n[c],b=new Date().toISOString(),S=c===s?a:void 0,j,N=u.stepHistory;if(S){let A=ct(u.stepHistory,S);if(!A)throw new Error(`Reuse execution ${S} not found on job ${u.id}`);j=A}else j={id:vi(),stepDefinitionId:m.id,type:m.type,status:"running",startedAt:b},N=mi(u.stepHistory,j,o,i);if(u=await this.persistJob({...u,status:u.status==="pending"?"planning":u.status,currentStepId:m.id,currentStepExecutionId:j.id,stepHistory:N,updatedAt:b}),u.status==="cancelled")return{outcome:"cancelled",job:u};this.emit({type:"step_started",jobId:u.id,stepDefinitionId:m.id,timestamp:b});try{let A=await this.dispatchStep(u,t,m,j.id,o,i);u=A.job;let Ke=await this.stopIfCancelled(u);if(Ke)return{outcome:"cancelled",job:Ke};if(A.outcome!=="completed")return A}catch(A){let Ke=await this.failJob(u,t,j.id,m.id,A);return Ke.status==="cancelled"?{outcome:"cancelled",job:Ke}:{outcome:"failed",job:Ke}}}return o!=null&&i!=null&&(u=await this.persistJob({...u,stepHistory:Qc(u.stepHistory,o,i),updatedAt:new Date().toISOString()})),{outcome:"completed",job:u}}async dispatchStep(e,t,n,o,i,s){switch(n.type){case"agent":return{outcome:"completed",job:await this.executeAgentStep(e,n,o)};case"interaction":return{outcome:"paused",job:await this.pauseForInteraction(e,t,n,o)};case"git":return{outcome:"completed",job:await this.executeGitStep(e,n,o)};case"provider_action":return{outcome:"completed",job:await this.executeProviderActionStep(e,n,o)};case"shell":return{outcome:"completed",job:await this.executeShellStep(e,n,o)};case"loop":return this.runLoopStep(e,t,n,o,i,s);case"sub_workflow":return this.runSubWorkflowStep(e,n,o);case"extract":return this.executeExtractStep(e,t,n,o);default:{let a=n;throw new h(`Step type '${a.type}' not yet supported by the Workflow Runner`)}}}async runLoopStep(e,t,n,o,i,s,a=0,u=n.maxIterations){let c=e,p=a;for(;;){if(p>=u)switch(n.onMaxIterations.action){case"fail":return c=await this.failExecution(c,t,o,n.id,`Loop '${n.id}' exceeded maxIterations (${u})`),{outcome:"failed",job:c};case"continue":return c=await this.finishExecution(c,o,n.id,{iterations:p,exitedOnMaxIterations:!0}),{outcome:"completed",job:c};case"ask_human":{let b={maxIterationsCheckpoint:!0,nextIteration:p,effectiveMaxIterations:u},S=new Date().toISOString(),j=Q(c.stepHistory,o,N=>({...N,status:"pending",output:b}));return c=await this.persistJob({...c,status:"waiting_for_human",currentStepId:n.id,currentStepExecutionId:o,stepHistory:j,updatedAt:S}),this.emit({type:"waiting_for_human",jobId:c.id,stepDefinitionId:n.id,interaction:"confirmation",data:b,questions:[`Loop '${n.id}' reached maxIterations (${u}). Extend, continue, or cancel?`],timestamp:S}),t.notificationPolicy.triggers.includes("on_needs_input")&&await this.notifications.send({title:`Input needed: ${t.name}`,body:`Job ${c.id} hit max iterations on loop '${n.id}'`,jobId:c.id}),{outcome:"paused",job:c}}default:{let b=n.onMaxIterations;throw new Error(`Unknown onMaxIterations action: ${JSON.stringify(b)}`)}}let m=await this.executeStepSequence(c,t,n.steps,o,p,0);if(c=m.job,m.outcome!=="completed")return m;if(uu(n.until,c.context))return c=await this.finishExecution(c,o,n.id,{iterations:p+1}),{outcome:"completed",job:c};p+=1}}async resumeAskHuman(e,t,n,o){let i=o,s=n.output;if(!s?.maxIterationsCheckpoint)throw new Error(`Loop execution ${n.id} is not at an ask_human checkpoint`);let a=Nt(t.steps,n.stepDefinitionId);if(!a||a.type!=="loop")throw new Error(`Loop step definition '${n.stepDefinitionId}' not found`);let u=bt(e.stepHistory,n.id),c=new Date().toISOString();if(i.action==="cancel")return await this.failExecution({...e,status:"planning",currentStepId:void 0,currentStepExecutionId:void 0,updatedAt:c},t,n.id,a.id,"Loop cancelled by human at maxIterations checkpoint");if(i.action==="continue"){let j=await this.persistJob({...e,status:"planning",currentStepId:void 0,currentStepExecutionId:void 0,stepHistory:Q(e.stepHistory,n.id,N=>({...N,status:"completed",completedAt:c,output:{iterations:s.nextIteration,exitedOnMaxIterations:!0,humanAction:"continue"}})),updatedAt:c});return this.emit({type:"human_answered",jobId:j.id,answers:i,timestamp:c}),this.emit({type:"step_completed",jobId:j.id,stepDefinitionId:a.id,timestamp:c}),u?.parentLoopExecutionId!=null&&u.iterationIndex!=null?this.continueLoopAfterBody(j,t,u.parentLoopExecutionId,u.iterationIndex):this.continueTopLevelAfter(j,t,a.id)}let p=typeof i.additionalIterations=="number"?i.additionalIterations:0,m=s.effectiveMaxIterations+p,b=await this.persistJob({...e,status:"planning",currentStepId:void 0,currentStepExecutionId:void 0,stepHistory:Q(e.stepHistory,n.id,j=>({...j,status:"running",output:void 0})),updatedAt:c});this.emit({type:"human_answered",jobId:b.id,answers:i,timestamp:c});let S=await this.runLoopStep(b,t,a,n.id,u?.parentLoopExecutionId,u?.iterationIndex,s.nextIteration,m);return S.outcome!=="completed"?S.job:u?.parentLoopExecutionId!=null&&u.iterationIndex!=null?this.continueLoopAfterBody(S.job,t,u.parentLoopExecutionId,u.iterationIndex):this.continueTopLevelAfter(S.job,t,a.id)}async resumeExtract(e,t,n,o){let i=lh(o),s=Nt(t.steps,n.stepDefinitionId);if(!s||s.type!=="extract")throw new Error(`Extract step definition '${n.stepDefinitionId}' not found`);let a=new Date().toISOString();if(i.action==="cancel")return this.failExecution({...e,status:"planning",currentStepId:void 0,currentStepExecutionId:void 0,updatedAt:a},t,n.id,s.id,`Extract '${s.id}' cancelled by human`);let u=i.action==="continue"?"":i.value,c=await this.finishExecution({...e,status:"planning",currentStepId:void 0,currentStepExecutionId:void 0,updatedAt:a},n.id,s.id,u);this.emit({type:"human_answered",jobId:c.id,answers:i,timestamp:a});let p=bt(e.stepHistory,n.id);if(!p)throw new Error(`Could not locate frame for execution ${n.id}`);let m=this.sequenceForFrameOnJob(c,t,p),b=p.index+1,S=await this.executeStepSequence(c,t,m,p.parentLoopExecutionId,p.iterationIndex,b);return S.outcome!=="completed"?S.job:p.parentLoopExecutionId!=null&&p.iterationIndex!=null?this.continueLoopAfterBody(S.job,t,p.parentLoopExecutionId,p.iterationIndex):this.completeJob(S.job,t)}async continueLoopAfterBody(e,t,n,o){let i=ct(e.stepHistory,n);if(!i)throw new Error(`Loop execution ${n} not found`);let s=Nt(t.steps,i.stepDefinitionId);if(!s||s.type!=="loop")throw new Error(`Loop step '${i.stepDefinitionId}' not found`);let a=bt(e.stepHistory,n),u=i.output?.effectiveMaxIterations??s.maxIterations,c=e;if(uu(s.until,c.context))c=await this.finishExecution(c,n,s.id,{iterations:o+1});else{let p=o+1,m=await this.runLoopStep(c,t,s,n,a?.parentLoopExecutionId,a?.iterationIndex,p,u);if(m.outcome!=="completed")return m.job;c=m.job}return a?.parentLoopExecutionId!=null&&a.iterationIndex!=null?this.continueLoopAfterBody(c,t,a.parentLoopExecutionId,a.iterationIndex):this.continueTopLevelAfter(c,t,s.id)}async continueTopLevelAfter(e,t,n){let o=t.steps.findIndex(s=>s.id===n),i=await this.executeStepSequence(e,t,t.steps,void 0,void 0,o+1);return i.outcome!=="completed"?i.job:this.completeJob(i.job,t)}sequenceForFrameOnJob(e,t,n){if(n.parentLoopExecutionId==null)return t.steps;let o=ct(e.stepHistory,n.parentLoopExecutionId);if(!o)throw new Error(`Parent loop execution ${n.parentLoopExecutionId} not found`);let i=Nt(t.steps,o.stepDefinitionId);if(!i||i.type!=="loop")throw new Error(`Parent loop step '${o.stepDefinitionId}' not found`);return i.steps}async runSubWorkflowStep(e,t,n){if(!e.subjectContext||e.subjectContext.mode!=="collection")throw new h(`sub_workflow steps require subjectContext.mode === 'collection' (job ${e.id})`);let o=e.subjectContext.subjects,i=[];for(let p=0;p<o.length;p++){let m=o[p],b=await this.createJob({workflowId:t.workflowId,subjectContext:{mode:"single",subject:m},inputValues:{},parentJobId:e.id,parentStepExecutionId:n,fanOutIndex:p});i.push(b)}let s=i.map(p=>p.id),a=new Date().toISOString(),u=Q(e.stepHistory,n,p=>({...p,status:"waiting_for_children",childJobIds:s})),c=await this.persistJob({...e,status:"waiting_for_children",currentStepId:t.id,currentStepExecutionId:n,stepHistory:u,updatedAt:a});for(let p of i)this.emit({type:"job_started",jobId:p.id,timestamp:a}),this.runJob(p.id);return{outcome:"paused",job:c}}async onChildTerminal(e){let t=await this.jobs.get(e);if(!t?.parentJobId||!t.parentStepExecutionId)return;let n=`${t.parentJobId}:${t.parentStepExecutionId}`;if(!this.childTerminalLocks.has(n)){this.childTerminalLocks.add(n);try{let o=(await this.jobs.list({parentJobId:t.parentJobId,parentStepExecutionId:t.parentStepExecutionId})).filter(A=>A.parentStepExecutionId===t.parentStepExecutionId),i=yi(o,A=>A.fanOutIndex);if(!i?.allTerminal)return;let{activeJobs:s}=i,a=await this.jobs.get(t.parentJobId);if(!a||a.status==="cancelled"||a.status!=="waiting_for_children"&&a.status!=="failed")return;let u=await this.workflowForJob(a),c=t.parentStepExecutionId,p=ct(a.stepHistory,c);if(!p||p.type!=="sub_workflow")return;let m=s.some(A=>A.status==="failed");if(s.some(A=>A.status==="cancelled"))return;if(m){await this.failExecution(a,u,c,p.stepDefinitionId,"One or more child jobs failed");return}let S=s.slice().sort((A,Ke)=>(A.fanOutIndex??0)-(Ke.fanOutIndex??0)).map(A=>({fanOutIndex:A.fanOutIndex,jobId:A.id,output:A.context})),j=new Date().toISOString();a=await this.persistJob({...a,status:"planning",context:{...a.context,[p.stepDefinitionId]:S},currentStepId:void 0,currentStepExecutionId:void 0,stepHistory:Q(a.stepHistory,c,A=>({...A,status:"completed",completedAt:j,output:S})),completedAt:void 0,updatedAt:j}),this.emit({type:"step_completed",jobId:a.id,stepDefinitionId:p.stepDefinitionId,timestamp:j});let N=await this.continueTopLevelAfter(a,u,p.stepDefinitionId)}finally{this.childTerminalLocks.delete(n)}}}async onBatchMemberTerminal(e){let t=await this.jobs.get(e);if(!t?.batchId)return;let n=t.batchId;if(!this.batchTerminalLocks.has(n)){this.batchTerminalLocks.add(n);try{let o=await this.batches.get(t.batchId);if(!o||o.status!=="running")return;let i=await this.jobs.list({batchId:o.id}),s=yi(i,m=>m.fanOutIndex);if(!s||s.groupCount!==o.resolvedSubjects.length||!s.allTerminal)return;let{activeJobs:a}=s,u=eu(a),c=new Date().toISOString(),p=await this.batches.update(o.id,{status:u,completedAt:c});if(!p)return;if(this.emit({type:"batch_completed",batchId:p.id,summary:a.map(m=>({jobId:m.id,status:m.status})),timestamp:c}),!p.notificationSent){let m=await this.workflowForJob(t),b=p.notificationOverride??m.notificationPolicy,S=u==="completed"?"on_complete":"on_fail";b.triggers.includes(S)&&await this.notifications.send({title:`Batch ${u}: ${m.name}`,body:`JobBatch ${p.id} finished with status '${u}' (${a.length} members)`,batchId:p.id}),await this.batches.update(p.id,{notificationSent:!0})}}finally{this.batchTerminalLocks.delete(n)}}}async resolveSelection(e){if(e.mode==="view")return Bn(e.viewId,this.views,this.providers);let t=[];for(let n of e.subjectIds)if(e.subjectType==="ticket"){let o=await this.getTicketById(n);t.push({subjectType:"ticket",...o})}else if(e.subjectType==="pull_request"){let o=await this.getPullRequestById(n);t.push({subjectType:"pull_request",...o})}else if(e.subjectType==="documentation"){let o=await this.getDocumentationById(n);t.push({subjectType:"documentation",...o})}else throw new h(`Unsupported subjectType: ${e.subjectType}`);return t}async executeAgentStep(e,t,n){let o=await tu(t.contextFileIds??[],this.contextFiles,this.logger),i=xt(e),s=Ft(t.objective,i),a=t.agentInstanceId??(await this.settings.get()).defaultAgentInstanceId;if(!a)throw new Error("No default agent instance configured (set EngineSettings.defaultAgentInstanceId)");let u=await this.providers.getAgentProvider(a).run({objective:s,outputFormat:t.outputFormat,knowledge:o,context:{...i,stepId:t.id},...e.worktreePath?{cwd:e.worktreePath}:{}}),c=Yc(t.outputFormat,u.parsed);return this.finishExecution(e,n,t.id,c)}async executeGitStep(e,t,n){let o=Dt(t.params,xt(e));switch(t.operation){case"create_worktree":{let i=await au({job:e,params:o,git:this.git,jobs:this.jobs,localRepositories:this.localRepositories});return this.finishExecution(e,n,t.id,i,{worktreePath:i.worktreePath,branch:i.branch})}case"create_branch":{let i=Jn(e),s=vt(o,"branchName");return await this.git.createBranch(i,{branchName:s,...typeof o.baseBranch=="string"?{baseBranch:o.baseBranch}:{}}),this.finishExecution(e,n,t.id,{branch:s},{branch:s})}case"checkout":{let i=Jn(e),s=vt(o,"branch");return await this.git.checkout(i,{branch:s}),this.finishExecution(e,n,t.id,{branch:s},{branch:s})}case"commit":{let i=Jn(e),s=await this.git.commit(i,{message:vt(o,"message"),addAll:o.addAll!==!1});return this.finishExecution(e,n,t.id,s)}case"push":{let i=Jn(e);return await this.git.push(i,{...typeof o.remote=="string"?{remote:o.remote}:{},...typeof o.branch=="string"?{branch:o.branch}:{}}),this.finishExecution(e,n,t.id,{remote:typeof o.remote=="string"?o.remote:"origin",branch:typeof o.branch=="string"?o.branch:e.branch})}default:{let i=t.operation;throw new Error(`Unknown git operation: ${i}`)}}}async executeProviderActionStep(e,t,n){if(!e.subjectContext||e.subjectContext.mode!=="single")throw new h(`provider_action steps require subjectContext.mode === 'single' (job ${e.id})`);let o=this.resolveProviderActionSubject(e,t);if(t.extendedAction)return this.executeExtendedProviderAction(e,t,n,o);let i=Dt(t.params??{},xt(e))??{},s=await this.dispatchPortableProviderAction(o,t.action,i);return this.finishExecution(e,n,t.id,s)}resolveProviderActionSubject(e,t){if(!t.target){let o=e.subjectContext;if(!o||o.mode!=="single")throw new h(`provider_action steps require subjectContext.mode === 'single' (job ${e.id})`);let i=o.subject;return{subjectType:i.subjectType,source:i.source,subjectId:i.id}}let n=Ft(t.target.subjectId,xt(e)).trim();if(!n)throw new Error(`provider_action '${t.id}' target.subjectId interpolated to an empty id`);return{subjectType:t.target.subjectType,source:t.target.source,subjectId:n}}async dispatchPortableProviderAction(e,t,n){let{subjectType:o,source:i,subjectId:s}=e;if(o==="documentation"){let u=this.providers.getDocumentationProvider(i);switch(t){case"get_subject":return u.get(s);case"get_content":return u.getContent(s);case"get_comments":return u.getComments(s);case"post_comment":return await u.postComment(s,vt(n,"body")),{posted:!0};case"update_status":throw new Error(`Provider action '${t}' is not valid for subject type 'documentation'`);default:{let c=t;throw new Error(`Unknown provider action: ${c}`)}}}let a=o==="ticket"?this.providers.getTicketProvider(i):o==="pull_request"?this.providers.getRepoProvider(i):null;if(!a)throw new Error(`Unsupported subjectType for provider_action: ${o}`);switch(t){case"get_subject":return a.get(s);case"get_comments":return a.getComments(s);case"post_comment":return await a.postComment(s,vt(n,"body")),{posted:!0};case"update_status":return await a.updateStatus(s,vt(n,"status")),{status:vt(n,"status")};case"get_content":throw new Error(`Provider action 'get_content' is not valid for subject type '${o}'`);default:{let u=t;throw new Error(`Unknown provider action: ${u}`)}}}async executeExtendedProviderAction(e,t,n,o){let i=t.extendedAction,s=o.subjectType==="documentation"?this.providers.getDocumentationProvider(i.providerId):o.subjectType==="ticket"?this.providers.getTicketProvider(i.providerId):o.subjectType==="pull_request"?this.providers.getRepoProvider(i.providerId):null;if(!s)throw new Error(`Unsupported subjectType for provider_action: ${o.subjectType}`);if(!oc(s))throw new Error(`Provider instance '${i.providerId}' does not support extended actions. Available: none`);let a=await s.listExtendedActions(),u=a.find(m=>m.actionId===i.actionId);if(!u)throw new Error(`Provider '${i.providerId}' has no extended action '${i.actionId}'. Available: ${qt(a)}`);let c=Dt(i.params??{},xt(e))??{};pn(u,c);let p=await s.executeExtendedAction(i.actionId,{...c,subjectId:o.subjectId});return this.finishExecution(e,n,t.id,p)}async executeShellStep(e,t,n){let o=Ft(t.command,xt(e)),i=e.worktreePath??process.cwd();try{let s=await ah(o,{cwd:i,windowsHide:!0});return this.finishExecution(e,n,t.id,{exitCode:0,stdout:String(s.stdout??""),stderr:String(s.stderr??"")})}catch(s){let a=s,u=a.stderr??"",c=a.stdout??"",p=typeof a.code=="number"?a.code:Number.parseInt(String(a.code??"1"),10)||1;throw new Error(`shell command failed (exit ${p}, cwd=${i}): ${u||c||a.message||o}`)}}async executeExtractStep(e,t,n,o){let i=Ft(n.source,xt(e)),s=Vc({source:i,path:n.path,pattern:n.pattern});if(s.kind==="match")return{outcome:"completed",job:await this.finishExecution(e,o,n.id,s.value)};switch(n.onNoMatch){case"fail":throw new Error(`Extract '${n.id}' did not match`);case"empty":return{outcome:"completed",job:await this.finishExecution(e,o,n.id,"")};case"ask_human":return{outcome:"paused",job:await this.pauseForExtract(e,t,n,o,s.sourceValue)};default:{let a=n.onNoMatch;throw new Error(`Unknown onNoMatch action: ${String(a)}`)}}}async pauseForExtract(e,t,n,o,i){let s=new Date().toISOString(),a=n.pattern?.trim()||void 0,u={extractNoMatch:!0,sourceValue:i,...a?{pattern:a}:{}},c={sourceValue:i,...a?{pattern:a}:{}},p=Q(e.stepHistory,o,b=>({...b,status:"pending",output:u})),m=await this.persistJob({...e,status:"waiting_for_human",currentStepId:n.id,currentStepExecutionId:o,stepHistory:p,updatedAt:s});return this.emit({type:"waiting_for_human",jobId:m.id,stepDefinitionId:n.id,interaction:"confirmation",data:c,questions:[`Extract '${n.id}' did not match. Provide a value, continue with empty, or cancel?`],timestamp:s}),t.notificationPolicy.triggers.includes("on_needs_input")&&await this.notifications.send({title:`Input needed: ${t.name}`,body:`Job ${m.id} needs a value for extract step '${n.id}'`,jobId:m.id}),m}async pauseForInteraction(e,t,n,o){let i=new Date().toISOString(),s=uh(t,n.id),a=s!=null?e.context[s]:void 0,u=Q(e.stepHistory,o,b=>({...b,status:"pending"})),c=await this.persistJob({...e,status:"waiting_for_human",currentStepId:n.id,currentStepExecutionId:o,stepHistory:u,updatedAt:i}),p=Gc(n.interaction,a);return this.emit({type:"waiting_for_human",jobId:c.id,stepDefinitionId:n.id,interaction:n.interaction,data:a,questions:p,timestamp:i}),t.notificationPolicy.triggers.includes("on_needs_input")&&n.notify!==!1&&await this.notifications.send({title:`Input needed: ${t.name}`,body:`Job ${c.id} is waiting for human input on step '${n.id}'`,jobId:c.id}),c}async finishExecution(e,t,n,o,i={}){let s=new Date().toISOString(),a=Q(e.stepHistory,t,c=>({...c,status:"completed",completedAt:s,output:o})),u=await this.persistJob({...e,...i,context:{...e.context,[n]:o},stepHistory:a,updatedAt:s});return this.emit({type:"step_completed",jobId:u.id,stepDefinitionId:n,timestamp:s}),u}async failExecution(e,t,n,o,i){return this.failJob(e,t,n,o,new Error(i))}async completeJob(e,t){let n=new Date().toISOString(),o=await this.persistJob({...e,status:"completed",currentStepId:void 0,currentStepExecutionId:void 0,completedAt:n,updatedAt:n});return o.status==="cancelled"||(this.emit({type:"job_completed",jobId:o.id,timestamp:n}),await this.onBatchMemberTerminal(o.id),!o.batchId&&t.notificationPolicy.triggers.includes("on_complete")&&await this.notifications.send({title:`Job completed: ${t.name}`,body:`Job ${o.id} completed successfully`,jobId:o.id})),o}async failJob(e,t,n,o,i){let s=i instanceof Error?i.message:String(i),a=new Date().toISOString(),u=Q(e.stepHistory,n,p=>({...p,status:"failed",completedAt:a,error:s})),c=await this.persistJob({...e,status:"failed",currentStepId:o,currentStepExecutionId:n,stepHistory:u,completedAt:a,updatedAt:a});return this.emit({type:"step_failed",jobId:c.id,stepDefinitionId:o,error:s,timestamp:a}),c.status==="cancelled"?(await this.onBatchMemberTerminal(c.id),c):(this.emit({type:"job_failed",jobId:c.id,error:s,timestamp:a}),await this.onBatchMemberTerminal(c.id),!c.batchId&&t.notificationPolicy.triggers.includes("on_fail")&&await this.notifications.send({title:`Job failed: ${t.name}`,body:`Job ${c.id} failed on step '${o}': ${s}`,jobId:c.id}),c)}async resolveSubjectContext(e,t){if(e.appliesTo==="none")return;let n=dh(e.appliesTo);if(!t)throw new Error(`Workflow '${e.id}' applies to '${n}' but no subjectId was provided`);if(n==="ticket")return{mode:"single",subject:{subjectType:"ticket",...await this.getTicketById(t)}};if(n==="pull_request")return{mode:"single",subject:{subjectType:"pull_request",...await this.getPullRequestById(t)}};if(n==="documentation")return{mode:"single",subject:{subjectType:"documentation",...await this.getDocumentationById(t)}};throw new Error(`Unsupported subjectType for workflow subject resolution: ${n}`)}async workflowForJob(e){return e.workflowSnapshot?e.workflowSnapshot:(this.logger.warn(`Job ${e.id} has no workflowSnapshot; falling back to live WorkflowDefinition ${e.workflowId}`),this.requireWorkflow(e.workflowId))}async requireWorkflow(e){let t=await this.workflows.get(e);if(!t)throw new y(`Workflow not found: ${e}`);return t}emitRetryLaunch(e,t){let n=new Date().toISOString();this.emit({type:"job_started",jobId:e,timestamp:n}),this.emit({type:"job_retried",jobId:e,retryOf:t,timestamp:n})}inputValuesFromContext(e,t){let n={};for(let o of t.inputSchema)Object.prototype.hasOwnProperty.call(e,o.name)&&(n[o.name]=e[o.name]);return n}async persistCancelled(e){let t=new Date().toISOString();return this.persistJob({...e,status:"cancelled",completedAt:e.completedAt??t,updatedAt:t})}async stopIfCancelled(e){return!this.cancellation.isCancellationRequested(e.id)&&e.status!=="cancelled"&&(await this.jobs.get(e.id))?.status!=="cancelled"?null:(this.cancellation.clear(e.id),e.status==="cancelled"?e:this.persistCancelled(e))}async persistJob(e){let t=await this.jobs.get(e.id),n=this.cancellation.isCancellationRequested(e.id)||t?.status==="cancelled"||e.status==="cancelled",o=n?"cancelled":e.status,i=n?t?.completedAt??e.completedAt??e.updatedAt:e.completedAt,s=await this.jobs.update(e.id,{status:o,context:e.context,currentStepId:e.currentStepId,currentStepExecutionId:e.currentStepExecutionId,stepHistory:e.stepHistory,worktreePath:e.worktreePath,branch:e.branch,updatedAt:e.updatedAt,completedAt:i});if(!s)throw new Error(`Failed to persist job ${e.id}`);return t?.status!=="cancelled"&&s.status==="cancelled"&&this.emit({type:"job_cancelled",jobId:s.id,timestamp:s.updatedAt}),s}emit(e){this.events.emit(e)}async getTicketById(e){return Ii(this.providers.ticketInstanceIds(),t=>this.providers.getTicketProvider(t).get(e),`Ticket not found: ${e}`)}async getPullRequestById(e){return Ii(this.providers.repoInstanceIds(),t=>this.providers.getRepoProvider(t).get(e),`Pull request not found: ${e}`)}async getDocumentationById(e){return Ii(this.providers.documentationInstanceIds(),t=>this.providers.getDocumentationProvider(t).get(e),`Documentation page not found: ${e}`)}};we=ji=th([nh(),de(0,pe(O)),de(1,pe(z)),de(2,pe(se)),de(3,pe(ie)),de(4,pe(ye)),de(5,pe(F)),de(6,pe(er)),de(7,pe(ae)),de(8,pe(ce)),de(9,pe(Fe)),de(10,pe(P)),de(11,pe(St)),rh("design:paramtypes",[O,z,se,ie,ye,F,Object,ae,ce,Fe,Object,St])],we)});import{Module as fh}from"@nestjs/common";var ph,Jt,_i=l(()=>{"use strict";mr();Cn();On();Wc();Ln();bi();ph=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Jt=class{};Jt=ph([fh({imports:[Re,st,at,qn],providers:[St,we],exports:[we]})],Jt)});import{Catch as hh}from"@nestjs/common";var mh,Un,du=l(()=>{"use strict";R();mh=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Un=class{catch(e,t){t.switchToHttp().getResponse().status(e.httpStatus).json({error:e.message})}};Un=mh([hh(wt)],Un)});var v,ne=l(()=>{"use strict";R();v=class{schema;constructor(e){this.schema=e}transform(e){let t=this.schema.safeParse(e);if(!t.success){let n=t.error.issues.map(o=>`${o.path.join(".")||"(root)"}: ${o.message}`).join("; ");throw new h(`Validation failed: ${n}`)}return t.data}}});import{randomUUID as yh}from"node:crypto";function gh(){return yh()}function Mn(r){let e=r.id??gh(),t=ca(r.steps),n=pu(r.steps,t);return{...r,id:e,steps:n}}function pu(r,e){return r.map(t=>{let n=t.id;return n||(n=ia(t.name,e),e.add(n)),t.type==="loop"?{...t,id:n,steps:pu(t.steps,e)}:{...t,id:n}})}var Ei=l(()=>{"use strict";C()});function fu(r,e,t){if(!r)throw new y(`Workflow not found: ${e}`);if(r.appliesTo==="none")throw new h(`Cannot bind a View to workflow '${e}' because appliesTo is 'none'`);if(!ja(r.appliesTo,t))throw new h(`subjectType '${t}' is not included in workflow '${e}' appliesTo`);return r}function mu(r,e){if(!r)throw new y(`Workflow not found: ${e}`);if(r.appliesTo!=="none")throw new h(`WorkflowShortcut requires appliesTo 'none', got '${String(r.appliesTo)}'`);if(r.subjectHandling!=="per-subject")throw new h(`WorkflowShortcut requires subjectHandling 'per-subject', got '${r.subjectHandling}'`);return r}function Wn(r){if(r.appliesTo==="none"&&r.subjectHandling==="collection")throw new h("Workflows with appliesTo 'none' must use subjectHandling 'per-subject'")}var Sr=l(()=>{"use strict";C();R()});function hu(r){return r.issues.map(e=>`${e.path.join(".")||"(root)"}: ${e.message}`).join("; ")}async function Hn(r,e){let t=tt.safeParse(e);if(!t.success)throw new h(`Validation failed: ${hu(t.error)}`);let n=Mn(t.data),o=ht.safeParse(n);if(!o.success)throw new h(`Validation failed: ${hu(o.error)}`);return Wn(o.data),r.create(o.data)}var Pi=l(()=>{"use strict";C();R();Sr();Ei()});import{Body as yu,Controller as wh,Delete as bh,Get as gu,HttpCode as Sh,Inject as xh,Param as Ri,Patch as vh,Post as Ih,Query as jh}from"@nestjs/common";var Lt,U,It,Ne,wu=l(()=>{"use strict";C();mt();R();ne();Ei();Pi();Sr();Lt=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},U=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},It=function(r,e){return function(t,n){e(t,n,r)}},Ne=class{workflows;constructor(e){this.workflows=e}async list(e){if(e!=null&&e!==""&&e!=="per-subject"&&e!=="collection")throw new h(`Invalid subjectHandling filter: ${e}`);return this.workflows.list(e?{subjectHandling:e}:{})}async get(e){let t=await this.workflows.get(e);if(!t)throw new y(`Workflow not found: ${e}`);return t}async create(e){return Hn(this.workflows,e)}async update(e,t){let n=Mn({...t,id:e}),o=ht.safeParse(n);if(!o.success){let u=o.error.issues.map(c=>`${c.path.join(".")||"(root)"}: ${c.message}`).join("; ");throw new h(`Validation failed: ${u}`)}Wn(o.data);let{id:i,...s}=o.data,a=await this.workflows.update(e,s);if(!a)throw new y(`Workflow not found: ${e}`);return a}async remove(e){if(!await this.workflows.get(e))throw new y(`Workflow not found: ${e}`);if(!await this.workflows.delete(e))throw new y(`Workflow not found: ${e}`)}};Lt([gu(),It(0,jh("subjectHandling")),U("design:type",Function),U("design:paramtypes",[String]),U("design:returntype",Promise)],Ne.prototype,"list",null);Lt([gu(":id"),It(0,Ri("id")),U("design:type",Function),U("design:paramtypes",[String]),U("design:returntype",Promise)],Ne.prototype,"get",null);Lt([Ih(),It(0,yu()),U("design:type",Function),U("design:paramtypes",[Object]),U("design:returntype",Promise)],Ne.prototype,"create",null);Lt([vh(":id"),It(0,Ri("id")),It(1,yu(new v(tt))),U("design:type",Function),U("design:paramtypes",[String,Object]),U("design:returntype",Promise)],Ne.prototype,"update",null);Lt([bh(":id"),Sh(204),It(0,Ri("id")),U("design:type",Function),U("design:paramtypes",[String]),U("design:returntype",Promise)],Ne.prototype,"remove",null);Ne=Lt([wh("workflows"),It(0,xh(O)),U("design:paramtypes",[O])],Ne)});function _h(r){return Su(r.workflowDefinition.steps,"steps")}function bu(r){let e=_h(r);if(e.length>0)throw new Error(`Workflow library entry '${r.id}' is not portable: ${e.join(", ")}`)}function Su(r,e){let t=[];return r.forEach((n,o)=>{let i=`${e}[${o}]`;n.type==="provider_action"&&(n.target&&t.push(`${i}.target`),n.extendedAction&&t.push(`${i}.extendedAction`)),n.type==="loop"&&t.push(...Su(n.steps,`${i}.steps`))}),t}var xu=l(()=>{"use strict"});function vu(){return structuredClone(ki)}function Iu(r){let e=ki.find(t=>t.id===r);return e?structuredClone(e):void 0}var Eh,Ph,ki,ju=l(()=>{"use strict";xu();Eh={id:"clarify-then-summarize",source:"example",name:"Clarify then summarize",description:"Asks clarifying questions in a loop until none remain, then summarizes the answers.",workflowDefinition:{name:"Clarify then summarize",description:"Asks clarifying questions in a loop until none remain, then summarizes the answers.",appliesTo:"none",subjectHandling:"per-subject",inputSchema:[{name:"topic",label:"Topic",type:"string",required:!0}],steps:[{type:"loop",name:"Clarify",steps:[{type:"agent",name:"Draft questions",objective:"Draft clarifying questions about {{topic}}. If you have no remaining questions, return an empty list.",outputFormat:"questionnaire"},{type:"interaction",name:"Collect answers",interaction:"questionnaire"}],until:{type:"field_empty",stepId:"draft-questions",field:"questions"},maxIterations:5,onMaxIterations:{action:"continue"}},{type:"agent",name:"Summarize",objective:"Produce a final summary for {{topic}} using these answers: {{collect-answers}}",outputFormat:"free_text"}],notificationPolicy:{triggers:["on_needs_input","on_complete","on_fail"]}}},Ph={id:"pr-review",source:"example",name:"PR Review",description:"Reviews a pull request for acceptance criteria, code quality, and test coverage.",workflowDefinition:{name:"PR Review",description:"Reviews a pull request for acceptance criteria, code quality, and test coverage.",appliesTo:"pull_request",subjectHandling:"per-subject",inputSchema:[{name:"repoPath",label:"Repository path",type:"localRepository",required:!0},{name:"ticketDescription",label:"Related ticket description (optional)",type:"string",required:!1}],steps:[{type:"git",name:"Prepare review worktree",operation:"create_worktree",params:{repoPath:"{{repoPath}}",baseBranch:"{{subject.sourceBranch}}",branchName:"review/{{subject.id}}"}},{type:"agent",name:"Build requirements checklist",objective:`Ticket: {{ticketDescription}}
20
+ `)}function En(n,e){return e==="free_text"?n:Cc(n)}function Cc(n){let e=[...n.matchAll(/```json\s*([\s\S]*?)```/gi)].map(o=>o[1].trim()),t=[...n.matchAll(/```\s*([\s\S]*?)```/g)].map(o=>o[1].trim()),r=[...e].reverse();r.length===0&&r.push(...[...t].reverse()),r.push(n.trim());for(let o of r)if(o)try{return JSON.parse(o)}catch{continue}throw new Error("No valid JSON block found in agent response")}var om,im,sm,am,wr=l(()=>{"use strict";Fe();om={user:"User preferences",organization:"Organization guidelines",project:"Project context"},im=["user","organization","project"],sm={questionnaire:'Respond with a single fenced JSON block matching this shape exactly: {"questions":[{"id":"<string>","prompt":"<string>"}]}. No other prose outside the fence.',confirmation:'Respond with a single fenced JSON block matching this shape exactly: {"approved":<boolean>}. No other prose outside the fence.',comment_suggestions:'Respond with a single fenced JSON block matching this shape exactly: {"suggestions":[{"id":"<string>","file":"<string>","line":<number>,"body":"<string>"}]}. No other prose outside the fence.',free_text:"Respond in plain text. Do not wrap the answer in a JSON object."},am={anthropic:"Anthropic",cursor:"Cursor"}});async function*um(n){let{query:e}=await import("@anthropic-ai/claude-agent-sdk"),t=n.options;yield*e({prompt:n.prompt,options:{permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,...t?.cwd?{cwd:t.cwd}:{},...t?.resume?{resume:t.resume}:{},...t?.model?{model:t.model}:{},...t?.env?{env:t.env}:{}}})}var cm,br,Tc=l(()=>{"use strict";wr();Fe();wr();cm=Bt("anthropic"),br=class{secrets;options;constructor(e,t={}){this.secrets=e,this.options=t}async run(e){let t=await this.requireApiKey(),r=In(e),o={permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,env:{...process.env,ANTHROPIC_API_KEY:t}};e.cwd&&(o.cwd=e.cwd),e.sessionId&&(o.resume=e.sessionId),this.options.model&&(o.model=this.options.model);let i=this.options.queryFn??um,s,a,u;for await(let c of i({prompt:r,options:o}))c.session_id&&(s=c.session_id),c.type==="result"&&(c.subtype==="success"&&typeof c.result=="string"?a=c.result:u=c.errors?.join("; ")||c.subtype||"Claude agent returned an error result");if(u)throw new Error(`Claude agent failed: ${u}`);if(a==null)throw new Error("Claude agent returned no result text");if(!s)throw new Error("Claude agent returned no session id");return{raw:a,parsed:En(a,e.outputFormat),sessionId:s}}async requireApiKey(){let e=this.options.secretKey?.trim()||cm,t=await this.secrets.get(e);if(!t)throw yr("anthropic",e);return t}}});function dm(n,e,t){return{apiKey:n,...t?{model:{id:t}}:{},local:{...e?{cwd:e}:{},settingSources:[]}}}async function pm(){let{Agent:n}=await import("@cursor/sdk");return{create:e=>n.create({apiKey:e.apiKey,...e.model?{model:e.model}:{},local:{...e.local?.cwd?{cwd:e.local.cwd}:{},settingSources:[]}}),resume:(e,t)=>n.resume(e,{apiKey:t.apiKey,...t.model?{model:t.model}:{},local:{...t.local?.cwd?{cwd:t.local.cwd}:{},settingSources:[]}})}}var lm,Sr,Oc=l(()=>{"use strict";wr();Fe();lm=Bt("cursor"),Sr=class{secrets;options;constructor(e,t={}){this.secrets=e,this.options=t}async run(e){let t=await this.requireApiKey(),r=In(e),o=this.options.sdk??await pm(),i=dm(t,e.cwd,this.options.model),s=e.sessionId?await o.resume(e.sessionId,i):await o.create(i);try{let u=await(await s.send(r)).wait();if(u.status!=="finished")throw new Error(u.error?.message||`Cursor agent ended with status '${u.status}'`);let c=u.result??"";return{raw:c,parsed:En(c,e.outputFormat),sessionId:s.agentId}}finally{await s[Symbol.asyncDispose]?.()}}async requireApiKey(){let e=this.options.secretKey?.trim()||lm,t=await this.secrets.get(e);if(!t)throw yr("cursor",e);return t}}});function $c(n){return typeof n=="object"&&n!=null&&typeof n.listExtendedActions=="function"&&typeof n.executeExtendedAction=="function"}function xr(n,e){let t=n.params.filter(r=>r.required).filter(r=>{let o=e[r.name];return o==null||typeof o=="string"&&o.trim()===""}).map(r=>r.name);if(t.length>0)throw new Error(`Extended action '${n.actionId}' is missing required params: ${t.join(", ")}`)}function Lt(n){return n.length===0?"none":n.map(e=>e.actionId).join(", ")}var vr=l(()=>{"use strict"});function Pn(n){return n==null?"":typeof n=="string"?n:qc(n).replace(/\n+$/,"")}function jr(n){return{version:1,type:"doc",content:n.split(`
21
+ `).map(t=>({type:"paragraph",content:t.length===0?[]:[{type:"text",text:t}]}))}}function qc(n){if(n==null||typeof n!="object")return"";let e=n;if(e.type==="text")return e.text??"";if(e.type==="hardBreak")return`
22
+ `;let t=(e.content??[]).map(qc).join("");return e.type==="paragraph"||e.type==="heading"||e.type==="blockquote"||e.type==="listItem"?`${t}
23
+ `:t}var fi=l(()=>{"use strict"});function gm(n,e){return e.startsWith("http://")||e.startsWith("https://")?e:`${n.replace(/\/$/,"")}${e.startsWith("/")?e:`/${e}`}`}function Bc(n){return{representation:"atlas_doc_format",value:JSON.stringify(jr(n))}}function Nc(n){return Pn(ym(n))}function ym(n){if(n==null||typeof n!="object")return n;let e=n.atlas_doc_format;if(e!=null){if(typeof e=="object"&&e!==null&&"value"in e){let t=e.value;if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t}return e}}function Fc(n,e,t){return{id:String(n.id??""),source:t,title:String(n.title??""),url:wm(e,n),raw:n}}function wm(n,e){let t=n.replace(/\/$/,""),r=e._links?.webui?.trim();if(r)return r.startsWith("http://")||r.startsWith("https://")?r:r.startsWith("/wiki")?`${t}${r}`:`${t}/wiki${r.startsWith("/")?r:`/${r}`}`;let o=e.id!=null?String(e.id):"";return o?`${t}/wiki/pages/${encodeURIComponent(o)}`:t}function bm(n,e){return{id:String(n.id??""),subjectId:e,body:Nc(n.body),createdAt:n.version?.createdAt??n.createdAt??"",raw:n}}var fm,mm,hm,Dc,_r,Ir,mi=l(()=>{"use strict";vr();fi();fm="kno.confluence.apiToken",mm=50,hm=10,Dc=500,_r=[{actionId:"create_page",label:"Create Confluence page",params:[{name:"spaceKey",label:"Space key",type:"string",required:!0},{name:"title",label:"Title",type:"string",required:!0},{name:"content",label:"Content",type:"string",required:!0}]}],Ir=class{secrets;fetchFn;instanceId;baseUrl;email;secretKey;constructor(e,t,r=fetch){this.secrets=e,this.fetchFn=r,this.instanceId=t.instanceId,this.baseUrl=t.baseUrl?.trim()||void 0,this.email=t.email?.trim()||void 0,this.secretKey=t.secretKey?.trim()||fm}async get(e){let{baseUrl:t}=await this.requireConfig(),r=await this.request("GET",`/wiki/api/v2/pages/${encodeURIComponent(e)}`);return Fc(r,t,this.instanceId)}async getContent(e){await this.requireConfig();let t=await this.request("GET",`/wiki/api/v2/pages/${encodeURIComponent(e)}?body-format=atlas_doc_format`);return Nc(t.body)}async query(e){let t=e.pageIds;if(!Array.isArray(t))throw new Error("Documentation query requires { pageIds: string[] }");let r=[];for(let o of t)r.push(await this.get(String(o)));return r}async getComments(e){await this.requireConfig();let t=[],r=`/wiki/api/v2/pages/${encodeURIComponent(e)}/footer-comments?body-format=atlas_doc_format&limit=${mm}`,o=new Set;for(let i=0;i<hm&&t.length<Dc&&!(!r||o.has(r));i++){o.add(r);let s=await this.request("GET",r),a=Array.isArray(s.results)?s.results:[];for(let c of a){if(t.length>=Dc)break;t.push(bm(c,e))}let u=typeof s._links?.next=="string"?s._links.next:void 0;if(!u||a.length===0)break;r=u}return t}async postComment(e,t){await this.requireConfig(),await this.request("POST","/wiki/api/v2/footer-comments",{body:{pageId:e,body:Bc(t)}})}listExtendedActions(){return _r}async executeExtendedAction(e,t){if(e==="create_page")return this.createPage(t);throw new Error(`Provider 'confluence' has no extended action '${e}'. Available: ${Lt(this.listExtendedActions())}`)}async createPage(e){let t=_r[0];xr(t,e);let r=String(e.spaceKey).trim(),o=String(e.title).trim(),i=String(e.content),{baseUrl:s}=await this.requireConfig(),a=await this.resolveSpaceId(r),u=await this.request("POST","/wiki/api/v2/pages",{body:{spaceId:a,status:"current",title:o,body:Bc(i)}});return Fc(u,s,this.instanceId)}async resolveSpaceId(e){let t=await this.request("GET",`/wiki/api/v2/spaces?keys=${encodeURIComponent(e)}`),r=Array.isArray(t.results)?t.results:[],o=r.find(s=>(s.key??"").toLowerCase()===e.toLowerCase())??r[0],i=o?.id!=null?String(o.id):"";if(!i)throw new Error(`Confluence space '${e}' was not found`);return i}async requireConfig(){let e=this.baseUrl,t=this.email,r=await this.secrets.get(this.secretKey);if(!e||!t||!r){let o=[];throw e||o.push("config.baseUrl"),t||o.push("config.email"),r||o.push(`SecretStore '${this.secretKey}'`),new Error(`Confluence instance '${this.instanceId}' is not configured \u2014 missing ${o.join(", ")}. Set baseUrl and email on the provider instance, and store the API token with: POST /api/secrets/${this.secretKey} or npm --workspace apps/engine run set-secret -- ${this.secretKey} <value>`)}return{baseUrl:e,email:t,token:r}}async request(e,t,r={}){let{baseUrl:o,email:i,token:s}=await this.requireConfig(),a=gm(o,t),u={Authorization:`Basic ${Buffer.from(`${i}:${s}`).toString("base64")}`,Accept:"application/json"};r.body!==void 0&&(u["Content-Type"]="application/json");let c=await this.fetchFn(a,{method:e,headers:u,...r.body!==void 0?{body:JSON.stringify(r.body)}:{}});if(!c.ok){let m=await c.text().catch(()=>"");throw new Error(`Confluence ${e} ${t} failed (${c.status}): ${m||c.statusText}`)}if(c.status===204)return;let d=await c.text();if(d)return JSON.parse(d)}}});import{randomUUID as Sm}from"node:crypto";var xm,Er,Jc=l(()=>{"use strict";xm=new Set(["github_wiki","gitlab_wiki","azure_wiki","web"]),Er=class{pages;contentById;comments;instanceId;type;constructor(e=[],t){this.pages=new Map,this.contentById=new Map,this.comments=new Map,this.instanceId=t?.instanceId,this.type=t?.type;for(let r of e){let{content:o,...i}=r;this.pages.set(i.id,structuredClone(i)),o!==void 0&&this.contentById.set(i.id,o)}}async get(e){let t=this.pages.get(e);if(!t)throw new Error(`Documentation page not found: ${e}`);return this.withSource(structuredClone(t))}async getContent(e){await this.get(e);let t=this.contentById.get(e);if(t===void 0)throw new Error(`Documentation content not found: ${e}`);return t}async query(e){let t=e.pageIds;if(!Array.isArray(t))throw new Error("Documentation query requires { pageIds: string[] }");let r=[];for(let o of t)r.push(await this.get(String(o)));return r}async getComments(e){let t=await this.get(e);return this.assertCommentsSupported(t),structuredClone(this.comments.get(e)??[])}async postComment(e,t){let r=await this.get(e);this.assertCommentsSupported(r);let o=this.comments.get(e)??[];o.push({id:Sm(),subjectId:e,body:t,createdAt:new Date().toISOString()}),this.comments.set(e,o)}assertCommentsSupported(e){let t=this.type??e.source;if(xm.has(t))throw new Error(`Comments are not supported for documentation source '${t}'`)}withSource(e){return this.instanceId?{...e,source:this.instanceId}:e}}});function hi(){return jm.replace(/\/$/,"")}function Ut(n){let e=n.trim(),t=e.lastIndexOf("#");if(t<=0||t===e.length-1)throw new Error(`Bitbucket pull request id must be '{repoSlug}#{prNumber}' (e.g. 'kno-engine#42'), got '${n}'`);let r=e.slice(0,t),o=e.slice(t+1);if(!/^\d+$/.test(o))throw new Error(`Bitbucket pull request id must be '{repoSlug}#{prNumber}' with a numeric PR number, got '${n}'`);return{repoSlug:r,prNumber:o}}function _m(n,e){return`${n}#${e}`}function Im(n){let e=n.repoSlug;if(typeof e!="string"||e.trim().length===0)throw new Error("Bitbucket query requires filter.repoSlug or filter.role \u2014 repo-scoped listing needs repoSlug; workspace-wide listing needs role (author|reviewer)");return e.trim()}function Em(n){if(typeof n.repoSlug=="string"&&n.repoSlug.trim().length>0||!Mc(n.role))return;let e=String(n.role).trim().toLowerCase();if(e!=="author"&&e!=="reviewer")throw new Error(`Bitbucket query filter.role must be 'author' or 'reviewer', got '${String(n.role)}'`);return e}function Uc(n){if(!Mc(n))return;let e=String(n).trim().toUpperCase();if(e!=="OPEN"&&e!=="MERGED"&&e!=="DECLINED")throw new Error(`Bitbucket query filter.state must be OPEN, MERGED, or DECLINED, got '${String(n)}'`);return e}function Pm(n){if(typeof n.q=="string"&&n.q.trim().length>0)return n.q;let e=Uc(n.state);if(e)return`state="${e}"`}function Rm(n){let e=n.destination?.repository?.name;if(typeof e=="string"&&e.trim().length>0)return e.trim();let t=n.destination?.repository?.full_name;if(typeof t=="string"&&t.includes("/"))return t.slice(t.lastIndexOf("/")+1);throw new Error("Bitbucket workspace pull request is missing destination.repository slug")}function km(n){let e=n.trim().toLowerCase();if(e==="approved")return"approve";if(e==="declined"||e==="rejected")return"decline";if(e==="merged")return"merge";throw new Error(`No Bitbucket action for status '${n}'. Accepted: approved, declined/rejected, merged`)}function Mc(n){return n!=null&&n!==""}function wi(...n){for(let e of n)if(typeof e=="string"&&e.trim().length>0)return e.trim()}function Pr(n,e,t){let r=String(n.id??""),o=typeof n.description=="string"?n.description:"";return{id:_m(e,r),source:t,title:String(n.title??""),...o?{description:o}:{},sourceBranch:String(n.source?.branch?.name??""),targetBranch:String(n.destination?.branch?.name??""),...n.author?.display_name?{author:n.author.display_name}:{},...n.links?.html?.href?{url:n.links.html.href}:{},raw:n}}function Am(n,e){let t=n.user?.display_name??n.author?.display_name;return{id:String(n.id??""),subjectId:e,body:n.content?.raw??"",...t?{author:t}:{},createdAt:n.created_on??"",raw:n}}var vm,jm,gi,Lc,yi,bi,Rr,Si=l(()=>{"use strict";vr();vm="kno.bitbucket.apiToken",jm="https://api.bitbucket.org/2.0";gi=50,Lc=10,yi=500,bi=[{actionId:"add_reviewer",label:"Add reviewer",params:[{name:"username",label:"Reviewer username",type:"string",required:!0}]}],Rr=class{secrets;fetchFn;instanceId;email;workspace;secretKey;constructor(e,t,r=fetch){this.secrets=e,this.fetchFn=r,this.instanceId=t.instanceId,this.email=t.email?.trim()||void 0,this.workspace=t.workspace?.trim()||void 0,this.secretKey=t.secretKey?.trim()||vm}async get(e){let{repoSlug:t,prNumber:r}=Ut(e),{workspace:o}=await this.requireConfig(),i=await this.request("GET",this.prPath(o,t,r));return Pr(i,t,this.instanceId)}async query(e){let t=Em(e);if(t)return this.queryWorkspacePullRequests(t,e);let r=Im(e),{workspace:o}=await this.requireConfig(),i=Pm(e),s=new URLSearchParams({pagelen:String(gi)});i&&s.set("q",i);let a=`${hi()}/repositories/${encodeURIComponent(o)}/${encodeURIComponent(r)}/pullrequests?${s.toString()}`;return this.collectPullRequests(a,r)}async queryWorkspacePullRequests(e,t){let{workspace:r}=await this.requireConfig(),o=await this.selectedUser(),i=new URLSearchParams({pagelen:String(gi)}),s=Uc(t.state);s&&i.set("state",s),e==="reviewer"&&i.set("role","REVIEWER");let a=`${hi()}/workspaces/${encodeURIComponent(r)}/pullrequests/${encodeURIComponent(o)}?${i.toString()}`;return this.collectPullRequests(a)}selectedUserCache;async selectedUser(){let{email:e}=await this.requireConfig();if(this.selectedUserCache?.email===e)return this.selectedUserCache.id;let t=await this.request("GET","/user"),r=wi(t.uuid,t.account_id,t.username);if(!r)throw new Error("Bitbucket GET /user did not return uuid, account_id, or username \u2014 cannot list workspace pull requests");return this.selectedUserCache={email:e,id:r},r}async collectPullRequests(e,t){let r=[],o=new Set,i=e;for(let s=0;s<Lc&&r.length<yi&&!(!i||o.has(i));s++){o.add(i);let a=await this.request("GET",i),u=Array.isArray(a.values)?a.values:[];for(let d of u){if(r.length>=yi)break;r.push(Pr(d,t??Rm(d),this.instanceId))}let c=typeof a.next=="string"&&a.next.length>0?a.next:void 0;if(!c||u.length===0)break;i=c}return r}async getComments(e){let{repoSlug:t,prNumber:r}=Ut(e),{workspace:o}=await this.requireConfig(),i=[],s=new Set,a=`${this.prPath(o,t,r)}/comments?pagelen=${gi}`;for(let u=0;u<Lc&&i.length<yi&&!(!a||s.has(a));u++){s.add(a);let c=await this.request("GET",a),d=Array.isArray(c.values)?c.values:[];for(let w of d)i.push(Am(w,e));let m=typeof c.next=="string"&&c.next.length>0?c.next:void 0;if(!m||d.length===0)break;a=m}return i}async postComment(e,t){let{repoSlug:r,prNumber:o}=Ut(e),{workspace:i}=await this.requireConfig();await this.request("POST",`${this.prPath(i,r,o)}/comments`,{body:{content:{raw:t}}})}async postPositionedComments(e,t){let{repoSlug:r,prNumber:o}=Ut(e),{workspace:i}=await this.requireConfig(),s=`${this.prPath(i,r,o)}/comments`,a=[],u=[];for(let c of t)try{await this.request("POST",s,{body:{content:{raw:c.body},inline:{path:c.file,to:c.line}}}),a.push(c)}catch(d){u.push({comment:c,error:d instanceof Error?d.message:String(d)})}return{succeeded:a,failed:u}}async updateStatus(e,t){let{repoSlug:r,prNumber:o}=Ut(e),{workspace:i}=await this.requireConfig(),s=km(t);await this.request("POST",`${this.prPath(i,r,o)}/${s}`)}listExtendedActions(){return bi}async executeExtendedAction(e,t){if(e==="add_reviewer")return this.addReviewer(t);throw new Error(`Provider 'bitbucket' has no extended action '${e}'. Available: ${Lt(this.listExtendedActions())}`)}async addReviewer(e){let t=typeof e.subjectId=="string"?e.subjectId.trim():"";if(!t)throw new Error("Bitbucket action 'add_reviewer' requires params.subjectId");let r=typeof e.username=="string"?e.username.trim():"";if(!r)throw new Error("Bitbucket action 'add_reviewer' requires params.username");let{repoSlug:o,prNumber:i}=Ut(t),{workspace:s}=await this.requireConfig(),a=await this.request("GET",this.prPath(s,o,i)),u=await this.request("GET",`/users/${encodeURIComponent(r)}`),c=wi(u.uuid),d=wi(u.account_id);if(!c&&!d)throw new Error(`Bitbucket user '${r}' has no uuid or account_id`);let m=Array.isArray(a.reviewers)?a.reviewers:[];if(m.some(_=>c!=null&&_.uuid===c||d!=null&&_.account_id===d))return Pr(a,o,this.instanceId);let S=[...m.map(_=>_.uuid?{uuid:_.uuid}:{account_id:_.account_id}),c?{uuid:c}:{account_id:d}],k=await this.request("PUT",this.prPath(s,o,i),{body:{title:a.title??"",reviewers:S}});return Pr(k,o,this.instanceId)}prPath(e,t,r){return`/repositories/${encodeURIComponent(e)}/${encodeURIComponent(t)}/pullrequests/${encodeURIComponent(r)}`}async requireConfig(){let e=this.email,t=this.workspace,r=await this.secrets.get(this.secretKey);if(!e||!t||!r){let o=[];throw e||o.push("config.email"),t||o.push("config.workspace"),r||o.push(`SecretStore '${this.secretKey}'`),new Error(`Bitbucket instance '${this.instanceId}' is not configured \u2014 missing ${o.join(", ")}. Set email and workspace on the provider instance, and store the API token with: POST /api/secrets/${this.secretKey} or npm --workspace apps/engine run set-secret -- ${this.secretKey} <value>`)}return{email:e,workspace:t,token:r}}async request(e,t,r={}){let{email:o,token:i}=await this.requireConfig(),s=t.startsWith("http://")||t.startsWith("https://")?t:`${hi()}${t.startsWith("/")?t:`/${t}`}`,a={Authorization:`Basic ${Buffer.from(`${o}:${i}`).toString("base64")}`,Accept:"application/json"};r.body!==void 0&&(a["Content-Type"]="application/json");let u=await this.fetchFn(s,{method:e,headers:a,...r.body!==void 0?{body:JSON.stringify(r.body)}:{}});if(!u.ok){let d=await u.text().catch(()=>"");throw new Error(`Bitbucket ${e} ${t} failed (${u.status}): ${d||u.statusText}`)}if(u.status===204)return;let c=await u.text();if(c)return JSON.parse(c)}}});import{randomUUID as Cm}from"node:crypto";function Tm(n,e){return Object.entries(e).every(([t,r])=>t==="status"?n.raw?.status===r:n[t]===r)}var kr,Wc=l(()=>{"use strict";kr=class{pullRequests;comments;instanceId;constructor(e=[],t){this.pullRequests=new Map(e.map(r=>[r.id,structuredClone(r)])),this.comments=new Map,this.instanceId=t}async get(e){let t=this.pullRequests.get(e);if(!t)throw new Error(`Pull request not found: ${e}`);return this.withSource(structuredClone(t))}async query(e){return[...this.pullRequests.values()].filter(t=>Tm(t,e)).map(t=>this.withSource(structuredClone(t)))}async getComments(e){return await this.get(e),structuredClone(this.comments.get(e)??[])}async postComment(e,t){await this.get(e);let r=this.comments.get(e)??[];r.push({id:Cm(),subjectId:e,body:t,createdAt:new Date().toISOString()}),this.comments.set(e,r)}async updateStatus(e,t){let r=this.pullRequests.get(e);if(!r)throw new Error(`Pull request not found: ${e}`);r.raw={...r.raw??{},status:t}}withSource(e){return this.instanceId?{...e,source:this.instanceId}:e}}});function xi(n){return n.pull_request!=null}function Ar(n){let e=n.trim(),t=e.lastIndexOf("#");if(t<=0||t===e.length-1)throw new Error(`GitHub issue id must be '{owner}/{repo}#{issueNumber}' (e.g. 'acme/kno#42'), got '${n}'`);let r=e.slice(0,t),o=e.slice(t+1),{owner:i,name:s}=Hc(r);if(!/^\d+$/.test(o))throw new Error(`GitHub issue id must be '{owner}/{repo}#{issueNumber}' (e.g. 'acme/kno#42'), got '${n}'`);return{owner:i,repo:s,issueNumber:o}}function Bm(n,e,t){return`${n}/${e}#${t}`}function Hc(n){let e=n.trim(),t=e.indexOf("/");if(t<=0||t===e.length-1||e.indexOf("/",t+1)!==-1)throw new Error(`GitHub repo must be '{owner}/{name}', got '${n}'`);return{owner:e.slice(0,t),name:e.slice(t+1)}}function Fm(n){let e=n.role;if(e==="assignee"||e==="creator")return e}function Nm(n,e){return n==="creator"?`author:${e}`:`assignee:${e}`}function Jm(n){let e=n.trim().toLowerCase();if(e==="open")return{state:"open"};if(e==="closed"||e==="done"||e==="completed")return{state:"closed",state_reason:"completed"};if(e==="not_planned"||e==="wontfix")return{state:"closed",state_reason:"not_planned"};throw new Error(`No GitHub Issues mapping for status '${n}'. Accepted: ${Dm.join(", ")}`)}function Lm(n){let e=n.repository?.full_name;if(typeof e=="string"&&e.includes("/"))return e;let t=n.repository_url;if(typeof t=="string"){let r="/repos/",o=t.lastIndexOf(r);if(o>=0){let i=t.slice(o+r.length);if(i.includes("/"))return i}}throw new Error("GitHub search result is missing repository full_name")}function vi(n,e,t){let r=String(n.number??""),[o,i]=t.split("/"),s=typeof n.body=="string"?n.body:"";return{id:Bm(o??"",i??"",r),source:e,title:String(n.title??""),...s?{description:s}:{},status:String(n.state??""),...n.assignee?.login?{assignee:n.assignee.login}:{},...n.html_url?{url:n.html_url}:{},raw:n}}function Um(n,e){return{id:String(n.id??""),subjectId:e,body:n.body??"",...n.user?.login?{author:n.user.login}:{},createdAt:n.created_at??""}}function Cr(n){return n!=null&&n!==""}var Om,$m,qm,Dm,Tr,Gc=l(()=>{"use strict";Om="2026-03-10",$m="https://api.github.com",qm="kno.github.apiToken",Dm=["open","closed/done/completed","not_planned/wontfix"],Tr=class{secrets;fetchFn;instanceId;username;secretKey;constructor(e,t,r=fetch){this.secrets=e,this.fetchFn=r,this.instanceId=t.instanceId,this.username=t.username?.trim()||void 0,this.secretKey=t.secretKey?.trim()||qm}async get(e){let{owner:t,repo:r,issueNumber:o}=Ar(e),i=await this.request("GET",`/repos/${encodeURIComponent(t)}/${encodeURIComponent(r)}/issues/${encodeURIComponent(o)}`);if(xi(i))throw new Error(`Ticket not found: ${e}`);return vi(i,this.instanceId,`${t}/${r}`)}async query(e){let t=typeof e.repo=="string"?e.repo.trim():"";if(t)return this.queryRepoIssues(t,e);let r=Fm(e);if(r)return this.querySearch(r,e);throw new Error("GitHub Issues query requires filter.repo ('owner/name') or filter.role ('assignee' | 'creator')")}async getComments(e){let{owner:t,repo:r,issueNumber:o}=Ar(e),i=await this.request("GET",`/repos/${encodeURIComponent(t)}/${encodeURIComponent(r)}/issues/${encodeURIComponent(o)}/comments`);return(Array.isArray(i)?i:[]).map(a=>Um(a,e))}async postComment(e,t){let{owner:r,repo:o,issueNumber:i}=Ar(e);await this.request("POST",`/repos/${encodeURIComponent(r)}/${encodeURIComponent(o)}/issues/${encodeURIComponent(i)}/comments`,{body:{body:t}})}async updateStatus(e,t){let{owner:r,repo:o,issueNumber:i}=Ar(e);await this.request("PATCH",`/repos/${encodeURIComponent(r)}/${encodeURIComponent(o)}/issues/${encodeURIComponent(i)}`,{body:Jm(t)})}async queryRepoIssues(e,t){let{owner:r,name:o}=Hc(e),i=[],s=new URLSearchParams;s.set("per_page",String(100)),Cr(t.state)&&s.set("state",String(t.state)),Cr(t.labels)&&s.set("labels",String(t.labels)),Cr(t.assignee)&&s.set("assignee",String(t.assignee));for(let a=1;a<=10&&i.length<500;a++){s.set("page",String(a));let u=await this.request("GET",`/repos/${encodeURIComponent(r)}/${encodeURIComponent(o)}/issues?${s.toString()}`),c=Array.isArray(u)?u:[];if(c.length===0)break;for(let d of c)if(!xi(d)){if(i.length>=500)break;i.push(vi(d,this.instanceId,`${r}/${o}`))}if(c.length<100)break}return i}async querySearch(e,t){let r=this.requireUsername(),o=[Nm(e,r),"is:issue"];Cr(t.state)&&o.push(`is:${String(t.state).trim().toLowerCase()}`);let i=o.join(" "),s=[];for(let a=1;a<=10&&s.length<500;a++){let u=new URLSearchParams({q:i,per_page:String(100),page:String(a)}),c=await this.request("GET",`/search/issues?${u.toString()}`),d=Array.isArray(c.items)?c.items:[];if(d.length===0)break;for(let m of d)if(!xi(m)){if(s.length>=500)break;s.push(vi(m,this.instanceId,Lm(m)))}if(d.length<100)break}return s}requireUsername(){if(!this.username)throw new Error(`GitHub Issues instance '${this.instanceId}' is not configured \u2014 missing config.username`);return this.username}async requireToken(){let e=await this.secrets.get(this.secretKey);if(!e)throw new Error(`GitHub Issues instance '${this.instanceId}' is not configured \u2014 missing SecretStore '${this.secretKey}'. Store the token with: POST /api/secrets/${this.secretKey} or npm --workspace apps/engine run set-secret -- ${this.secretKey} <value>`);return e}async request(e,t,r={}){let o=await this.requireToken(),i=`${$m}${t}`,s={Authorization:`Bearer ${o}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":Om};r.body!==void 0&&(s["Content-Type"]="application/json");let a=await this.fetchFn(i,{method:e,headers:s,...r.body!==void 0?{body:JSON.stringify(r.body)}:{}});if(!a.ok){let c=await a.text().catch(()=>"");throw new Error(`GitHub ${e} ${t} failed (${a.status}): ${c||a.statusText}`)}if(a.status===204)return;let u=await a.text();if(u)return JSON.parse(u)}}});var _t,g,h,B,Rn,R=l(()=>{"use strict";_t=class extends Error{details;constructor(e,t){super(e),this.name=this.constructor.name,this.details=t}},g=class extends _t{httpStatus=404},h=class extends _t{httpStatus=400},B=class extends _t{httpStatus=409},Rn=class extends Error{details;constructor(e,t){super(e),this.name="StepFailureError",this.details=t}}});function Gm(n){if(typeof n.jql=="string"&&n.jql.trim().length>0)return n.jql;let e=[];if($r(n.project)&&e.push(`project = ${qr(n.project)}`),$r(n.status)&&e.push(`status = ${qr(n.status)}`),$r(n.assignee)&&e.push(`assignee = ${qr(n.assignee)}`),$r(n.sprintId)){let t=n.sprintId;e.push(typeof t=="number"||/^\d+$/.test(String(t))?`sprint = ${Number(t)}`:`sprint = ${qr(t)}`)}if(e.length===0)throw new h("Jira query requires jql or at least one of project, status, assignee, sprintId");return e.join(" AND ")}function $r(n){return n!=null&&n!==""}function qr(n){return`"${String(n).replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Kc(n,e,t){let r=String(n.key??n.id??""),o=n.fields??{},i=Pn(o.description);return{id:r,source:t,title:String(o.summary??""),...i?{description:i}:{},status:String(o.status?.name??""),...o.assignee?.displayName?{assignee:String(o.assignee.displayName)}:{},url:`${e.replace(/\/$/,"")}/browse/${r}`,raw:n}}var Mm,Wm,Hm,Or,Dr,Vc=l(()=>{"use strict";R();fi();Mm="kno.jira.apiToken",Wm=50,Hm=10,Or=500,Dr=class{secrets;fetchFn;instanceId;baseUrl;email;secretKey;constructor(e,t,r=fetch){this.secrets=e,this.fetchFn=r,this.instanceId=t.instanceId,this.baseUrl=t.baseUrl?.trim()||void 0,this.email=t.email?.trim()||void 0,this.secretKey=t.secretKey?.trim()||Mm}async get(e){let{baseUrl:t}=await this.requireConfig(),r=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}`);return Kc(r,t,this.instanceId)}async query(e){let{baseUrl:t}=await this.requireConfig(),r=Gm(e),o=[],i,s=new Set;for(let a=0;a<Hm&&o.length<Or;a++){let u={jql:r,maxResults:Math.min(Wm,Or-o.length),fields:["summary","description","status","assignee"]};i&&(u.nextPageToken=i);let c=await this.request("POST","/rest/api/3/search/jql",{body:u}),d=Array.isArray(c.issues)?c.issues:[];for(let w of d){if(o.length>=Or)break;o.push(Kc(w,t,this.instanceId))}let m=typeof c.nextPageToken=="string"?c.nextPageToken:void 0;if(c.isLast===!0||!m||d.length===0||m===i||s.has(m))break;s.add(m),i=m}return o}async getComments(e){let t=[],r=0,o=100,i=Or;for(;t.length<i;){let s=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}/comment?startAt=${r}&maxResults=${o}`),a=Array.isArray(s.comments)?s.comments:[];for(let u of a)t.push({id:String(u.id??""),subjectId:e,body:Pn(u.body),...u.author?.displayName?{author:u.author.displayName}:{},createdAt:u.created??"",raw:u});if(r+=a.length,a.length===0||typeof s.total=="number"&&r>=s.total||a.length<o)break}return t}async postComment(e,t){await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(e)}/comment`,{body:{body:jr(t)}})}async updateStatus(e,t){let r=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}/transitions`),o=Array.isArray(r.transitions)?r.transitions:[],i=t.trim().toLowerCase(),s=o.find(a=>(a.to?.name??"").trim().toLowerCase()===i);if(!s?.id){let a=o.map(c=>c.to?.name).filter(c=>typeof c=="string"&&c.length>0),u=a.length>0?a.join(", "):"(none)";throw new Error(`No Jira transition to status '${t}' from the current state. Available: ${u}`)}await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(e)}/transitions`,{body:{transition:{id:s.id}}})}async requireConfig(){let e=this.baseUrl,t=this.email,r=await this.secrets.get(this.secretKey);if(!e||!t||!r){let o=[];throw e||o.push("config.baseUrl"),t||o.push("config.email"),r||o.push(`SecretStore '${this.secretKey}'`),new Error(`Jira instance '${this.instanceId}' is not configured \u2014 missing ${o.join(", ")}. Set baseUrl and email on the provider instance, and store the API token with: POST /api/secrets/${this.secretKey} or npm --workspace apps/engine run set-secret -- ${this.secretKey} <value>`)}return{baseUrl:e,email:t,token:r}}async request(e,t,r={}){let{baseUrl:o,email:i,token:s}=await this.requireConfig(),a=`${o.replace(/\/$/,"")}${t}`,u={Authorization:`Basic ${Buffer.from(`${i}:${s}`).toString("base64")}`,Accept:"application/json"};r.body!==void 0&&(u["Content-Type"]="application/json");let c=await this.fetchFn(a,{method:e,headers:u,...r.body!==void 0?{body:JSON.stringify(r.body)}:{}});if(!c.ok){let m=await c.text().catch(()=>"");throw new Error(`Jira ${e} ${t} failed (${c.status}): ${m||c.statusText}`)}if(c.status===204)return;let d=await c.text();if(d)return JSON.parse(d)}}});import{randomUUID as Km}from"node:crypto";function Vm(n,e){return Object.entries(e).every(([t,r])=>n[t]===r)}var Br,Qc=l(()=>{"use strict";Br=class{tickets;comments;instanceId;constructor(e=[],t){this.tickets=new Map(e.map(r=>[r.id,structuredClone(r)])),this.comments=new Map,this.instanceId=t}async get(e){let t=this.tickets.get(e);if(!t)throw new Error(`Ticket not found: ${e}`);return this.withSource(structuredClone(t))}async query(e){return[...this.tickets.values()].filter(t=>Vm(t,e)).map(t=>this.withSource(structuredClone(t)))}async getComments(e){return await this.get(e),structuredClone(this.comments.get(e)??[])}async postComment(e,t){await this.get(e);let r=this.comments.get(e)??[];r.push({id:Km(),subjectId:e,body:t,createdAt:new Date().toISOString()}),this.comments.set(e,r)}async updateStatus(e,t){let r=this.tickets.get(e);if(!r)throw new Error(`Ticket not found: ${e}`);r.status=t}withSource(e){return this.instanceId?{...e,source:this.instanceId}:e}}});function Ue(n,e){let t=n[e];return typeof t=="string"&&t.trim().length>0?t.trim():void 0}function Fr(n){return new Error(`This workflow requires provider instance '${n}', which isn't configured`)}function Qm(n){return n==="jira"||n==="github"?"ticket":n==="bitbucket"?"pull_request":n==="confluence"?"documentation":"any"}var Wj,U,Mt=l(()=>{"use strict";C();Tc();Oc();mi();Jc();Si();Wc();Gc();Vc();Qc();Wj=Symbol("PROVIDER_REGISTRY");U=class n{tickets=new Map;repos=new Map;documentation=new Map;agents=new Map;instances=[];constructor(){}static fromSettings(e,t){let r=new n;return r.load(e,t),r}static fromMaps(e){let t=new n;for(let[r,o]of Object.entries(e.tickets??{}))t.tickets.set(r,o);for(let[r,o]of Object.entries(e.repos??{}))t.repos.set(r,o);for(let[r,o]of Object.entries(e.documentation??{}))t.documentation.set(r,o);for(let[r,o]of Object.entries(e.agents??{}))t.agents.set(r,o);return t.instances.push(...e.instances??[]),t}load(e,t){let r=new Set;for(let o of e){if(r.has(o.id))throw new Error(`Duplicate provider instance id '${o.id}'`);r.add(o.id),this.instances.push(o),this.instantiate(o,t)}}instantiate(e,t){if(Oe(e)){let o=Ue(e.config,"model");if(e.type==="claude"){this.agents.set(e.id,new br(t,{secretKey:e.secretKey,model:o}));return}this.agents.set(e.id,new Sr(t,{secretKey:e.secretKey,model:o}));return}if(!jt(e))throw new Error(`Unknown provider instance kind on '${e.id}'`);let r=Qm(e.type);if(r!=="any"&&e.subjectType!==r)throw new Error(`Provider instance '${e.id}' type '${e.type}' cannot serve subjectType '${e.subjectType}'`);if(e.type==="jira"){this.tickets.set(e.id,new Dr(t,{instanceId:e.id,baseUrl:Ue(e.config,"baseUrl"),email:Ue(e.config,"email"),secretKey:e.secretKey}));return}if(e.type==="github"){this.tickets.set(e.id,new Tr(t,{instanceId:e.id,username:Ue(e.config,"username"),secretKey:e.secretKey}));return}if(e.type==="bitbucket"){this.repos.set(e.id,new Rr(t,{instanceId:e.id,email:Ue(e.config,"email"),workspace:Ue(e.config,"workspace"),secretKey:e.secretKey}));return}if(e.type==="confluence"){this.documentation.set(e.id,new Ir(t,{instanceId:e.id,baseUrl:Ue(e.config,"baseUrl"),email:Ue(e.config,"email"),secretKey:e.secretKey}));return}if(e.subjectType==="ticket"){this.tickets.set(e.id,new Br([],e.id));return}if(e.subjectType==="pull_request"){this.repos.set(e.id,new kr([],e.id));return}this.documentation.set(e.id,new Er([],{instanceId:e.id,type:Ue(e.config,"type")}))}getTicketProvider(e){let t=this.tickets.get(e);if(!t)throw Fr(e);return t}getRepoProvider(e){let t=this.repos.get(e);if(!t)throw Fr(e);return t}getDocumentationProvider(e){let t=this.documentation.get(e);if(!t)throw Fr(e);return t}getAgentProvider(e){let t=this.agents.get(e);if(!t)throw Fr(e);return t}getInstance(e){return this.instances.find(t=>t.id===e)}listInstances(e){return e==null?[...this.instances]:this.instances.filter(t=>jt(t)&&t.subjectType===e)}ticketInstanceIds(){return[...this.tickets.keys()]}repoInstanceIds(){return[...this.repos.keys()]}documentationInstanceIds(){return[...this.documentation.keys()]}}});function Xc(n,e){switch(n){case"my-open-prs":return{role:"author",state:"OPEN"};case"reviewing":return{role:"reviewer",state:"OPEN"};case"repo-open-prs":{let t=typeof e.repoSlug=="string"?e.repoSlug.trim():"";if(!t)throw new h("Bitbucket template 'repo-open-prs' requires params.repoSlug");return{repoSlug:t,state:"OPEN"}}default:throw new g(`Unknown Bitbucket query template: ${n}`)}}var zc,Yc=l(()=>{"use strict";R();zc=[{id:"my-open-prs",label:"My open pull requests",params:[]},{id:"reviewing",label:"Pull requests I'm reviewing",params:[]},{id:"repo-open-prs",label:"Open pull requests in a repository",params:[{name:"repoSlug",label:"Repository",type:"string",required:!0}]}]});function eu(n,e){switch(n){case"my-open-issues":return{role:"assignee",state:"open"};case"created-by-me":return{role:"creator",state:"open"};case"repo-open-issues":{let t=typeof e.repo=="string"?e.repo.trim():"";if(!t)throw new h("GitHub template 'repo-open-issues' requires params.repo");return{repo:t,state:"open"}}default:throw new g(`Unknown GitHub query template: ${n}`)}}var Zc,tu=l(()=>{"use strict";R();Zc=[{id:"my-open-issues",label:"My open issues",params:[]},{id:"created-by-me",label:"Issues I created",params:[]},{id:"repo-open-issues",label:"Open issues in a repository",params:[{name:"repo",label:"Repository (owner/name)",type:"string",required:!0}]}]});function su(n,e){switch(n){case"my-open-tickets":return{jql:"assignee = currentUser() AND statusCategory != Done"};case"created-by-me":return{jql:"reporter = currentUser() AND statusCategory != Done"};case"project-open-tickets":return{jql:`project = ${ou(ru(n,e))} AND statusCategory != Done`};case"current-sprint-tickets":return{jql:`project = ${ou(ru(n,e))} AND sprint in openSprints() AND statusCategory != Done`};default:throw new g(`Unknown Jira query template: ${n}`)}}function ru(n,e){let t=typeof e.project=="string"?e.project.trim():"";if(!t)throw new h(`Jira template '${n}' requires params.project`);return t}function ou(n){return`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}var nu,iu,au=l(()=>{"use strict";R();nu={name:"project",label:"Project key",type:"string",required:!0},iu=[{id:"my-open-tickets",label:"My open tickets",params:[]},{id:"created-by-me",label:"Tickets I created",params:[]},{id:"project-open-tickets",label:"Open tickets in a project",params:[nu]},{id:"current-sprint-tickets",label:"Tickets in the current sprint",params:[nu]}]});import{Inject as uu,Injectable as Ym}from"@nestjs/common";var zm,Xm,cu,lu,at,ji=l(()=>{"use strict";C();R();ye();Mt();Yc();tu();au();zm=function(n,e,t,r){var o=arguments.length,i=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Xm=function(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)},cu=function(n,e){return function(t,r){e(t,r,n)}},lu={bitbucket:{list:()=>zc,resolve:Xc},github:{list:()=>Zc,resolve:eu},jira:{list:()=>iu,resolve:su}},at=class{settings;registry;constructor(e,t){this.settings=e,this.registry=t}async list(e){let t=await this.providerType(e);return t?lu[t]?.list()??[]:[]}async resolve(e,t,r){let o=await this.providerType(e),i=o?lu[o]:void 0;if(!i)throw new g(`No query templates for provider instance '${e}'`);let s=i.list().find(a=>a.id===t);if(!s)throw new g(`Unknown query template '${t}' for provider instance '${e}'`);for(let a of s.params){if(!a.required)continue;let u=r[a.name];if(u==null||typeof u=="string"&&u.trim()==="")throw new h(`Template '${t}' requires params.${a.name}`)}return i.resolve(t,r)}async providerType(e){let r=(await this.settings.get()).providerInstances?.find(o=>o.id===e)??this.registry.getInstance(e);if(!(!r||!jt(r)))return r.type}};at=zm([Ym(),cu(0,uu(E)),cu(1,uu(U)),Xm("design:paramtypes",[E,U])],at)});import{Inject as pu,Injectable as th}from"@nestjs/common";var Zm,eh,du,nh,ct,_i=l(()=>{"use strict";C();ye();mi();Si();Mt();Zm=function(n,e,t,r){var o=arguments.length,i=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},eh=function(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)},du=function(n,e){return function(t,r){e(t,r,n)}},nh={bitbucket:()=>bi,confluence:()=>_r},ct=class{settings;registry;constructor(e,t){this.settings=e,this.registry=t}async list(e){let r=(await this.settings.get()).providerInstances?.find(o=>o.id===e)??this.registry.getInstance(e);return!r||!jt(r)?[]:nh[r.type]?.()??[]}};ct=Zm([th(),du(0,pu(E)),du(1,pu(U)),eh("design:paramtypes",[E,U])],ct)});async function fu(n){let e=n.fetchFn??fetch;return n.type==="claude"?sh(n.apiKey,e):ah(n.apiKey,e)}async function sh(n,e){let t=await e(rh,{method:"GET",headers:{"x-api-key":n,"anthropic-version":ih}});if(!t.ok)throw mu("Claude",t.status);let r=await t.json();return(Array.isArray(r.data)?r.data:[]).flatMap(i=>{if(!i||typeof i!="object")return[];let s=i,a=typeof s.id=="string"?s.id:"";if(!a)return[];let u=typeof s.display_name=="string"&&s.display_name.trim()?s.display_name:a;return[{id:a,displayName:u}]})}async function ah(n,e){let t=await e(oh,{method:"GET",headers:{Authorization:`Basic ${Buffer.from(`${n}:`).toString("base64")}`}});if(!t.ok)throw mu("Cursor",t.status);let r=await t.json();return(Array.isArray(r.items)?r.items:[]).flatMap(i=>{if(!i||typeof i!="object")return[];let s=i,a=typeof s.id=="string"?s.id:"";if(!a)return[];let u=typeof s.displayName=="string"&&s.displayName.trim()?s.displayName:a;return[{id:a,displayName:u}]})}function mu(n,e){let t=new Error(`${n} rejected the API key (HTTP ${e}). Check the key and try again.`);return t.name="PreviewModelsAuthError",t}var rh,oh,ih,hu=l(()=>{"use strict";rh="https://api.anthropic.com/v1/models",oh="https://api.cursor.com/v1/models",ih="2023-06-01"});import{Inject as Ei,Injectable as lh}from"@nestjs/common";var ch,uh,Ii,Nr,ut,Pi=l(()=>{"use strict";C();ye();Fe();R();hu();ch=function(n,e,t,r){var o=arguments.length,i=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},uh=function(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)},Ii=function(n,e){return function(t,r){e(t,r,n)}},Nr="PREVIEW_MODELS_FETCH",ut=class{settings;secrets;fetchFn;constructor(e,t,r){this.settings=e,this.secrets=t,this.fetchFn=r}async preview(e){let t=e.apiKey?.trim();if(t)return this.lookup(e.type,t);let r=e.instanceId?.trim();if(!r)throw new h("Provide apiKey or instanceId to preview models");let o=(await this.settings.get()).providerInstances?.find(s=>s.id===r);if(!o)throw new g(`Provider instance not found: ${r}`);if(!Oe(o)||o.type!==e.type)throw new h(`Provider instance '${r}' is not a ${e.type} agent`);let i=await this.secrets.get(o.secretKey);if(!i)throw new h(`No API key stored for instance '${r}'. Enter a key to fetch models.`);return this.lookup(e.type,i)}async lookup(e,t){try{return await fu({type:e,apiKey:t,fetchFn:this.fetchFn})}catch(r){throw r instanceof Error&&r.name==="PreviewModelsAuthError"?new h(r.message):new h(r instanceof Error?r.message:"Failed to fetch available models")}}};ut=ch([lh(),Ii(0,Ei(E)),Ii(1,Ei(he)),Ii(2,Ei(Nr)),uh("design:paramtypes",[E,Function,Function])],ut)});import{Module as ph}from"@nestjs/common";var dh,lt,Jr=l(()=>{"use strict";To();Fs();Bo();Fe();_n();ye();pi();Mt();ji();_i();Pi();dh=function(n,e,t,r){var o=arguments.length,i=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},lt=class{};lt=dh([ph({imports:[Ft,$e],providers:[{provide:U,useFactory:async(n,e)=>{let t=await n.get();return U.fromSettings(t.providerInstances??[],e)},inject:[E,he]},{provide:sn,useClass:Fn},st,at,ct,{provide:Nr,useValue:(n,e)=>fetch(n,e)},ut],exports:[U,sn,st,at,ct,ut,Nr]})],lt)});import{Injectable as mh}from"@nestjs/common";var fh,we,Lr=l(()=>{"use strict";fh=function(n,e,t,r){var o=arguments.length,i=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},we=class{listeners=new Set;emit(e){for(let t of this.listeners)t(e)}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}};we=fh([mh()],we)});import{Global as gh,Module as yh}from"@nestjs/common";var hh,dt,Ur=l(()=>{"use strict";Lr();hh=function(n,e,t,r){var o=arguments.length,i=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},dt=class{};dt=hh([gh(),yh({providers:[we],exports:[we]})],dt)});import{Injectable as bh}from"@nestjs/common";import{resolve as Sh}from"node:path";var wh,pt,Ri=l(()=>{"use strict";wh=function(n,e,t,r){var o=arguments.length,i=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},pt=class{tails=new Map;lockKey(e){let t=Sh(e);return process.platform==="win32"?t.toLowerCase():t}async withLock(e,t){let r=this.lockKey(e),i=(this.tails.get(r)??Promise.resolve()).then(t);return this.tails.set(r,i.then(()=>{},()=>{})),i}};pt=wh([bh()],pt)});import{Injectable as jh}from"@nestjs/common";import{execFile as _h}from"node:child_process";import{mkdirSync as ki,rmSync as Ih}from"node:fs";import{dirname as Eh,join as Wr,resolve as Mr}from"node:path";import{promisify as Ph}from"node:util";function gu(n){return n==null?"":typeof n=="string"?n:n.toString("utf8")}function yu(n){return Wr(n,"worktrees")}function kh(n){let e=[],t;for(let r of n.split(/\r?\n/)){let o=r.trimEnd();if(o===""){t&&e.push(t),t=void 0;continue}if(o.startsWith("worktree ")){t&&e.push(t),t={path:o.slice(9)};continue}if(t&&o.startsWith("branch ")){let i=o.slice(7);t.branch=i.startsWith("refs/heads/")?i.slice(11):i}}return t&&e.push(t),e}var xh,vh,Rh,Me,Ai=l(()=>{"use strict";Ri();xh=function(n,e,t,r){var o=arguments.length,i=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},vh=function(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)},Rh=Ph(_h),Me=class{worktreesRoot;fetchLocks;constructor(e,t=new pt){this.worktreesRoot=e,this.fetchLocks=t,ki(this.worktreesRoot,{recursive:!0})}async createWorktree(e,t){let r=t.worktreePath??Wr(this.worktreesRoot,e);return ki(Wr(r,".."),{recursive:!0}),await this.fetchOrigin(t.repoPath,t.repoPath),await this.git(t.repoPath,["worktree","add","-b",t.branchName,r,t.baseBranch]),{worktreePath:r,branch:t.branchName}}async addWorktreeForExistingBranch(e){ki(Wr(e.worktreePath,".."),{recursive:!0}),await this.fetchOrigin(e.repoPath,e.repoPath,e.branch);let t=await this.existingBranchStartPoint(e.repoPath,e.branch);return t.kind==="local"?await this.git(e.repoPath,["worktree","add",e.worktreePath,e.branch]):await this.git(e.repoPath,["worktree","add","--track","-b",e.branch,e.worktreePath,t.ref]),{worktreePath:e.worktreePath,branch:e.branch}}async listWorktrees(e){let{stdout:t}=await this.git(e,["worktree","list","--porcelain"]);return kh(t)}async resetWorktreeToRemote(e,t){let r=Mr(e);try{r=await this.mainRepoPath(e)}catch{}await this.fetchOrigin(e,r,t);let o=`origin/${t}`;try{await this.git(e,["rev-parse","--verify",o]),await this.git(e,["reset","--hard",o])}catch{await this.git(e,["reset","--hard",t])}await this.git(e,["clean","-fd"])}async removeWorktree(e){let t=Mr(e);try{let r=await this.mainRepoPath(t);await this.git(r,["worktree","remove","--force",t])}catch{Ih(t,{recursive:!0,force:!0})}}async fetchOrigin(e,t,r){await this.fetchLocks.withLock(t,async()=>{try{let o=r?["fetch","origin",r]:["fetch","origin"];await this.git(e,o)}catch{}})}async mainRepoPath(e){let t=Mr(e),{stdout:r}=await this.git(t,["rev-parse","--git-common-dir"]),o=Mr(t,r.trim());return o.endsWith(".git")?Eh(o):o}async existingBranchStartPoint(e,t){try{return await this.git(e,["rev-parse","--verify",`refs/heads/${t}`]),{kind:"local"}}catch{let r=`origin/${t}`;return await this.git(e,["rev-parse","--verify",r]),{kind:"remote",ref:r}}}async checkout(e,t){await this.git(e,["checkout",t.branch])}async createBranch(e,t){t.baseBranch?await this.git(e,["checkout","-b",t.branchName,t.baseBranch]):await this.git(e,["checkout","-b",t.branchName])}async commit(e,t){return t.addAll!==!1&&await this.git(e,["add","-A"]),await this.git(e,["commit","-m",t.message]),{sha:(await this.git(e,["rev-parse","HEAD"])).stdout.trim()}}async push(e,t={}){let r=t.remote??"origin";t.branch?await this.git(e,["push",r,t.branch]):await this.git(e,["push",r,"HEAD"])}async git(e,t){try{let r=await Rh("git",t,{cwd:e,encoding:"utf8",windowsHide:!0});return{stdout:r.stdout??"",stderr:r.stderr??""}}catch(r){let o=r,i=gu(o.stderr),s=gu(o.stdout),a=i||s||o.message||"unknown git error";throw new Error(`git ${t.join(" ")} failed (cwd=${e}, code=${String(o.code??"?")}): ${a}`)}}};Me=xh([jh(),vh("design:paramtypes",[String,pt])],Me)});import{Module as Ch}from"@nestjs/common";import{mkdirSync as Th}from"node:fs";var Ah,wu,Hr,bu=l(()=>{"use strict";Nn();Ai();Ri();Ah=function(n,e,t,r){var o=arguments.length,i=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},wu=cn();Th(wu,{recursive:!0});Hr=class{};Hr=Ah([Ch({providers:[pt,{provide:Me,useFactory:n=>new Me(yu(wu),n),inject:[pt]}],exports:[Me]})],Hr)});function Ht(n,e){return n.replace(/\{\{\s*([^}]+?)\s*\}\}/g,(t,r)=>{let o=Ci(e,r.trim());return o==null?"":typeof o=="string"?o:JSON.stringify(o)})}function Ci(n,e){let t=e.split(".").filter(Boolean),r=n;for(let o of t){if(r==null||typeof r!="object")return;r=r[o]}return r}function Wt(n,e){return typeof n=="string"?Ht(n,e):Array.isArray(n)?n.map(t=>Wt(t,e)):n&&typeof n=="object"?Object.fromEntries(Object.entries(n).map(([t,r])=>[t,Wt(r,e)])):n}var Ti=l(()=>{"use strict"});function xu(n){let e=n.path?.trim()||void 0,t=n.pattern?.trim()||void 0,r=n.source,o=n.source;if(e){if(n.source.trim()==="")return{kind:"no_match",sourceValue:n.source};let i;try{i=JSON.parse(n.source)}catch(a){let u=a instanceof Error?a.message:String(a);throw new Error(`Extract source is not valid JSON (required when path is set): ${u}`)}let s=Oh(i,e);if(r=s??i,s==null)return{kind:"no_match",sourceValue:r};o=s}if(t){let i=Su(o),s;try{s=new RegExp(t)}catch(c){let d=c instanceof Error?c.message:String(c);throw new Error(`Invalid extract pattern: ${d}`)}let a=i.match(s);return a?{kind:"match",value:a[1]!==void 0?a[1]:a[0],sourceValue:r}:{kind:"no_match",sourceValue:r}}return{kind:"match",value:Su(o),sourceValue:r}}function Oh(n,e){if(!(n==null||typeof n!="object"))return Ci(n,e)}function Su(n){return typeof n=="string"?n:typeof n=="number"||typeof n=="boolean"||typeof n=="bigint"?String(n):n==null?"":JSON.stringify(n)}var vu=l(()=>{"use strict";Ti()});function ft(n,e){for(let t of n){if(t.id===e)return t;if(t.iterations)for(let r of t.iterations){let o=ft(r.stepExecutions,e);if(o)return o}}}function It(n,e,t,r){for(let o=0;o<n.length;o++){let i=n[o];if(i.id===e)return{execution:i,siblings:n,index:o,parentLoopExecutionId:t,iterationIndex:r};if(i.iterations)for(let s of i.iterations){let a=It(s.stepExecutions,e,i.id,s.index);if(a)return a}}}function W(n,e,t){return n.map(r=>r.id===e?t(r):r.iterations?{...r,iterations:r.iterations.map(o=>({...o,stepExecutions:W(o.stepExecutions,e,t)}))}:r)}function Oi(n,e,t,r){return t==null?[...n,e]:n.map(o=>{if(o.id===t){let i=[...o.iterations??[]],s=i.find(a=>a.index===r);if(s){let a={...s,stepExecutions:[...s.stepExecutions,e]},u=i.findIndex(c=>c.index===r);i[u]=a}else{let a={index:r,stepExecutions:[e],startedAt:e.startedAt??new Date().toISOString()};i.push(a),i.sort((u,c)=>u.index-c.index)}return{...o,iterations:i}}return o.iterations?{...o,iterations:o.iterations.map(i=>({...i,stepExecutions:Oi(i.stepExecutions,e,t,r)}))}:o})}function Et(n,e){for(let t of n){if(t.id===e)return t;if(t.type==="loop"){let r=Et(t.steps,e);if(r)return r}}}function ju(n,e,t){return W(n,e,r=>{let o=(r.iterations??[]).map(i=>{if(i.index!==t)return i;let s=i.stepExecutions.every(a=>a.completedAt)?i.stepExecutions.map(a=>a.completedAt).reduce((a,u)=>a>u?a:u):void 0;return{...i,...s?{completedAt:s}:{}}});return{...r,iterations:o}})}function $i(n){let e=[];for(let t of n){t.childJobIds&&e.push(...t.childJobIds);for(let r of t.iterations??[])e.push(...$i(r.stepExecutions))}return e}var _u=l(()=>{"use strict"});import{z as Y}from"zod";function Iu(n,e){let t=Fh[n].safeParse(e);if(!t.success){let r=t.error.issues.map(o=>`${o.path.length?o.path.join("."):"(root)"}: ${o.message}`).join("; ");throw new Error(`Agent output failed validation for format '${n}': ${r}`)}return t.data}var $h,qh,Dh,Bh,Fh,Eu=l(()=>{"use strict";$h=Y.object({questions:Y.array(Y.object({id:Y.string(),prompt:Y.string()}))}),qh=Y.object({approved:Y.boolean()}),Dh=Y.object({suggestions:Y.array(Y.object({id:Y.string().min(1),file:Y.string().min(1),line:Y.number().int(),body:Y.string()}))}),Bh=Y.string(),Fh={questionnaire:$h,confirmation:qh,comment_suggestions:Dh,free_text:Bh}});function be(n){return n==="completed"||n==="failed"||n==="cancelled"}function qi(n,e){let t=new Map;for(let o of n){let i=e(o);if(i==null)continue;let s=t.get(i)??[];s.push(o),t.set(i,s)}if(t.size===0)return null;let r=[];for(let o of t.values()){let i=new Set(o.map(a=>a.retryOf).filter(a=>a!=null)),s=o.find(a=>!i.has(a.id));if(!s)return null;r.push(s)}return{activeJobs:r,allTerminal:r.every(o=>be(o.status)),groupCount:t.size}}function Pu(n){let e=n.every(r=>r.status==="completed"),t=n.every(r=>r.status==="failed"||r.status==="cancelled");return e?"completed":t?"failed":"completed_with_issues"}var Di=l(()=>{"use strict"});async function Gr(n,e,t){let r=await e.get(n);if(!r)throw new g(`SubjectView not found: ${n}`);if(!r.providerInstanceId)throw new h(`SubjectView '${n}' has no providerInstanceId \u2014 reconfigure the View to pick a provider instance`);if(r.subjectType==="ticket")return(await t.getTicketProvider(r.providerInstanceId).query(r.query)).map(i=>({subjectType:"ticket",...i}));if(r.subjectType==="pull_request")return(await t.getRepoProvider(r.providerInstanceId).query(r.query)).map(i=>({subjectType:"pull_request",...i}));if(r.subjectType==="documentation")return(await t.getDocumentationProvider(r.providerInstanceId).query(r.query)).map(i=>({subjectType:"documentation",...i}));throw new h(`Unsupported subjectType on view: ${r.subjectType}`)}var Bi=l(()=>{"use strict";R()});import{Injectable as Jh}from"@nestjs/common";var Nh,Pt,Fi=l(()=>{"use strict";Nh=function(n,e,t,r){var o=arguments.length,i=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Pt=class{requested=new Set;requestCancellation(e){this.requested.add(e)}isCancellationRequested(e){return this.requested.has(e)}clear(e){this.requested.delete(e)}};Pt=Nh([Jh()],Pt)});import{Inject as Wh,Injectable as Hh}from"@nestjs/common";var Lh,Uh,Mh,Se,Kr=l(()=>{"use strict";C();ye();Lh=function(n,e,t,r){var o=arguments.length,i=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Uh=function(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)},Mh=function(n,e){return function(t,r){e(t,r,n)}},Se=class{settings;running=new Map;queues=new Map;admitTails=new Map;constructor(e){this.settings=e}async acquire(e,t,r){let o={jobId:t,stepExecutionId:r,agentInstanceId:e,enqueuedAt:new Date().toISOString()},i=null;await this.serialized(e,async()=>{await this.drainQueue(e),!await this.tryAdmit(e)&&(i=new Promise((s,a)=>{let u=this.queues.get(e)??[];u.push({entry:o,resolve:s,reject:a}),this.queues.set(e,u)}))}),i&&await i}release(e){let t=this.running.get(e)??0;t<=1?this.running.delete(e):this.running.set(e,t-1),this.serialized(e,()=>this.drainQueue(e))}listQueued(){let e=[];for(let t of this.queues.values())for(let r of t)e.push(r.entry);return e.sort((t,r)=>t.enqueuedAt.localeCompare(r.enqueuedAt))}dropQueued(e){for(let[t,r]of this.queues){let o=[];for(let i of r)i.entry.jobId===e?i.reject(new Error(`Job ${e} cancelled while queued for an agent slot`)):o.push(i);o.length===0?this.queues.delete(t):this.queues.set(t,o)}}runningCount(e){return this.running.get(e)??0}async serialized(e,t){let o=(this.admitTails.get(e)??Promise.resolve()).then(t,t);this.admitTails.set(e,o.then(()=>{},()=>{})),await o}async drainQueue(e){let t=await this.limit(e);for(;;){let r=this.queues.get(e);if(!r||r.length===0||!this.hasCapacity(e,t))return;let o=r.shift();r.length===0&&this.queues.delete(e),this.addRunning(e),o.resolve()}}async tryAdmit(e){let t=await this.limit(e);return this.hasCapacity(e,t)?(this.addRunning(e),!0):!1}hasCapacity(e,t){return(this.running.get(e)??0)<t}addRunning(e){this.running.set(e,(this.running.get(e)??0)+1)}async limit(e){let r=((await this.settings.get()).providerInstances??[]).find(o=>o.id===e);return!r||!Oe(r)?jn:bc(r)}};Se=Lh([Hh(),Mh(0,Wh(E)),Uh("design:paramtypes",[Object])],Se)});import{Logger as Gh}from"@nestjs/common";import{readFile as Kh}from"node:fs/promises";async function Ru(n,e,t=new Gh("resolveContextFiles"),r=o=>Kh(o,"utf8")){let o=[];for(let i of n){let s=await e.get(i);if(!s){t.warn(`Context file '${i}' is no longer in the catalog; skipping`);continue}try{let a=await r(s.path);o.push({tier:s.tier,content:a,sourceRef:s.path})}catch(a){let u=a instanceof Error?a.message:String(a);throw new Error(`Cannot read context file '${s.name}' at ${s.path}: ${u}`)}}return o}var ku=l(()=>{"use strict"});import{basename as Vh,dirname as Qh,join as zh,resolve as kn,sep as Au}from"node:path";function Xh(n){return n.replace(/-/g,"").slice(0,4)}function Cu(n,e){return`${n}-${Xh(e)}`}function Ni(n){return n.replace(/[\\/:*?"<>|]/g,"-")}function Vr(n){let e=kn(n);return zh(Qh(e),`${Vh(e)}-worktrees`)}function Qr(n,e){let t=kn(n),r=kn(e);if(mt(t,r))return!0;let o=t.endsWith(Au)?t:t+Au,i=process.platform==="win32"?r.toLowerCase():r,s=process.platform==="win32"?o.toLowerCase():o;return i.startsWith(s)}function mt(n,e){let t=kn(n),r=kn(e);return process.platform==="win32"?t.toLowerCase()===r.toLowerCase():t===r}var Ji=l(()=>{"use strict"});import{join as Tu}from"node:path";async function Ou(n,e,t){let r={...e},o=await t.list();for(let i of n){if(i.type!=="localRepository")continue;let s=r[i.name];if(s==null||s==="")continue;let a=String(s),u=o.find(m=>m.id===a),c=o.find(m=>mt(m.localPath,a)),d=u??c;if(!d)throw new h(`Unknown local repository: ${a}`);r[i.name]=d.localPath}return r}async function $u(n){let{job:e,params:t,git:r,jobs:o,localRepositories:i}=n,s=zr(t,"repoPath"),a=t.mode==="existing-branch"?"existing-branch":"new-branch",u=(await i.list()).find(S=>mt(S.localPath,s)),c=u?.worktreeBasePath?.trim()?u.worktreeBasePath.trim():Vr(s);if(Qr(s,c)&&!mt(s,c))throw new Error(`Worktree base '${c}' must not be inside the repository at '${s}'`);if(a==="existing-branch")return Yh({job:e,repoPath:s,branch:zr(t,"branch"),worktreeBase:c,explicitPath:typeof t.worktreePath=="string"?t.worktreePath:void 0,git:r,jobs:o});let d=zr(t,"branchName"),m=Cu(d,e.id),w=typeof t.worktreePath=="string"&&t.worktreePath.trim()!==""?t.worktreePath:Tu(c,Ni(m));return r.createWorktree(e.id,{repoPath:s,baseBranch:zr(t,"baseBranch"),branchName:m,worktreePath:w})}async function Yh(n){let{job:e,repoPath:t,branch:r,worktreeBase:o,git:i,jobs:s}=n,a=await i.listWorktrees(t),u=a.filter(w=>w.branch===r&&!mt(w.path,t)),c=a.find(w=>w.branch===r&&mt(w.path,t));if(u.length===0){if(c)throw new Error(`branch ${r} is checked out in the repository working copy; refusing to reuse the main clone`);let w=n.explicitPath&&n.explicitPath.trim()!==""?n.explicitPath:Tu(o,Ni(r));return i.addWorktreeForExistingBranch({repoPath:t,branch:r,worktreePath:w})}let d=u[0].path,m=await Zh(s,d);if(m&&!be(m.status))throw new Error(`branch ${r} already has an active worktree in use by Job ${m.id}`);return m&&m.id!==e.id&&await s.update(m.id,{worktreeDeletedAt:new Date().toISOString()}),await i.resetWorktreeToRemote(d,r),{worktreePath:d,branch:r}}async function Zh(n,e){let r=(await n.list({liveWorktree:!0})).filter(o=>o.worktreePath!=null&&mt(o.worktreePath,e));return r.find(o=>!be(o.status))??r.sort((o,i)=>i.updatedAt.localeCompare(o.updatedAt))[0]}function zr(n,e){let t=n[e];if(typeof t!="string"||t.trim()==="")throw new Error(`git step missing required param '${e}'`);return t}var qu=l(()=>{"use strict";R();Ji();Di()});import{Inject as se,Injectable as ng,Logger as rg}from"@nestjs/common";import{randomUUID as Li}from"node:crypto";import{exec as og}from"node:child_process";import{promisify as ig}from"node:util";async function Ui(n,e,t){if(n.length===0)throw new Error(t);let r;for(let o of n)try{return await e(o)}catch(i){r=i}throw r instanceof Error?r:new Error(t)}function Du(n,e){let t=e[n.stepId];if(t==null||typeof t!="object")return n.type==="field_empty";let r=t[n.field];return n.type==="field_empty"?r==null?!0:typeof r=="string"||Array.isArray(r)?r.length===0:!1:r===n.value}function cg(n,e){let t=o=>{let i=[];for(let s of o)i.push(s),s.type==="loop"&&i.push(...t(s.steps));return i},r=o=>{let i=o.findIndex(s=>s.id===e);if(i>=0){for(let s=i-1;s>=0;s--)if(o[s].type==="agent")return o[s].id;return}for(let s of o)if(s.type==="loop"){let a=r(s.steps);if(a!==void 0||s.steps.some(u=>u.id===e))return a}};return r(n.steps)}function Rt(n){let e={...n.context};return n.subjectContext?.mode==="single"&&(e.subject=n.subjectContext.subject),n.worktreePath&&(e.worktreePath=n.worktreePath),n.branch&&(e.branch=n.branch),e}function ug(n){if(n===null||typeof n!="object"||Array.isArray(n))throw new Error("Extract resume payload must be an object with an action");let e=n;if(e.action==="provide_value"){if(typeof e.value!="string")throw new Error("Extract resume action 'provide_value' requires a string value");return{action:"provide_value",value:e.value}}if(e.action==="continue"||e.action==="cancel")return{action:e.action};throw new Error(`Unknown extract resume action: ${String(e.action)}`)}function Xr(n){if(!n.worktreePath)throw new Error(`Job ${n.id} has no worktreePath; run create_worktree first`);return n.worktreePath}function kt(n,e){let t=n[e];if(typeof t!="string"||t.length===0)throw new Error(`Missing required string param '${e}'`);return t}function lg(n){if(n==="none")throw new Error("normalizeAppliesTo called with none");if(Array.isArray(n)){if(n.length!==1)throw new Error(`Workflow Runner requires appliesTo to be a single SubjectType (got ${JSON.stringify(n)})`);return n[0]}return n}function Bu(n,e){for(let t of n)if(t.required&&(e[t.name]===void 0||e[t.name]===null))throw new h(`Missing required input: ${t.name}`)}var eg,tg,ie,Mi,sg,ag,xe,Yr=l(()=>{"use strict";C();St();bn();Hn();Wn();Lr();Ai();ye();Gn();Kn();Mt();To();vr();R();Ti();vu();_u();Eu();Di();Bi();Fi();Kr();ku();qu();eg=function(n,e,t,r){var o=arguments.length,i=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},tg=function(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)},ie=function(n,e){return function(t,r){e(t,r,n)}},sg=ig(og),ag=new Set(["agent","shell","git","provider_action"]),xe=Mi=class{workflows;jobs;batches;views;events;providers;notifications;contextFiles;localRepositories;git;settings;cancellation;agentGate;logger=new rg(Mi.name);childTerminalLocks=new Set;batchTerminalLocks=new Set;constructor(e,t,r,o,i,s,a,u,c,d,m,w,S){this.workflows=e,this.jobs=t,this.batches=r,this.views=o,this.events=i,this.providers=s,this.notifications=a,this.contextFiles=u,this.localRepositories=c,this.git=d,this.settings=m,this.cancellation=w,this.agentGate=S,this.events.subscribe(k=>{let _=k;(_.type==="job_completed"||_.type==="job_failed"||_.type==="job_cancelled")&&this.onChildTerminal(_.jobId)})}async start(e){let t=await this.createJob(e);return this.emit({type:"job_started",jobId:t.id,timestamp:new Date().toISOString()}),this.runJob(t.id)}async launch(e){let t=await this.requireWorkflow(e.workflowId);if(t.subjectHandling!=="per-subject"&&t.subjectHandling!=="collection")throw new h(`Unsupported subjectHandling: ${String(t.subjectHandling)}`);Bu(t.inputSchema,e.inputValues);let r=await this.resolveSelection(e.selection);if(t.subjectHandling==="collection"){let a=await this.createJob({workflowId:t.id,subjectContext:{mode:"collection",subjects:r},selection:e.selection,inputValues:e.inputValues});return this.emit({type:"job_started",jobId:a.id,timestamp:new Date().toISOString()}),this.runJob(a.id)}let o=new Date().toISOString(),i=await this.batches.create({id:Li(),workflowId:t.id,selection:e.selection,resolvedSubjects:r,status:"running",triggeredBy:e.triggeredBy,...e.notificationOverride?{notificationOverride:e.notificationOverride}:{},notificationSent:!1,createdAt:o}),s=[];for(let a=0;a<r.length;a++){let u=r[a],c=await this.createJob({workflowId:t.id,subjectContext:{mode:"single",subject:u},selection:e.selection,batchId:i.id,fanOutIndex:a,inputValues:e.inputValues});s.push(c)}for(let a of s)this.emit({type:"job_started",jobId:a.id,timestamp:new Date().toISOString()}),await this.runJob(a.id);return await this.batches.get(i.id)}async createJob(e){let t=e.workflowSnapshot?structuredClone(e.workflowSnapshot):await this.workflows.get(e.workflowId);if(!t)throw new g(`Workflow not found: ${e.workflowId}`);if(!e.subjectContext&&t.subjectHandling!=="per-subject")throw new h(`Workflow Runner only supports subjectHandling 'per-subject' at start() without an explicit subjectContext (got '${t.subjectHandling}')`);let r=await Ou(t.inputSchema,e.inputValues,this.localRepositories);Bu(t.inputSchema,r);let o=e.subjectContext??await this.resolveSubjectContext(t,e.subjectId),i=new Date().toISOString();return this.jobs.create({id:Li(),workflowId:t.id,status:"pending",...o?{subjectContext:o}:{},...e.selection?{selection:e.selection}:{},...e.batchId?{batchId:e.batchId}:{},...e.parentJobId?{parentJobId:e.parentJobId}:{},...e.parentStepExecutionId?{parentStepExecutionId:e.parentStepExecutionId}:{},...e.fanOutIndex!=null?{fanOutIndex:e.fanOutIndex}:{},...e.retryOf?{retryOf:e.retryOf}:{},workflowSnapshot:structuredClone(t),context:{...r},stepHistory:[],createdAt:i,updatedAt:i})}async deleteWorktrees(e){if(e.length===0)throw new h("jobIds is required");let t=[];for(let s of e){let a=await this.jobs.get(s);if(!a)throw new g(`Job not found: ${s}`);t.push(a)}let r=t.find(s=>!be(s.status));if(r)throw new B(`Cannot delete worktree for active Job ${r.id}`);let o=new Date().toISOString(),i=[];for(let s of t){s.worktreePath&&!s.worktreeDeletedAt&&await this.git.removeWorktree(s.worktreePath);let a=await this.jobs.update(s.id,{worktreeDeletedAt:o,updatedAt:o});i.push(a)}return i}async runJob(e){let t=await this.jobs.get(e);if(!t)throw new g(`Job not found: ${e}`);if(be(t.status))return t;let r=await this.workflowForJob(t);if(t.status==="pending"&&(t=await this.persistJob({...t,status:"planning",updatedAt:new Date().toISOString()}),t.status==="cancelled"))return t;let o=await this.executeStepSequence(t,r,r.steps,void 0,void 0,0);return o.outcome!=="completed"?o.job:this.completeJob(o.job,r)}async resume(e,t){let r=await this.jobs.get(e);if(!r)throw new g(`Job not found: ${e}`);if(r.status!=="waiting_for_human")throw new B(`Job ${e} is not waiting for human input (status: ${r.status})`);let o=await this.workflowForJob(r),i=r.currentStepExecutionId;if(!i)throw new Error(`Job ${e} is waiting_for_human but has no currentStepExecutionId`);let s=ft(r.stepHistory,i);if(!s)throw new Error(`Paused execution ${i} not found on job ${e}`);if(s.type==="loop")return this.resumeAskHuman(r,o,s,t);if(s.type==="extract")return this.resumeExtract(r,o,s,t);if(s.type!=="interaction")throw new Error(`Paused execution ${i} has type '${s.type}'; expected interaction, extract, or loop`);let a=Et(o.steps,s.stepDefinitionId),u=t;if(a?.type==="interaction"&&a.interaction==="comment_review"){let O=Qa(t);if(!O)throw new h(`comment_review step '${a.id}' resume requires { finalComments: { file, line, body }[] }`);u=O}let c=new Date().toISOString(),d=W(r.stepHistory,i,O=>({...O,status:"completed",completedAt:c,output:u})),m=u!==null&&typeof u=="object"&&!Array.isArray(u)?u:{response:u};r=await this.persistJob({...r,status:"planning",context:{...r.context,[s.stepDefinitionId]:u},stepHistory:d,currentStepId:void 0,currentStepExecutionId:void 0,updatedAt:c}),this.emit({type:"human_answered",jobId:r.id,answers:m,timestamp:c});let w=It(r.stepHistory,i);if(!w)throw new Error(`Could not locate frame for execution ${i}`);let S=this.sequenceForFrameOnJob(r,o,w),k=w.index+1,_=await this.executeStepSequence(r,o,S,w.parentLoopExecutionId,w.iterationIndex,k);return _.outcome!=="completed"?_.job:w.parentLoopExecutionId!=null&&w.iterationIndex!=null?this.continueLoopAfterBody(_.job,o,w.parentLoopExecutionId,w.iterationIndex):this.completeJob(_.job,o)}async retryFailedJob(e){let t=await this.jobs.get(e);if(!t)throw new g(`Job not found: ${e}`);if(t.status!=="failed")throw new B(`Job ${e} is not failed (status: ${t.status})`);let r=t.parentJobId!=null&&t.parentStepExecutionId!=null&&t.fanOutIndex!=null,o=t.batchId!=null&&t.fanOutIndex!=null;if(r){let a=await this.jobs.get(t.parentJobId);if(!a)throw new g(`Parent job not found: ${t.parentJobId}`);let u=await this.createJob({workflowId:t.workflowId,subjectContext:t.subjectContext,inputValues:{},parentJobId:t.parentJobId,parentStepExecutionId:t.parentStepExecutionId,fanOutIndex:t.fanOutIndex,retryOf:t.id,workflowSnapshot:t.workflowSnapshot}),c=W(a.stepHistory,t.parentStepExecutionId,d=>({...d,status:"waiting_for_children",error:void 0,completedAt:void 0,childJobIds:[...d.childJobIds??[],u.id]}));return a=await this.persistJob({...a,status:"waiting_for_children",stepHistory:c,completedAt:void 0,updatedAt:new Date().toISOString()}),this.emitRetryLaunch(u.id,t.id),this.runJob(u.id),u}if(o){let a=await this.batches.get(t.batchId);if(!a)throw new g(`JobBatch not found: ${t.batchId}`);a.status!=="running"&&await this.batches.update(a.id,{status:"running",completedAt:null,notificationSent:!1});let u=await this.createJob({workflowId:t.workflowId,subjectContext:t.subjectContext,selection:t.selection,batchId:t.batchId,fanOutIndex:t.fanOutIndex,inputValues:{},retryOf:t.id,workflowSnapshot:t.workflowSnapshot});return this.emitRetryLaunch(u.id,t.id),this.runJob(u.id),u}let i=await this.workflowForJob(t),s=await this.createJob({workflowId:t.workflowId,subjectContext:t.subjectContext,selection:t.selection,inputValues:this.inputValuesFromContext(t.context,i),retryOf:t.id,workflowSnapshot:t.workflowSnapshot});return this.emitRetryLaunch(s.id,t.id),this.runJob(s.id),s}async retryFailedStep(e,t){let r=await this.jobs.get(e);if(!r)throw new g(`Job not found: ${e}`);if(r.status!=="failed")throw new B(`Job ${e} is not failed (status: ${r.status})`);let o=r.currentStepExecutionId;if(!o)throw new B(`Job ${e} has no currentStepExecutionId; cannot retry the failed step`);let i=ft(r.stepHistory,o);if(!i)throw new B(`Job ${e} currentStepExecutionId ${o} was not found in stepHistory`);if(i.type==="sub_workflow")throw new B("Step-level retry is not available for sub_workflow steps. Retry the specific failed child job instead.");if(!ag.has(i.type))throw new B(`Step-level retry is not available for '${i.type}' steps`);let s=await this.workflowForJob(r),a=It(r.stepHistory,o);if(!a)throw new B(`Could not locate execution frame for ${o} on job ${e}`);let u=this.sequenceForFrameOnJob(r,s,a),c=u[a.index];if(!c||c.id!==i.stepDefinitionId)throw new B(`Failed step '${i.stepDefinitionId}' does not match sequence position ${a.index}`);if(oc(c,i)&&(!t||!Object.prototype.hasOwnProperty.call(t,"comments")))throw new B(`Step '${c.id}' had a partial positioned-comment failure; retry with overrideParams.comments instead of a plain step retry`);let d=new Date().toISOString(),m={...r.context};delete m[i.stepDefinitionId];let w=await this.persistJob({...r,status:"planning",context:m,completedAt:void 0,currentStepId:i.stepDefinitionId,currentStepExecutionId:i.id,stepHistory:W(r.stepHistory,i.id,k=>({...k,status:"running",error:void 0,failureDetails:void 0,completedAt:void 0,output:void 0,startedAt:d})),updatedAt:d}),S=await this.executeStepSequence(w,s,u,a.parentLoopExecutionId,a.iterationIndex,a.index,i.id,t);return S.outcome!=="completed"?S.job:a.parentLoopExecutionId!=null&&a.iterationIndex!=null?this.continueLoopAfterBody(S.job,s,a.parentLoopExecutionId,a.iterationIndex):this.completeJob(S.job,s)}async cancelJob(e){let t=await this.jobs.get(e);if(!t)throw new g(`Job not found: ${e}`);if(be(t.status))throw new B(`Job ${e} is already terminal (status: ${t.status})`);for(let i of $i(t.stepHistory)){let s=await this.jobs.get(i);s&&!be(s.status)&&await this.cancelJob(i)}let r=await this.jobs.get(e);if(be(r.status))return r;this.cancellation.requestCancellation(e),this.agentGate.dropQueued(e);let o=await this.persistCancelled(r);return(r.status==="waiting_for_human"||r.status==="waiting_for_children")&&this.cancellation.clear(e),await this.onBatchMemberTerminal(o.id),o}async cancelBatch(e){let t=await this.batches.get(e);if(!t)throw new g(`JobBatch not found: ${e}`);if(t.status!=="running")throw new B(`JobBatch ${e} is already terminal (status: ${t.status})`);let r=await this.jobs.list({batchId:e});for(let s of r)be(s.status)||await this.cancelJob(s.id);let o=new Date().toISOString(),i=await this.batches.update(e,{status:"cancelled",completedAt:o});if(!i)throw new Error(`Failed to persist cancelled batch ${e}`);return this.emit({type:"batch_cancelled",batchId:i.id,timestamp:o}),i}async executeStepSequence(e,t,r,o,i,s,a,u){let c=e;for(let d=s;d<r.length;d++){let m=await this.stopIfCancelled(c);if(m)return{outcome:"cancelled",job:m};let w=r[d],S=new Date().toISOString(),k=d===s?a:void 0,_,O=c.stepHistory;if(k){let Pe=ft(c.stepHistory,k);if(!Pe)throw new Error(`Reuse execution ${k} not found on job ${c.id}`);_=Pe}else _={id:Li(),stepDefinitionId:w.id,type:w.type,status:"running",startedAt:S},O=Oi(c.stepHistory,_,o,i);if(c=await this.persistJob({...c,status:c.status==="pending"?"planning":c.status,currentStepId:w.id,currentStepExecutionId:_.id,stepHistory:O,updatedAt:S}),c.status==="cancelled")return{outcome:"cancelled",job:c};this.emit({type:"step_started",jobId:c.id,stepDefinitionId:w.id,timestamp:S});try{let Pe=await this.dispatchStep(c,t,w,_.id,o,i,k?u:void 0);c=Pe.job;let Dt=await this.stopIfCancelled(c);if(Dt)return{outcome:"cancelled",job:Dt};if(Pe.outcome!=="completed")return Pe}catch(Pe){let Dt=await this.failJob(c,t,_.id,w.id,Pe);return Dt.status==="cancelled"?{outcome:"cancelled",job:Dt}:{outcome:"failed",job:Dt}}}return o!=null&&i!=null&&(c=await this.persistJob({...c,stepHistory:ju(c.stepHistory,o,i),updatedAt:new Date().toISOString()})),{outcome:"completed",job:c}}async dispatchStep(e,t,r,o,i,s,a){switch(r.type){case"agent":return{outcome:"completed",job:await this.executeAgentStep(e,r,o)};case"interaction":return{outcome:"paused",job:await this.pauseForInteraction(e,t,r,o)};case"git":return{outcome:"completed",job:await this.executeGitStep(e,r,o)};case"provider_action":return{outcome:"completed",job:await this.executeProviderActionStep(e,r,o,a)};case"shell":return{outcome:"completed",job:await this.executeShellStep(e,r,o)};case"loop":return this.runLoopStep(e,t,r,o,i,s);case"sub_workflow":return this.runSubWorkflowStep(e,r,o);case"extract":return this.executeExtractStep(e,t,r,o);default:{let u=r;throw new h(`Step type '${u.type}' not yet supported by the Workflow Runner`)}}}async runLoopStep(e,t,r,o,i,s,a=0,u=r.maxIterations){let c=e,d=a;for(;;){if(d>=u)switch(r.onMaxIterations.action){case"fail":return c=await this.failExecution(c,t,o,r.id,`Loop '${r.id}' exceeded maxIterations (${u})`),{outcome:"failed",job:c};case"continue":return c=await this.finishExecution(c,o,r.id,{iterations:d,exitedOnMaxIterations:!0}),{outcome:"completed",job:c};case"ask_human":{let w={maxIterationsCheckpoint:!0,nextIteration:d,effectiveMaxIterations:u},S=new Date().toISOString(),k=W(c.stepHistory,o,_=>({..._,status:"pending",output:w}));return c=await this.persistJob({...c,status:"waiting_for_human",currentStepId:r.id,currentStepExecutionId:o,stepHistory:k,updatedAt:S}),this.emit({type:"waiting_for_human",jobId:c.id,stepDefinitionId:r.id,interaction:"confirmation",data:w,questions:[`Loop '${r.id}' reached maxIterations (${u}). Extend, continue, or cancel?`],timestamp:S}),t.notificationPolicy.triggers.includes("on_needs_input")&&await this.notifications.send({title:`Input needed: ${t.name}`,body:`Job ${c.id} hit max iterations on loop '${r.id}'`,jobId:c.id}),{outcome:"paused",job:c}}default:{let w=r.onMaxIterations;throw new Error(`Unknown onMaxIterations action: ${JSON.stringify(w)}`)}}let m=await this.executeStepSequence(c,t,r.steps,o,d,0);if(c=m.job,m.outcome!=="completed")return m;if(Du(r.until,c.context))return c=await this.finishExecution(c,o,r.id,{iterations:d+1}),{outcome:"completed",job:c};d+=1}}async resumeAskHuman(e,t,r,o){let i=o,s=r.output;if(!s?.maxIterationsCheckpoint)throw new Error(`Loop execution ${r.id} is not at an ask_human checkpoint`);let a=Et(t.steps,r.stepDefinitionId);if(!a||a.type!=="loop")throw new Error(`Loop step definition '${r.stepDefinitionId}' not found`);let u=It(e.stepHistory,r.id),c=new Date().toISOString();if(i.action==="cancel")return await this.failExecution({...e,status:"planning",currentStepId:void 0,currentStepExecutionId:void 0,updatedAt:c},t,r.id,a.id,"Loop cancelled by human at maxIterations checkpoint");if(i.action==="continue"){let k=await this.persistJob({...e,status:"planning",currentStepId:void 0,currentStepExecutionId:void 0,stepHistory:W(e.stepHistory,r.id,_=>({..._,status:"completed",completedAt:c,output:{iterations:s.nextIteration,exitedOnMaxIterations:!0,humanAction:"continue"}})),updatedAt:c});return this.emit({type:"human_answered",jobId:k.id,answers:i,timestamp:c}),this.emit({type:"step_completed",jobId:k.id,stepDefinitionId:a.id,timestamp:c}),u?.parentLoopExecutionId!=null&&u.iterationIndex!=null?this.continueLoopAfterBody(k,t,u.parentLoopExecutionId,u.iterationIndex):this.continueTopLevelAfter(k,t,a.id)}let d=typeof i.additionalIterations=="number"?i.additionalIterations:0,m=s.effectiveMaxIterations+d,w=await this.persistJob({...e,status:"planning",currentStepId:void 0,currentStepExecutionId:void 0,stepHistory:W(e.stepHistory,r.id,k=>({...k,status:"running",output:void 0})),updatedAt:c});this.emit({type:"human_answered",jobId:w.id,answers:i,timestamp:c});let S=await this.runLoopStep(w,t,a,r.id,u?.parentLoopExecutionId,u?.iterationIndex,s.nextIteration,m);return S.outcome!=="completed"?S.job:u?.parentLoopExecutionId!=null&&u.iterationIndex!=null?this.continueLoopAfterBody(S.job,t,u.parentLoopExecutionId,u.iterationIndex):this.continueTopLevelAfter(S.job,t,a.id)}async resumeExtract(e,t,r,o){let i=ug(o),s=Et(t.steps,r.stepDefinitionId);if(!s||s.type!=="extract")throw new Error(`Extract step definition '${r.stepDefinitionId}' not found`);let a=new Date().toISOString();if(i.action==="cancel")return this.failExecution({...e,status:"planning",currentStepId:void 0,currentStepExecutionId:void 0,updatedAt:a},t,r.id,s.id,`Extract '${s.id}' cancelled by human`);let u=i.action==="continue"?"":i.value,c=await this.finishExecution({...e,status:"planning",currentStepId:void 0,currentStepExecutionId:void 0,updatedAt:a},r.id,s.id,u);this.emit({type:"human_answered",jobId:c.id,answers:i,timestamp:a});let d=It(e.stepHistory,r.id);if(!d)throw new Error(`Could not locate frame for execution ${r.id}`);let m=this.sequenceForFrameOnJob(c,t,d),w=d.index+1,S=await this.executeStepSequence(c,t,m,d.parentLoopExecutionId,d.iterationIndex,w);return S.outcome!=="completed"?S.job:d.parentLoopExecutionId!=null&&d.iterationIndex!=null?this.continueLoopAfterBody(S.job,t,d.parentLoopExecutionId,d.iterationIndex):this.completeJob(S.job,t)}async continueLoopAfterBody(e,t,r,o){let i=ft(e.stepHistory,r);if(!i)throw new Error(`Loop execution ${r} not found`);let s=Et(t.steps,i.stepDefinitionId);if(!s||s.type!=="loop")throw new Error(`Loop step '${i.stepDefinitionId}' not found`);let a=It(e.stepHistory,r),u=i.output?.effectiveMaxIterations??s.maxIterations,c=e;if(Du(s.until,c.context))c=await this.finishExecution(c,r,s.id,{iterations:o+1});else{let d=o+1,m=await this.runLoopStep(c,t,s,r,a?.parentLoopExecutionId,a?.iterationIndex,d,u);if(m.outcome!=="completed")return m.job;c=m.job}return a?.parentLoopExecutionId!=null&&a.iterationIndex!=null?this.continueLoopAfterBody(c,t,a.parentLoopExecutionId,a.iterationIndex):this.continueTopLevelAfter(c,t,s.id)}async continueTopLevelAfter(e,t,r){let o=t.steps.findIndex(s=>s.id===r),i=await this.executeStepSequence(e,t,t.steps,void 0,void 0,o+1);return i.outcome!=="completed"?i.job:this.completeJob(i.job,t)}sequenceForFrameOnJob(e,t,r){if(r.parentLoopExecutionId==null)return t.steps;let o=ft(e.stepHistory,r.parentLoopExecutionId);if(!o)throw new Error(`Parent loop execution ${r.parentLoopExecutionId} not found`);let i=Et(t.steps,o.stepDefinitionId);if(!i||i.type!=="loop")throw new Error(`Parent loop step '${o.stepDefinitionId}' not found`);return i.steps}async runSubWorkflowStep(e,t,r){if(!e.subjectContext||e.subjectContext.mode!=="collection")throw new h(`sub_workflow steps require subjectContext.mode === 'collection' (job ${e.id})`);let o=e.subjectContext.subjects,i=[];for(let d=0;d<o.length;d++){let m=o[d],w=await this.createJob({workflowId:t.workflowId,subjectContext:{mode:"single",subject:m},inputValues:{},parentJobId:e.id,parentStepExecutionId:r,fanOutIndex:d});i.push(w)}let s=i.map(d=>d.id),a=new Date().toISOString(),u=W(e.stepHistory,r,d=>({...d,status:"waiting_for_children",childJobIds:s})),c=await this.persistJob({...e,status:"waiting_for_children",currentStepId:t.id,currentStepExecutionId:r,stepHistory:u,updatedAt:a});for(let d of i)this.emit({type:"job_started",jobId:d.id,timestamp:a}),this.runJob(d.id);return{outcome:"paused",job:c}}async onChildTerminal(e){let t=await this.jobs.get(e);if(!t?.parentJobId||!t.parentStepExecutionId)return;let r=`${t.parentJobId}:${t.parentStepExecutionId}`;if(!this.childTerminalLocks.has(r)){this.childTerminalLocks.add(r);try{let o=(await this.jobs.list({parentJobId:t.parentJobId,parentStepExecutionId:t.parentStepExecutionId})).filter(O=>O.parentStepExecutionId===t.parentStepExecutionId),i=qi(o,O=>O.fanOutIndex);if(!i?.allTerminal)return;let{activeJobs:s}=i,a=await this.jobs.get(t.parentJobId);if(!a||a.status==="cancelled"||a.status!=="waiting_for_children"&&a.status!=="failed")return;let u=await this.workflowForJob(a),c=t.parentStepExecutionId,d=ft(a.stepHistory,c);if(!d||d.type!=="sub_workflow")return;let m=s.some(O=>O.status==="failed");if(s.some(O=>O.status==="cancelled"))return;if(m){await this.failExecution(a,u,c,d.stepDefinitionId,"One or more child jobs failed");return}let S=s.slice().sort((O,Pe)=>(O.fanOutIndex??0)-(Pe.fanOutIndex??0)).map(O=>({fanOutIndex:O.fanOutIndex,jobId:O.id,output:O.context})),k=new Date().toISOString();a=await this.persistJob({...a,status:"planning",context:{...a.context,[d.stepDefinitionId]:S},currentStepId:void 0,currentStepExecutionId:void 0,stepHistory:W(a.stepHistory,c,O=>({...O,status:"completed",completedAt:k,output:S})),completedAt:void 0,updatedAt:k}),this.emit({type:"step_completed",jobId:a.id,stepDefinitionId:d.stepDefinitionId,timestamp:k});let _=await this.continueTopLevelAfter(a,u,d.stepDefinitionId)}finally{this.childTerminalLocks.delete(r)}}}async onBatchMemberTerminal(e){let t=await this.jobs.get(e);if(!t?.batchId)return;let r=t.batchId;if(!this.batchTerminalLocks.has(r)){this.batchTerminalLocks.add(r);try{let o=await this.batches.get(t.batchId);if(!o||o.status!=="running")return;let i=await this.jobs.list({batchId:o.id}),s=qi(i,m=>m.fanOutIndex);if(!s||s.groupCount!==o.resolvedSubjects.length||!s.allTerminal)return;let{activeJobs:a}=s,u=Pu(a),c=new Date().toISOString(),d=await this.batches.update(o.id,{status:u,completedAt:c});if(!d)return;if(this.emit({type:"batch_completed",batchId:d.id,summary:a.map(m=>({jobId:m.id,status:m.status})),timestamp:c}),!d.notificationSent){let m=await this.workflowForJob(t),w=d.notificationOverride??m.notificationPolicy,S=u==="completed"?"on_complete":"on_fail";w.triggers.includes(S)&&await this.notifications.send({title:`Batch ${u}: ${m.name}`,body:`JobBatch ${d.id} finished with status '${u}' (${a.length} members)`,batchId:d.id}),await this.batches.update(d.id,{notificationSent:!0})}}finally{this.batchTerminalLocks.delete(r)}}}async resolveSelection(e){if(e.mode==="view")return Gr(e.viewId,this.views,this.providers);let t=[];for(let r of e.subjectIds)if(e.subjectType==="ticket"){let o=await this.getTicketById(r);t.push({subjectType:"ticket",...o})}else if(e.subjectType==="pull_request"){let o=await this.getPullRequestById(r);t.push({subjectType:"pull_request",...o})}else if(e.subjectType==="documentation"){let o=await this.getDocumentationById(r);t.push({subjectType:"documentation",...o})}else throw new h(`Unsupported subjectType: ${e.subjectType}`);return t}async executeAgentStep(e,t,r){let o=await Ru(t.contextFileIds??[],this.contextFiles,this.logger),i=Rt(e),s=Ht(t.objective,i),a=t.agentInstanceId??(await this.settings.get()).defaultAgentInstanceId;if(!a)throw new Error("No default agent instance configured (set EngineSettings.defaultAgentInstanceId)");let u=await this.setExecutionStatus(e,r,"queued"),c=!1;try{await this.agentGate.acquire(a,u.id,r),c=!0;let d=await this.stopIfCancelled(u);if(d)return d;if(u=await this.jobs.get(u.id)??u,u=await this.setExecutionStatus(u,r,"running"),u.status==="cancelled")return u;let m=await this.providers.getAgentProvider(a).run({objective:s,outputFormat:t.outputFormat,knowledge:o,context:{...i,stepId:t.id},...u.worktreePath?{cwd:u.worktreePath}:{}}),w=Iu(t.outputFormat,m.parsed);return this.finishExecution(u,r,t.id,w)}finally{c&&this.agentGate.release(a)}}async setExecutionStatus(e,t,r){let o=new Date().toISOString(),i=W(e.stepHistory,t,s=>({...s,status:r}));return this.persistJob({...e,stepHistory:i,updatedAt:o})}async executeGitStep(e,t,r){let o=Wt(t.params,Rt(e));switch(t.operation){case"create_worktree":{let i=await $u({job:e,params:o,git:this.git,jobs:this.jobs,localRepositories:this.localRepositories});return this.finishExecution(e,r,t.id,i,{worktreePath:i.worktreePath,branch:i.branch})}case"create_branch":{let i=Xr(e),s=kt(o,"branchName");return await this.git.createBranch(i,{branchName:s,...typeof o.baseBranch=="string"?{baseBranch:o.baseBranch}:{}}),this.finishExecution(e,r,t.id,{branch:s},{branch:s})}case"checkout":{let i=Xr(e),s=kt(o,"branch");return await this.git.checkout(i,{branch:s}),this.finishExecution(e,r,t.id,{branch:s},{branch:s})}case"commit":{let i=Xr(e),s=await this.git.commit(i,{message:kt(o,"message"),addAll:o.addAll!==!1});return this.finishExecution(e,r,t.id,s)}case"push":{let i=Xr(e);return await this.git.push(i,{...typeof o.remote=="string"?{remote:o.remote}:{},...typeof o.branch=="string"?{branch:o.branch}:{}}),this.finishExecution(e,r,t.id,{remote:typeof o.remote=="string"?o.remote:"origin",branch:typeof o.branch=="string"?o.branch:e.branch})}default:{let i=t.operation;throw new Error(`Unknown git operation: ${i}`)}}}async executeProviderActionStep(e,t,r,o){if(!e.subjectContext||e.subjectContext.mode!=="single")throw new h(`provider_action steps require subjectContext.mode === 'single' (job ${e.id})`);let i=this.resolveProviderActionSubject(e,t);if(t.extendedAction)return this.executeExtendedProviderAction(e,t,r,i);let s=o??Wt(t.params??{},Rt(e))??{},a=await this.dispatchPortableProviderAction(i,t.action,s);return this.finishExecution(e,r,t.id,a)}resolveProviderActionSubject(e,t){if(!t.target){let o=e.subjectContext;if(!o||o.mode!=="single")throw new h(`provider_action steps require subjectContext.mode === 'single' (job ${e.id})`);let i=o.subject;return{subjectType:i.subjectType,source:i.source,subjectId:i.id}}let r=Ht(t.target.subjectId,Rt(e)).trim();if(!r)throw new Error(`provider_action '${t.id}' target.subjectId interpolated to an empty id`);return{subjectType:t.target.subjectType,source:t.target.source,subjectId:r}}async dispatchPortableProviderAction(e,t,r){let{subjectType:o,source:i,subjectId:s}=e;if(o==="documentation"){let u=this.providers.getDocumentationProvider(i);switch(t){case"get_subject":return u.get(s);case"get_content":return u.getContent(s);case"get_comments":return u.getComments(s);case"post_comment":if(r.comments!==void 0)throw new Error("Array-mode post_comment requires subjectType 'pull_request' (got 'documentation')");return await u.postComment(s,kt(r,"body")),{posted:!0};case"update_status":throw new Error(`Provider action '${t}' is not valid for subject type 'documentation'`);default:{let c=t;throw new Error(`Unknown provider action: ${c}`)}}}let a=o==="ticket"?this.providers.getTicketProvider(i):o==="pull_request"?this.providers.getRepoProvider(i):null;if(!a)throw new Error(`Unsupported subjectType for provider_action: ${o}`);switch(t){case"get_subject":return a.get(s);case"get_comments":return a.getComments(s);case"post_comment":if(r.comments!==void 0){if(o!=="pull_request")throw new Error(`Array-mode post_comment requires subjectType 'pull_request' (got '${o}')`);let u=this.providers.getRepoProvider(i),c=u.postPositionedComments;if(typeof c!="function")throw new Error(`Provider '${i}' doesn't support positioned comments`);let d=rc(r.comments);if(!d)throw new h("post_comment params.comments must be { file, line, body }[]");let m=await c.call(u,s,d);if(m.failed.length>0)throw new Rn(`Failed to post ${m.failed.length} of ${d.length} positioned comments`,{succeeded:m.succeeded,failed:m.failed});return{posted:!0,succeeded:m.succeeded}}return await a.postComment(s,kt(r,"body")),{posted:!0};case"update_status":return await a.updateStatus(s,kt(r,"status")),{status:kt(r,"status")};case"get_content":throw new Error(`Provider action 'get_content' is not valid for subject type '${o}'`);default:{let u=t;throw new Error(`Unknown provider action: ${u}`)}}}async executeExtendedProviderAction(e,t,r,o){let i=t.extendedAction,s=o.subjectType==="documentation"?this.providers.getDocumentationProvider(i.providerId):o.subjectType==="ticket"?this.providers.getTicketProvider(i.providerId):o.subjectType==="pull_request"?this.providers.getRepoProvider(i.providerId):null;if(!s)throw new Error(`Unsupported subjectType for provider_action: ${o.subjectType}`);if(!$c(s))throw new Error(`Provider instance '${i.providerId}' does not support extended actions. Available: none`);let a=await s.listExtendedActions(),u=a.find(m=>m.actionId===i.actionId);if(!u)throw new Error(`Provider '${i.providerId}' has no extended action '${i.actionId}'. Available: ${Lt(a)}`);let c=Wt(i.params??{},Rt(e))??{};xr(u,c);let d=await s.executeExtendedAction(i.actionId,{...c,subjectId:o.subjectId});return this.finishExecution(e,r,t.id,d)}async executeShellStep(e,t,r){let o=Ht(t.command,Rt(e)),i=e.worktreePath??process.cwd();try{let s=await sg(o,{cwd:i,windowsHide:!0});return this.finishExecution(e,r,t.id,{exitCode:0,stdout:String(s.stdout??""),stderr:String(s.stderr??"")})}catch(s){let a=s,u=a.stderr??"",c=a.stdout??"",d=typeof a.code=="number"?a.code:Number.parseInt(String(a.code??"1"),10)||1;throw new Error(`shell command failed (exit ${d}, cwd=${i}): ${u||c||a.message||o}`)}}async executeExtractStep(e,t,r,o){let i=Ht(r.source,Rt(e)),s=xu({source:i,path:r.path,pattern:r.pattern});if(s.kind==="match")return{outcome:"completed",job:await this.finishExecution(e,o,r.id,s.value)};switch(r.onNoMatch){case"fail":throw new Error(`Extract '${r.id}' did not match`);case"empty":return{outcome:"completed",job:await this.finishExecution(e,o,r.id,"")};case"ask_human":return{outcome:"paused",job:await this.pauseForExtract(e,t,r,o,s.sourceValue)};default:{let a=r.onNoMatch;throw new Error(`Unknown onNoMatch action: ${String(a)}`)}}}async pauseForExtract(e,t,r,o,i){let s=new Date().toISOString(),a=r.pattern?.trim()||void 0,u={extractNoMatch:!0,sourceValue:i,...a?{pattern:a}:{}},c={sourceValue:i,...a?{pattern:a}:{}},d=W(e.stepHistory,o,w=>({...w,status:"pending",output:u})),m=await this.persistJob({...e,status:"waiting_for_human",currentStepId:r.id,currentStepExecutionId:o,stepHistory:d,updatedAt:s});return this.emit({type:"waiting_for_human",jobId:m.id,stepDefinitionId:r.id,interaction:"confirmation",data:c,questions:[`Extract '${r.id}' did not match. Provide a value, continue with empty, or cancel?`],timestamp:s}),t.notificationPolicy.triggers.includes("on_needs_input")&&await this.notifications.send({title:`Input needed: ${t.name}`,body:`Job ${m.id} needs a value for extract step '${r.id}'`,jobId:m.id}),m}async pauseForInteraction(e,t,r,o){let i=new Date().toISOString(),s=this.interactionPauseData(e,t,r),a=W(e.stepHistory,o,m=>({...m,status:"pending",...s!==void 0?{output:s}:{}})),u=await this.persistJob({...e,status:"waiting_for_human",currentStepId:r.id,currentStepExecutionId:o,stepHistory:a,updatedAt:i}),c=jc(r.interaction,s);return this.emit({type:"waiting_for_human",jobId:u.id,stepDefinitionId:r.id,interaction:r.interaction,data:s,questions:c,timestamp:i}),t.notificationPolicy.triggers.includes("on_needs_input")&&r.notify!==!1&&await this.notifications.send({title:`Input needed: ${t.name}`,body:`Job ${u.id} is waiting for human input on step '${r.id}'`,jobId:u.id}),u}interactionPauseData(e,t,r){if(r.interaction==="comment_review")return{suggestions:Va(r,t.steps,e.context)};let o=cg(t,r.id);return o!=null?e.context[o]:void 0}async finishExecution(e,t,r,o,i={}){let s=new Date().toISOString(),a=W(e.stepHistory,t,c=>({...c,status:"completed",completedAt:s,output:o})),u=await this.persistJob({...e,...i,context:{...e.context,[r]:o},stepHistory:a,updatedAt:s});return this.emit({type:"step_completed",jobId:u.id,stepDefinitionId:r,timestamp:s}),u}async failExecution(e,t,r,o,i){return this.failJob(e,t,r,o,new Error(i))}async completeJob(e,t){let r=new Date().toISOString(),o=await this.persistJob({...e,status:"completed",currentStepId:void 0,currentStepExecutionId:void 0,completedAt:r,updatedAt:r});return o.status==="cancelled"||(this.emit({type:"job_completed",jobId:o.id,timestamp:r}),await this.onBatchMemberTerminal(o.id),!o.batchId&&t.notificationPolicy.triggers.includes("on_complete")&&await this.notifications.send({title:`Job completed: ${t.name}`,body:`Job ${o.id} completed successfully`,jobId:o.id})),o}async failJob(e,t,r,o,i){let s=i instanceof Error?i.message:String(i),a=i instanceof Rn?i.details:void 0,u=new Date().toISOString(),c=W(e.stepHistory,r,m=>({...m,status:"failed",completedAt:u,error:s,...a!==void 0?{failureDetails:a}:{failureDetails:void 0}})),d=await this.persistJob({...e,status:"failed",currentStepId:o,currentStepExecutionId:r,stepHistory:c,completedAt:u,updatedAt:u});return this.emit({type:"step_failed",jobId:d.id,stepDefinitionId:o,error:s,timestamp:u}),d.status==="cancelled"?(await this.onBatchMemberTerminal(d.id),d):(this.emit({type:"job_failed",jobId:d.id,error:s,timestamp:u}),await this.onBatchMemberTerminal(d.id),!d.batchId&&t.notificationPolicy.triggers.includes("on_fail")&&await this.notifications.send({title:`Job failed: ${t.name}`,body:`Job ${d.id} failed on step '${o}': ${s}`,jobId:d.id}),d)}async resolveSubjectContext(e,t){if(e.appliesTo==="none")return;let r=lg(e.appliesTo);if(!t)throw new Error(`Workflow '${e.id}' applies to '${r}' but no subjectId was provided`);if(r==="ticket")return{mode:"single",subject:{subjectType:"ticket",...await this.getTicketById(t)}};if(r==="pull_request")return{mode:"single",subject:{subjectType:"pull_request",...await this.getPullRequestById(t)}};if(r==="documentation")return{mode:"single",subject:{subjectType:"documentation",...await this.getDocumentationById(t)}};throw new Error(`Unsupported subjectType for workflow subject resolution: ${r}`)}async workflowForJob(e){return e.workflowSnapshot?e.workflowSnapshot:(this.logger.warn(`Job ${e.id} has no workflowSnapshot; falling back to live WorkflowDefinition ${e.workflowId}`),this.requireWorkflow(e.workflowId))}async requireWorkflow(e){let t=await this.workflows.get(e);if(!t)throw new g(`Workflow not found: ${e}`);return t}emitRetryLaunch(e,t){let r=new Date().toISOString();this.emit({type:"job_started",jobId:e,timestamp:r}),this.emit({type:"job_retried",jobId:e,retryOf:t,timestamp:r})}inputValuesFromContext(e,t){let r={};for(let o of t.inputSchema)Object.prototype.hasOwnProperty.call(e,o.name)&&(r[o.name]=e[o.name]);return r}async persistCancelled(e){let t=new Date().toISOString();return this.persistJob({...e,status:"cancelled",completedAt:e.completedAt??t,updatedAt:t})}async stopIfCancelled(e){return!this.cancellation.isCancellationRequested(e.id)&&e.status!=="cancelled"&&(await this.jobs.get(e.id))?.status!=="cancelled"?null:(this.cancellation.clear(e.id),e.status==="cancelled"?e:this.persistCancelled(e))}async persistJob(e){let t=await this.jobs.get(e.id),r=this.cancellation.isCancellationRequested(e.id)||t?.status==="cancelled"||e.status==="cancelled",o=r?"cancelled":e.status,i=r?t?.completedAt??e.completedAt??e.updatedAt:e.completedAt,s=await this.jobs.update(e.id,{status:o,context:e.context,currentStepId:e.currentStepId,currentStepExecutionId:e.currentStepExecutionId,stepHistory:e.stepHistory,worktreePath:e.worktreePath,branch:e.branch,updatedAt:e.updatedAt,completedAt:i});if(!s)throw new Error(`Failed to persist job ${e.id}`);return t?.status!=="cancelled"&&s.status==="cancelled"&&this.emit({type:"job_cancelled",jobId:s.id,timestamp:s.updatedAt}),s}emit(e){this.events.emit(e)}async getTicketById(e){return Ui(this.providers.ticketInstanceIds(),t=>this.providers.getTicketProvider(t).get(e),`Ticket not found: ${e}`)}async getPullRequestById(e){return Ui(this.providers.repoInstanceIds(),t=>this.providers.getRepoProvider(t).get(e),`Pull request not found: ${e}`)}async getDocumentationById(e){return Ui(this.providers.documentationInstanceIds(),t=>this.providers.getDocumentationProvider(t).get(e),`Documentation page not found: ${e}`)}};xe=Mi=eg([ng(),ie(0,se(D)),ie(1,se(X)),ie(2,se(le)),ie(3,se(ue)),ie(4,se(we)),ie(5,se(U)),ie(6,se(sn)),ie(7,se(de)),ie(8,se(pe)),ie(9,se(Me)),ie(10,se(E)),ie(11,se(Pt)),ie(12,se(Se)),tg("design:paramtypes",[D,X,le,ue,we,U,Object,de,pe,Me,Object,Pt,Se])],xe)});import{Module as pg}from"@nestjs/common";var dg,Gt,Wi=l(()=>{"use strict";_n();Jr();Ur();bu();Yr();Fi();Kr();dg=function(n,e,t,r){var o=arguments.length,i=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Gt=class{};Gt=dg([pg({imports:[$e,lt,dt,Hr],providers:[Pt,Se,xe],exports:[xe,Se]})],Gt)});import{Catch as mg}from"@nestjs/common";var fg,Zr,Fu=l(()=>{"use strict";R();fg=function(n,e,t,r){var o=arguments.length,i=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Zr=class{catch(e,t){t.switchToHttp().getResponse().status(e.httpStatus).json({error:e.message,...e.details??{}})}};Zr=fg([mg(_t)],Zr)});var v,ae=l(()=>{"use strict";R();v=class{schema;constructor(e){this.schema=e}transform(e){let t=this.schema.safeParse(e);if(!t.success){let r=t.error.issues.map(o=>`${o.path.join(".")||"(root)"}: ${o.message}`).join("; ");throw new h(`Validation failed: ${r}`)}return t.data}}});function Nu(n,e,t){if(!n)throw new g(`Workflow not found: ${e}`);if(n.appliesTo==="none")throw new h(`Cannot bind a View to workflow '${e}' because appliesTo is 'none'`);if(!Ua(n.appliesTo,t))throw new h(`subjectType '${t}' is not included in workflow '${e}' appliesTo`);return n}function Ju(n,e){if(!n)throw new g(`Workflow not found: ${e}`);if(n.appliesTo!=="none")throw new h(`WorkflowShortcut requires appliesTo 'none', got '${String(n.appliesTo)}'`);if(n.subjectHandling!=="per-subject")throw new h(`WorkflowShortcut requires subjectHandling 'per-subject', got '${n.subjectHandling}'`);return n}function Lu(n){if(n.appliesTo==="none"&&n.subjectHandling==="collection")throw new h("Workflows with appliesTo 'none' must use subjectHandling 'per-subject'")}var eo=l(()=>{"use strict";C();R()});import{randomUUID as hg}from"node:crypto";function gg(){return hg()}function Uu(n){let e=n.id??gg(),t=ka(n.steps),r=Mu(n.steps,t);return{...n,id:e,steps:r}}function Mu(n,e){return n.map(t=>{let r=t.id;return r||(r=Ea(t.name,e),e.add(r)),t.type==="loop"?{...t,id:r,steps:Mu(t.steps,e)}:{...t,id:r}})}var Wu=l(()=>{"use strict";C()});function Hu(n){return n.issues.map(e=>`${e.path.join(".")||"(root)"}: ${e.message}`).join("; ")}function Hi(n){let e=it.safeParse(n);if(!e.success)throw new h(`Validation failed: ${Hu(e.error)}`);return e.data}function Gu(n){let e=Uu(n),t=xn.safeParse(e);if(!t.success)throw new h(`Validation failed: ${Hu(t.error)}`);return Lu(t.data),t.data}async function ht(n,e){return n.create(Gu(Hi(e)))}async function to(n,e,t){let r=Gu({...t,id:e}),{id:o,...i}=r,s=await n.update(e,i);if(!s)throw new g(`Workflow not found: ${e}`);return s}var no=l(()=>{"use strict";C();R();eo();Wu()});import{z as At}from"zod";async function Vu(n,e){let t=Hi(e.workflowDefinition),r=t.id;if(!r)return{workflow:await ht(n,t),created:!0};let o=await n.get(r);if(!o)return{workflow:await ht(n,t),created:!0};if(e.resolution==="update")return{workflow:await to(n,r,t),created:!1};if(e.resolution==="create_new"){let{id:i,...s}=t;return{workflow:await ht(n,s),created:!0}}throw new B(`A workflow named '${o.name}' already exists`,{conflictingWorkflowId:o.id,conflictingWorkflowName:o.name})}var ro,Ku,Gi=l(()=>{"use strict";R();no();ro=At.object({workflowDefinition:At.unknown(),resolution:At.enum(["update","create_new"]).optional()}),Ku=At.object({error:At.string(),conflictingWorkflowId:At.string(),conflictingWorkflowName:At.string()})});import{z as yg}from"zod";function bg(n){if(n.type==="loop")return"not offered as `{{stepId}}` tokens; reference inner steps. Exit conditions use `until.stepId`.";let e=Wa(n,"ticket");return e.opaque?"opaque (`{{stepId}}` only; no known field paths)":e.isScalar?"scalar (`{{stepId}}`)":e.fields?.length?`${e.isArray?"array of objects with fields":"object fields"}: ${e.fields.join(", ")}`:"no extra field paths (`{{stepId}}` is still the whole output)"}function Sg(n){return n.type==="agent"?`agent (\`${n.outputFormat}\`)`:n.type==="interaction"?`interaction (\`${n.interaction}\`)`:n.type==="git"?`git (\`${n.operation}\`)`:n.type==="provider_action"?n.extendedAction?"provider_action (`extendedAction`)":`provider_action (\`${n.action}\`)`:n.type}function xg(){return Object.keys(vn).map(t=>{let r=vn[t].map(o=>`\`{{subject.${o}}}\``).join(", ");return`- **${t}**: ${r}`}).join(`
24
+ `)}function vg(){return Object.keys(Qu).map(n=>`- **${n}**: ${Qu[n]}`).join(`
25
+ `)}function jg(){return wg.map(n=>`- **${Sg(n)}**: ${bg(n)}`).join(`
26
+ `)}function zu(n=er){let e=yg.toJSONSchema(n),t=JSON.stringify(e,null,2);return`# Knoflows workflow authoring instructions
27
+
28
+ Knoflows is a local workflow automation engine for software engineering tasks. A workflow is a pipeline of steps. It can run against a **subject** \u2014 a ticket, pull request, or documentation page \u2014 or standalone (\`appliesTo: "none"\`).
29
+
30
+ Steps are either **deterministic** (shell, git, provider_action, extract, sub_workflow, loop) or **agent-driven** (\`agent\`, often paired with an \`interaction\` pause for a human). Data threads between steps with \`{{path}}\` templating: the engine substitutes those tokens from the job subject, workflow inputs, and earlier step outputs when a step runs.
31
+
32
+ This document is generated from the live Engine schemas. Treat the JSON Schema block as the source of truth for every currently supported step type's fields. A one-line blurb below may go stale; a field list in that schema cannot, because it is derived from the same Zod schema the Engine validates against.
33
+
34
+ ## Workflow JSON file
35
+
36
+ Export produces a \`WorkflowDefinition\` with the workflow \`id\` and every step \`id\` preserved. Typical top-level fields: \`id\`, \`name\`, \`description\`, \`appliesTo\`, \`subjectHandling\`, \`inputSchema\`, \`steps\`, \`notificationPolicy\`.
37
+
38
+ When adding **new** steps, you may omit \`id\`; the Engine assigns one on import. Do not invent ids for existing steps \u2014 leave them untouched so templates keep resolving.
39
+
40
+ ## \`{{}}\` templating
41
+
42
+ Tokens of the form \`{{path}}\` are replaced when a step runs. Paths resolve against:
43
+
44
+ - workflow input fields (\`{{fieldName}}\` from \`inputSchema\`)
45
+ - the job subject (\`{{subject.field}}\` \u2014 see below)
46
+ - previous step outputs (\`{{stepId}}\` or \`{{stepId.field}}\`)
47
+
48
+ Inside a loop, each iteration overwrites that step's output; a later reference is the most recent pass.
49
+
50
+ ## Subject field reference
51
+
52
+ Known \`{{subject.field}}\` paths per \`SubjectType\` (same table as the builder's Available Parameters panel):
53
+
54
+ ${xg()}
55
+
56
+ Standalone workflows (\`appliesTo: "none"\`) have no subject; do not use \`{{subject.*}}\` there.
57
+
58
+ ## Step types (one-line descriptions)
59
+
60
+ Hand-maintained blurbs \u2014 cosmetic only. The JSON Schema below is authoritative for fields.
61
+
62
+ ${vg()}
63
+
64
+ ## Step definition JSON Schema
65
+
66
+ Generated with \`z.toJSONSchema()\` from the live \`StepDefinition\` discriminated union. This is the exact shape the Engine validates.
67
+
68
+ \`\`\`json
69
+ ${t}
70
+ \`\`\`
71
+
72
+ ## Step output shapes
73
+
74
+ When a later step uses \`{{step-id}}\` or \`{{step-id.field}}\`, these are the fields the Engine actually produces. Generated from \`getStepOutputShape\` (the same helper as Available Parameters).
75
+
76
+ ${jg()}
77
+
78
+ For \`get_subject\` without \`target\`, fields depend on the workflow's \`appliesTo\` subject type(s).
79
+
80
+ ## Provider-instance portability
81
+
82
+ \`provider_action.target\` and \`provider_action.extendedAction\` require a specific, already-configured provider instance id (\`source\` / \`providerId\`). An agent working from this file alone cannot invent those ids \u2014 they must match this Knoflows install's configured instances. Portable \`action\` values (\`get_subject\`, \`get_comments\`, \`post_comment\`, \`update_status\`, \`get_content\`) do not need an instance id unless \`target\` or \`extendedAction\` is set.
83
+
84
+ \`sub_workflow.workflowId\` likewise refers to a workflow that must already exist on the destination install. A dangling id after import shows the same inline mismatch warning used for missing provider instances; this file does not bundle dependencies.
85
+
86
+ ## Do not rename step ids without updating references
87
+
88
+ Step \`id\`s are referenced internally via \`{{step-id}}\` templates and \`loop.until.stepId\`. Renaming a step id requires updating every reference to it elsewhere in the same file, or those references will silently fail to resolve at runtime.
89
+
90
+ This risk is scoped to **future** runs of the edited workflow only. Each Job stores a \`workflowSnapshot\` \u2014 a frozen copy of the definition as it existed when that Job started \u2014 so already-run Job history is completely unaffected by later edits.
91
+ `}var Qu,wg,Xu=l(()=>{"use strict";C();Qu={agent:"Calls a coding agent with an objective; output shape depends on outputFormat.",interaction:"Pauses the job for a human (questionnaire, confirmation, conversation, or comment review).",shell:"Runs a shell command and captures exitCode, stdout, and stderr.",git:"Performs a git operation (worktree, checkout, branch, commit, or push).",provider_action:"Runs a portable provider action, or an instance-specific extendedAction.",sub_workflow:"Fans out a child workflow for each selected subject.",loop:"Repeats nested steps until an exit condition or maxIterations.",extract:"Pulls a value from a previous step or subject using a path and/or regex."},wg=[{type:"agent",id:"agent-free-text",name:"Agent",objective:"x",outputFormat:"free_text"},{type:"agent",id:"agent-questionnaire",name:"Agent",objective:"x",outputFormat:"questionnaire"},{type:"agent",id:"agent-confirmation",name:"Agent",objective:"x",outputFormat:"confirmation"},{type:"agent",id:"agent-comment-suggestions",name:"Agent",objective:"x",outputFormat:"comment_suggestions"},{type:"interaction",id:"interaction",name:"Interaction",interaction:"questionnaire"},{type:"interaction",id:"comment-review",name:"Review comments",interaction:"comment_review",sourceStepIds:["agent-comment-suggestions"]},{type:"shell",id:"shell",name:"Shell",command:"echo"},{type:"git",id:"git-worktree",name:"Git",operation:"create_worktree",params:{}},{type:"git",id:"git-commit",name:"Git",operation:"commit",params:{}},{type:"git",id:"git-push",name:"Git",operation:"push",params:{}},{type:"provider_action",id:"get-subject",name:"Get subject",action:"get_subject"},{type:"provider_action",id:"get-comments",name:"Get comments",action:"get_comments"},{type:"provider_action",id:"get-content",name:"Get content",action:"get_content"},{type:"provider_action",id:"post-comment",name:"Post comment",action:"post_comment"},{type:"provider_action",id:"extended-action",name:"Extended",action:"get_subject",extendedAction:{providerId:"example",actionId:"custom"}},{type:"sub_workflow",id:"sub-workflow",name:"Sub workflow",workflowId:"child",forEach:"selection"},{type:"loop",id:"loop",name:"Loop",maxIterations:1,onMaxIterations:{action:"fail"},until:{type:"field_empty",stepId:"inner",field:"x"},steps:[]},{type:"extract",id:"extract",name:"Extract",source:"{{subject.description}}",path:"title",onNoMatch:"fail"}]});import{Body as Ki,Controller as _g,Delete as Ig,Get as oo,Header as Eg,HttpCode as Pg,Inject as Rg,Param as io,Patch as kg,Post as Yu,Query as Ag,Res as Zu}from"@nestjs/common";var We,T,ve,me,el=l(()=>{"use strict";C();St();R();ae();no();Gi();Xu();We=function(n,e,t,r){var o=arguments.length,i=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},T=function(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)},ve=function(n,e){return function(t,r){e(t,r,n)}},me=class{workflows;constructor(e){this.workflows=e}async list(e){if(e!=null&&e!==""&&e!=="per-subject"&&e!=="collection")throw new h(`Invalid subjectHandling filter: ${e}`);return this.workflows.list(e?{subjectHandling:e}:{})}instructions(){return zu()}async importDefinition(e,t){let r=await Vu(this.workflows,e);return t.status(r.created?201:200),r.workflow}async exportDefinition(e,t){let r=await this.workflows.get(e);if(!r)throw new g(`Workflow not found: ${e}`);let o=`${ri(r.name)}.json`;return t.setHeader("Content-Disposition",`attachment; filename="${o}"`),r}async get(e){let t=await this.workflows.get(e);if(!t)throw new g(`Workflow not found: ${e}`);return t}async create(e){return ht(this.workflows,e)}async update(e,t){return to(this.workflows,e,t)}async remove(e){if(!await this.workflows.get(e))throw new g(`Workflow not found: ${e}`);if(!await this.workflows.delete(e))throw new g(`Workflow not found: ${e}`)}};We([oo(),ve(0,Ag("subjectHandling")),T("design:type",Function),T("design:paramtypes",[String]),T("design:returntype",Promise)],me.prototype,"list",null);We([oo("instructions"),Eg("Content-Type","text/markdown; charset=utf-8"),T("design:type",Function),T("design:paramtypes",[]),T("design:returntype",String)],me.prototype,"instructions",null);We([Yu("import"),ve(0,Ki(new v(ro))),ve(1,Zu({passthrough:!0})),T("design:type",Function),T("design:paramtypes",[Object,Object]),T("design:returntype",Promise)],me.prototype,"importDefinition",null);We([oo(":id/export"),ve(0,io("id")),ve(1,Zu({passthrough:!0})),T("design:type",Function),T("design:paramtypes",[String,Object]),T("design:returntype",Promise)],me.prototype,"exportDefinition",null);We([oo(":id"),ve(0,io("id")),T("design:type",Function),T("design:paramtypes",[String]),T("design:returntype",Promise)],me.prototype,"get",null);We([Yu(),ve(0,Ki()),T("design:type",Function),T("design:paramtypes",[Object]),T("design:returntype",Promise)],me.prototype,"create",null);We([kg(":id"),ve(0,io("id")),ve(1,Ki(new v(it))),T("design:type",Function),T("design:paramtypes",[String,Object]),T("design:returntype",Promise)],me.prototype,"update",null);We([Ig(":id"),Pg(204),ve(0,io("id")),T("design:type",Function),T("design:paramtypes",[String]),T("design:returntype",Promise)],me.prototype,"remove",null);me=We([_g("workflows"),ve(0,Rg(D)),T("design:paramtypes",[D])],me)});function Cg(n){return nl(n.workflowDefinition.steps,"steps")}function tl(n){let e=Cg(n);if(e.length>0)throw new Error(`Workflow library entry '${n.id}' is not portable: ${e.join(", ")}`)}function nl(n,e){let t=[];return n.forEach((r,o)=>{let i=`${e}[${o}]`;r.type==="provider_action"&&(r.target&&t.push(`${i}.target`),r.extendedAction&&t.push(`${i}.extendedAction`)),r.type==="loop"&&t.push(...nl(r.steps,`${i}.steps`))}),t}var rl=l(()=>{"use strict"});function ol(){return structuredClone(Vi)}function il(n){let e=Vi.find(t=>t.id===n);return e?structuredClone(e):void 0}var Tg,Og,Vi,sl=l(()=>{"use strict";rl();Tg={id:"clarify-then-summarize",source:"example",name:"Clarify then summarize",description:"Asks clarifying questions in a loop until none remain, then summarizes the answers.",workflowDefinition:{name:"Clarify then summarize",description:"Asks clarifying questions in a loop until none remain, then summarizes the answers.",appliesTo:"none",subjectHandling:"per-subject",inputSchema:[{name:"topic",label:"Topic",type:"string",required:!0}],steps:[{type:"loop",name:"Clarify",steps:[{type:"agent",name:"Draft questions",objective:"Draft clarifying questions about {{topic}}. If you have no remaining questions, return an empty list.",outputFormat:"questionnaire"},{type:"interaction",name:"Collect answers",interaction:"questionnaire"}],until:{type:"field_empty",stepId:"draft-questions",field:"questions"},maxIterations:5,onMaxIterations:{action:"continue"}},{type:"agent",name:"Summarize",objective:"Produce a final summary for {{topic}} using these answers: {{collect-answers}}",outputFormat:"free_text"}],notificationPolicy:{triggers:["on_needs_input","on_complete","on_fail"]}}},Og={id:"pr-review",source:"example",name:"PR Review",description:"Reviews a pull request for acceptance criteria, code quality, and test coverage.",workflowDefinition:{name:"PR Review",description:"Reviews a pull request for acceptance criteria, code quality, and test coverage.",appliesTo:"pull_request",subjectHandling:"per-subject",inputSchema:[{name:"repoPath",label:"Repository path",type:"localRepository",required:!0},{name:"ticketDescription",label:"Related ticket description (optional)",type:"string",required:!1}],steps:[{type:"git",name:"Prepare review worktree",operation:"create_worktree",params:{repoPath:"{{repoPath}}",baseBranch:"{{subject.sourceBranch}}",branchName:"review/{{subject.id}}"}},{type:"agent",name:"Build requirements checklist",objective:`Ticket: {{ticketDescription}}
24
92
  PR title: {{subject.title}}
25
93
  PR description: {{subject.description}}
26
94
 
@@ -30,5 +98,5 @@ Checklist: {{build-requirements-checklist}}`,outputFormat:"free_text"},{type:"sh
30
98
  {{run-relevant-tests}}`,outputFormat:"free_text"},{type:"agent",name:"Generate combined review report",objective:`Combine into one markdown report: Summary, Acceptance Criteria, Findings by Role, Tests Run, Suggested PR Comments, Verdict (APPROVE/COMMENT/REQUEST_CHANGES).
31
99
  Acceptance: {{acceptance-criteria-review}}
32
100
  Code quality: {{code-quality-review}}
33
- Testing: {{testing-review}}`,outputFormat:"free_text"}],notificationPolicy:{triggers:["on_fail","on_complete"]}}},ki=[Eh,Ph];for(let r of ki)bu(r)});import{Controller as Rh,Get as kh,Inject as Ah,Param as Ch,Post as Th}from"@nestjs/common";var Ai,jt,_u,Ut,Eu=l(()=>{"use strict";mt();R();ju();Pi();Ai=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},jt=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},_u=function(r,e){return function(t,n){e(t,n,r)}},Ut=class{workflows;constructor(e){this.workflows=e}list(){return vu()}async add(e){let t=Iu(e);if(!t)throw new y(`Workflow library entry not found: ${e}`);let n=structuredClone(t.workflowDefinition);return delete n.id,Hn(this.workflows,n)}};Ai([kh(),jt("design:type",Function),jt("design:paramtypes",[]),jt("design:returntype",Array)],Ut.prototype,"list",null);Ai([Th(":id/add"),_u(0,Ch("id")),jt("design:type",Function),jt("design:paramtypes",[String]),jt("design:returntype",Promise)],Ut.prototype,"add",null);Ut=Ai([Rh("workflow-library"),_u(0,Ah(O)),jt("design:paramtypes",[O])],Ut)});import{Body as Ti,Controller as Oh,Delete as $h,Get as Oi,HttpCode as qh,Inject as Ci,Param as Vn,Patch as Pu,Post as Bh,Query as Dh}from"@nestjs/common";var lt,T,be,Se,Ru=l(()=>{"use strict";C();qr();mt();R();ne();Sr();Bt();wi();lt=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},T=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},be=function(r,e){return function(t,n){e(t,n,r)}},Se=class{views;workflows;providers;constructor(e,t,n){this.views=e,this.workflows=t,this.providers=n}async list(e){if(e!=null&&e!==""){let t=re.safeParse(e);if(!t.success)throw new h(`Invalid subjectType filter: ${e}`);return this.views.list({subjectType:t.data})}return this.views.list({})}async reorder(e){let t=[];for(let i of e.viewIds){let s=await this.views.get(i);if(!s)throw new h(`Unknown view id in reorder: ${i}`);t.push(s)}if(new Set(t.map(i=>i.subjectType)).size!==1)throw new h("All viewIds in a reorder request must share the same subjectType");return await this.views.reorder(e.viewIds)}async listSubjects(e){return Bn(e,this.views,this.providers)}async get(e){let t=await this.views.get(e);if(!t)throw new y(`SubjectView not found: ${e}`);return t}async create(e){return await this.assertBinding(e.workflowId,e.subjectType),this.views.create(e)}async update(e,t){let n=await this.views.get(e);if(!n)throw new y(`SubjectView not found: ${e}`);await this.assertBinding(t.workflowId??n.workflowId,t.subjectType??n.subjectType);let o=await this.views.update(e,t);if(!o)throw new y(`SubjectView not found: ${e}`);return o}async remove(e){if(!await this.views.delete(e))throw new y(`SubjectView not found: ${e}`)}async assertBinding(e,t){let n=await this.workflows.get(e);fu(n,e,t)}};lt([Oi(),be(0,Dh("subjectType")),T("design:type",Function),T("design:paramtypes",[String]),T("design:returntype",Promise)],Se.prototype,"list",null);lt([Pu("reorder"),be(0,Ti(new v(Mr))),T("design:type",Function),T("design:paramtypes",[Object]),T("design:returntype",Promise)],Se.prototype,"reorder",null);lt([Oi(":id/subjects"),be(0,Vn("id")),T("design:type",Function),T("design:paramtypes",[String]),T("design:returntype",Promise)],Se.prototype,"listSubjects",null);lt([Oi(":id"),be(0,Vn("id")),T("design:type",Function),T("design:paramtypes",[String]),T("design:returntype",Promise)],Se.prototype,"get",null);lt([Bh(),be(0,Ti(new v(Lr))),T("design:type",Function),T("design:paramtypes",[Object]),T("design:returntype",Promise)],Se.prototype,"create",null);lt([Pu(":id"),be(0,Vn("id")),be(1,Ti(new v(Ur))),T("design:type",Function),T("design:paramtypes",[String,Object]),T("design:returntype",Promise)],Se.prototype,"update",null);lt([$h(":id"),qh(204),be(0,Vn("id")),T("design:type",Function),T("design:paramtypes",[String]),T("design:returntype",Promise)],Se.prototype,"remove",null);Se=lt([Oh("views"),be(0,Ci(ie)),be(1,Ci(O)),be(2,Ci(F)),T("design:paramtypes",[ie,O,F])],Se)});import{Body as $i,Controller as Fh,Delete as Nh,Get as Au,HttpCode as Jh,Inject as ku,Param as qi,Patch as Cu,Post as Lh}from"@nestjs/common";var _t,q,dt,ke,Tu=l(()=>{"use strict";C();Jo();mt();R();ne();Sr();_t=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},q=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},dt=function(r,e){return function(t,n){e(t,n,r)}},ke=class{shortcuts;workflows;constructor(e,t){this.shortcuts=e,this.workflows=t}async list(){return this.shortcuts.list()}async reorder(e){for(let t of e.shortcutIds)if(!await this.shortcuts.get(t))throw new h(`Unknown shortcut id in reorder: ${t}`);return this.shortcuts.reorder(e.shortcutIds)}async get(e){let t=await this.shortcuts.get(e);if(!t)throw new y(`WorkflowShortcut not found: ${e}`);return t}async create(e){return await this.assertBinding(e.workflowId),this.shortcuts.create(e)}async update(e,t){let n=await this.shortcuts.get(e);if(!n)throw new y(`WorkflowShortcut not found: ${e}`);await this.assertBinding(t.workflowId??n.workflowId);let o=await this.shortcuts.update(e,t);if(!o)throw new y(`WorkflowShortcut not found: ${e}`);return o}async remove(e){if(!await this.shortcuts.delete(e))throw new y(`WorkflowShortcut not found: ${e}`)}async assertBinding(e){let t=await this.workflows.get(e);mu(t,e)}};_t([Au(),q("design:type",Function),q("design:paramtypes",[]),q("design:returntype",Promise)],ke.prototype,"list",null);_t([Cu("reorder"),dt(0,$i(new v(en))),q("design:type",Function),q("design:paramtypes",[Object]),q("design:returntype",Promise)],ke.prototype,"reorder",null);_t([Au(":id"),dt(0,qi("id")),q("design:type",Function),q("design:paramtypes",[String]),q("design:returntype",Promise)],ke.prototype,"get",null);_t([Lh(),dt(0,$i(new v(Yr))),q("design:type",Function),q("design:paramtypes",[Object]),q("design:returntype",Promise)],ke.prototype,"create",null);_t([Cu(":id"),dt(0,qi("id")),dt(1,$i(new v(Zr))),q("design:type",Function),q("design:paramtypes",[String,Object]),q("design:returntype",Promise)],ke.prototype,"update",null);_t([Nh(":id"),Jh(204),dt(0,qi("id")),q("design:type",Function),q("design:paramtypes",[String]),q("design:returntype",Promise)],ke.prototype,"remove",null);ke=_t([Fh("workflow-shortcuts"),dt(0,ku(qe)),dt(1,ku(O)),q("design:paramtypes",[qe,O])],ke)});function Kn(r,e,t=50){let n=r!=null&&r!==""?Number(r):t,o=e!=null&&e!==""?Number(e):0;return!Number.isFinite(n)||n<1?{limit:t,offset:Math.max(0,o||0)}:!Number.isFinite(o)||o<0?{limit:n,offset:0}:{limit:Math.floor(n),offset:Math.floor(o)}}function Gn(r,e,t){return r.slice(t,t+e)}var Bi=l(()=>{"use strict"});import{z as X}from"zod";var zn,Qn,Xn,Yn,Di=l(()=>{"use strict";zn=X.object({workflowId:X.string().min(1),subjectId:X.string().min(1).optional(),inputValues:X.record(X.string(),X.unknown())}),Qn=X.object({response:X.unknown()}),Xn=X.object({workflowId:X.string().min(1),subjectIds:X.array(X.string().min(1))}),Yn=X.object({jobIds:X.array(X.string().min(1)).min(1)})});import{Body as Zn,Controller as Uh,Get as $u,HttpCode as qu,Inject as Ou,Param as xr,Post as Et,Query as Je}from"@nestjs/common";import"zod";function Fi(r,e){if(!(r==null||r==="")){if(r==="true")return!0;if(r==="false")return!1;throw new h(`Invalid ${e} filter: ${r}`)}}var Ae,k,$,Mh,oe,Bu=l(()=>{"use strict";Ln();pr();R();ne();Bi();Di();Ae=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},k=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},$=function(r,e){return function(t,n){e(t,n,r)}},Mh=["pending","planning","waiting_for_human","waiting_for_children","implementing","testing","completed","failed","cancelled"];oe=class{jobs;runner;constructor(e,t){this.jobs=e,this.runner=t}async list(e,t,n,o,i,s,a,u,c){if(t!=null&&t!==""&&!Mh.includes(t))throw new h(`Invalid status filter: ${t}`);let p=Fi(i,"topLevelOnly"),m=Fi(s,"terminal"),b=Fi(a,"liveWorktree"),{limit:S,offset:j}=Kn(u,c),N=await this.jobs.list({...e?{workflowId:e}:{},...t?{status:t}:{},...n?{batchId:n}:{},...o?{parentJobId:o}:{},...p===!0?{topLevelOnly:!0}:{},...m!==void 0?{terminal:m}:{},...b===!0?{liveWorktree:!0}:{}});return Gn(N,S,j)}async latestBySubject(e){return this.jobs.latestBySubject(e.workflowId,e.subjectIds)}async deleteWorktrees(e){return this.runner.deleteWorktrees(e.jobIds)}async get(e){let t=await this.jobs.get(e);if(!t)throw new y(`Job not found: ${e}`);return t}async create(e){return this.runner.start({workflowId:e.workflowId,...e.subjectId?{subjectId:e.subjectId}:{},inputValues:e.inputValues})}async resume(e,t){return this.runner.resume(e,t.response)}async retry(e){return this.runner.retryFailedJob(e)}async retryStep(e){return this.runner.retryFailedStep(e)}async cancel(e){return this.runner.cancelJob(e)}};Ae([$u(),$(0,Je("workflowId")),$(1,Je("status")),$(2,Je("batchId")),$(3,Je("parentJobId")),$(4,Je("topLevelOnly")),$(5,Je("terminal")),$(6,Je("liveWorktree")),$(7,Je("limit")),$(8,Je("offset")),k("design:type",Function),k("design:paramtypes",[String,String,String,String,String,String,String,String,String]),k("design:returntype",Promise)],oe.prototype,"list",null);Ae([Et("latest-by-subject"),qu(200),$(0,Zn(new v(Xn))),k("design:type",Function),k("design:paramtypes",[Object]),k("design:returntype",Promise)],oe.prototype,"latestBySubject",null);Ae([Et("delete-worktrees"),qu(200),$(0,Zn(new v(Yn))),k("design:type",Function),k("design:paramtypes",[Object]),k("design:returntype",Promise)],oe.prototype,"deleteWorktrees",null);Ae([$u(":id"),$(0,xr("id")),k("design:type",Function),k("design:paramtypes",[String]),k("design:returntype",Promise)],oe.prototype,"get",null);Ae([Et(),$(0,Zn(new v(zn))),k("design:type",Function),k("design:paramtypes",[Object]),k("design:returntype",Promise)],oe.prototype,"create",null);Ae([Et(":id/resume"),$(0,xr("id")),$(1,Zn(new v(Qn))),k("design:type",Function),k("design:paramtypes",[String,Object]),k("design:returntype",Promise)],oe.prototype,"resume",null);Ae([Et(":id/retry"),$(0,xr("id")),k("design:type",Function),k("design:paramtypes",[String]),k("design:returntype",Promise)],oe.prototype,"retry",null);Ae([Et(":id/retry-step"),$(0,xr("id")),k("design:type",Function),k("design:paramtypes",[String]),k("design:returntype",Promise)],oe.prototype,"retryStep",null);Ae([Et(":id/cancel"),$(0,xr("id")),k("design:type",Function),k("design:paramtypes",[String]),k("design:returntype",Promise)],oe.prototype,"cancel",null);oe=Ae([Uh("jobs"),$(0,Ou(z)),$(1,Ou(we)),k("design:paramtypes",[z,we])],oe)});import{z as te}from"zod";var eo,to,Ni=l(()=>{"use strict";C();eo=te.discriminatedUnion("mode",[te.object({mode:te.literal("view"),viewId:te.string().min(1)}),te.object({mode:te.literal("manual"),subjectType:re,subjectIds:te.array(te.string().min(1))})]),to=te.object({workflowId:te.string().min(1),selection:eo,triggeredBy:te.enum(["schedule","view_bulk","multiselect"]),notificationOverride:fr.optional(),inputValues:te.record(te.string(),te.unknown())})});import{Body as Wh,Controller as Hh,Get as Ui,Inject as Ji,Param as Mi,Post as Du,Query as Li}from"@nestjs/common";import"zod";var Mt,M,Ce,Le,Fu=l(()=>{"use strict";Ln();Br();pr();R();ne();Bi();Ni();Mt=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},M=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},Ce=function(r,e){return function(t,n){e(t,n,r)}},Le=class{batches;jobs;runner;constructor(e,t,n){this.batches=e,this.jobs=t,this.runner=n}async list(e,t,n){let{limit:o,offset:i}=Kn(t,n),s=await this.batches.list(e?{workflowId:e}:{});return Gn(s,o,i)}async get(e){let t=await this.batches.get(e);if(!t)throw new y(`JobBatch not found: ${e}`);return t}async listJobs(e){if(!await this.batches.get(e))throw new y(`JobBatch not found: ${e}`);return this.jobs.list({batchId:e})}async launch(e){let t=await this.runner.launch({workflowId:e.workflowId,selection:e.selection,triggeredBy:e.triggeredBy,...e.notificationOverride?{notificationOverride:e.notificationOverride}:{},inputValues:e.inputValues});return"resolvedSubjects"in t&&"jobIds"in t?{kind:"batch",batch:t}:{kind:"job",job:t}}async cancel(e){return this.runner.cancelBatch(e)}};Mt([Ui(),Ce(0,Li("workflowId")),Ce(1,Li("limit")),Ce(2,Li("offset")),M("design:type",Function),M("design:paramtypes",[String,String,String]),M("design:returntype",Promise)],Le.prototype,"list",null);Mt([Ui(":id"),Ce(0,Mi("id")),M("design:type",Function),M("design:paramtypes",[String]),M("design:returntype",Promise)],Le.prototype,"get",null);Mt([Ui(":id/jobs"),Ce(0,Mi("id")),M("design:type",Function),M("design:paramtypes",[String]),M("design:returntype",Promise)],Le.prototype,"listJobs",null);Mt([Du(),Ce(0,Wh(new v(to))),M("design:type",Function),M("design:paramtypes",[Object]),M("design:returntype",Promise)],Le.prototype,"launch",null);Mt([Du(":id/cancel"),Ce(0,Mi("id")),M("design:type",Function),M("design:paramtypes",[String]),M("design:returntype",Promise)],Le.prototype,"cancel",null);Le=Mt([Hh("batches"),Ce(0,Ji(se)),Ce(1,Ji(z)),Ce(2,Ji(we)),M("design:paramtypes",[se,z,we])],Le)});import{Body as Nu,Controller as Vh,Delete as Kh,Get as Ju,HttpCode as Gh,Inject as zh,Param as Wi,Patch as Qh,Post as Xh,Query as Yh}from"@nestjs/common";var Wt,W,Pt,Ue,Lu=l(()=>{"use strict";C();Fo();R();ne();Wt=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},W=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},Pt=function(r,e){return function(t,n){e(t,n,r)}},Ue=class{schedules;constructor(e){this.schedules=e}async list(e){if(e==null||e==="")return this.schedules.list();if(e!=="true"&&e!=="false")throw new h(`Invalid enabled filter: ${e}`);return this.schedules.list({enabled:e==="true"})}async get(e){let t=await this.schedules.get(e);if(!t)throw new y(`Schedule not found: ${e}`);return t}async create(e){return this.schedules.create(e)}async update(e,t){let n=await this.schedules.update(e,t);if(!n)throw new y(`Schedule not found: ${e}`);return n}async remove(e){if(!await this.schedules.delete(e))throw new y(`Schedule not found: ${e}`)}};Wt([Ju(),Pt(0,Yh("enabled")),W("design:type",Function),W("design:paramtypes",[String]),W("design:returntype",Promise)],Ue.prototype,"list",null);Wt([Ju(":id"),Pt(0,Wi("id")),W("design:type",Function),W("design:paramtypes",[String]),W("design:returntype",Promise)],Ue.prototype,"get",null);Wt([Xh(),Pt(0,Nu(new v(Ot))),W("design:type",Function),W("design:paramtypes",[Object]),W("design:returntype",Promise)],Ue.prototype,"create",null);Wt([Qh(":id"),Pt(0,Wi("id")),Pt(1,Nu(new v(Ot.partial().omit({id:!0})))),W("design:type",Function),W("design:paramtypes",[String,Object]),W("design:returntype",Promise)],Ue.prototype,"update",null);Wt([Kh(":id"),Gh(204),Pt(0,Wi("id")),W("design:type",Function),W("design:paramtypes",[String]),W("design:returntype",Promise)],Ue.prototype,"remove",null);Ue=Wt([Vh("schedules"),Pt(0,zh($e)),W("design:paramtypes",[$e])],Ue)});import{Controller as Zh,Inject as ey,Query as Uu,Sse as ty}from"@nestjs/common";import{Observable as Wu}from"rxjs";var Mu,ro,Hi,vr,Hu=l(()=>{"use strict";Tn();Mu=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},ro=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},Hi=function(r,e){return function(t,n){e(t,n,r)}},vr=class{events;constructor(e){this.events=e}stream(e,t){return new Wu(n=>{let o=this.events.subscribe(i=>{let s=i;e!=null&&e!==""&&(!("jobId"in s)||s.jobId!==e)||t!=null&&t!==""&&(!("batchId"in s)||s.batchId!==t)||n.next({data:s})});return()=>{o()}})}};Mu([ty(),Hi(0,Uu("jobId")),Hi(1,Uu("batchId")),ro("design:type",Function),ro("design:paramtypes",[String,String]),ro("design:returntype",Wu)],vr.prototype,"stream",null);vr=Mu([Zh("events"),Hi(0,ey(ye)),ro("design:paramtypes",[ye])],vr)});import{extendZodWithOpenApi as ry}from"@asteasolutions/zod-to-openapi";import{z as ny}from"zod";var Vu=l(()=>{"use strict";ry(ny)});import{z as Ku}from"zod";var no,Vi=l(()=>{"use strict";no=Ku.object({value:Ku.string().min(1)})});import{z as xe}from"zod";var HE,oy,Gu,zu=l(()=>{"use strict";HE=xe.object({path:xe.string().optional(),mode:xe.enum(["directories","files"]).optional(),extensions:xe.string().optional()}),oy=xe.object({name:xe.string().min(1),path:xe.string().min(1),isDirectory:xe.boolean()}),Gu=xe.object({path:xe.string().min(1),entries:xe.array(oy)})});import{z as d}from"zod";function jy(r){let e=d.toJSONSchema(r),{$schema:t,...n}=e;return n}function Xu(r){let e=(t,n)=>r.registerComponent("schemas",t,jy(n)).ref;return{WorkflowDefinition:e("WorkflowDefinition",ht),WorkflowDefinitionInput:e("WorkflowDefinitionInput",tt),UpdateWorkflowBody:e("UpdateWorkflowBody",yy),SubjectView:e("SubjectView",Jr),CreateSubjectViewBody:e("CreateSubjectViewBody",Lr),ReorderViewsBody:e("ReorderViewsBody",Mr),UpdateViewBody:e("UpdateViewBody",wy),WorkflowShortcut:e("WorkflowShortcut",Xr),CreateWorkflowShortcutBody:e("CreateWorkflowShortcutBody",Yr),UpdateWorkflowShortcutBody:e("UpdateWorkflowShortcutBody",Zr),ReorderShortcutsBody:e("ReorderShortcutsBody",en),Schedule:e("Schedule",Ot),UpdateScheduleBody:e("UpdateScheduleBody",by),EngineSettings:e("EngineSettings",rn),UpdateSettingsBody:e("UpdateSettingsBody",xy),SettingsPatchResponse:e("SettingsPatchResponse",Iy),ProviderInstanceConfig:e("ProviderInstanceConfig",tn),CreateProviderInstanceBody:e("CreateProviderInstanceBody",on),UpdateProviderInstanceBody:e("UpdateProviderInstanceBody",sn),ProviderInstanceMutationResponse:e("ProviderInstanceMutationResponse",vy),SetSecretBody:e("SetSecretBody",no),CreateJobBody:e("CreateJobBody",zn),ResumeJobBody:e("ResumeJobBody",Qn),LatestBySubjectBody:e("LatestBySubjectBody",Xn),LatestBySubjectResponse:e("LatestBySubjectResponse",Sy),LaunchBody:e("LaunchBody",to),Job:e("Job",Ki),JobBatch:e("JobBatch",Qu),LaunchResponse:e("LaunchResponse",dy),HealthResponse:e("HealthResponse",py),ProviderStatus:e("ProviderStatus",fy),QueryTemplate:e("QueryTemplate",ea),ProviderActionDescriptor:e("ProviderActionDescriptor",ta),PreviewModelsBody:e("PreviewModelsBody",an),PreviewModel:e("PreviewModel",Wa),ResolveQueryTemplateBody:e("ResolveQueryTemplateBody",Nr),ResolveQueryTemplateResponse:e("ResolveQueryTemplateResponse",ra),ErrorResponse:e("ErrorResponse",my),EngineEvent:e("EngineEvent",hy),Subject:e("Subject",oo),WorkflowLibraryEntry:e("WorkflowLibraryEntry",gy),ContextFile:e("ContextFile",Hr),CreateContextFileBody:e("CreateContextFileBody",Vr),UpdateContextFileBody:e("UpdateContextFileBody",Kr),LocalRepository:e("LocalRepository",Gr),CreateLocalRepositoryBody:e("CreateLocalRepositoryBody",zr),UpdateLocalRepositoryBody:e("UpdateLocalRepositoryBody",Qr),DeleteWorktreesBody:e("DeleteWorktreesBody",Yn),FilesystemBrowseResult:e("FilesystemBrowseResult",Gu)}}var iy,sy,ay,cy,oo,uy,ly,Ki,Qu,dy,py,fy,my,hy,yy,gy,wy,by,Sy,xy,vy,Iy,_,Gi,zi=l(()=>{"use strict";Vu();C();Di();Ni();Vi();zu();iy=d.enum(["pending","planning","waiting_for_human","waiting_for_children","implementing","testing","completed","failed","cancelled"]),sy=d.object({subjectType:d.literal("ticket"),id:d.string(),source:d.string().min(1),title:d.string(),description:d.string().optional(),status:d.string(),assignee:d.string().optional(),url:d.string().optional(),raw:d.record(d.string(),d.unknown()).optional()}),ay=d.object({subjectType:d.literal("pull_request"),id:d.string(),source:d.string().min(1),title:d.string(),description:d.string().optional(),sourceBranch:d.string(),targetBranch:d.string(),author:d.string().optional(),url:d.string().optional(),raw:d.record(d.string(),d.unknown()).optional()}),cy=d.object({subjectType:d.literal("documentation"),id:d.string(),source:d.string().min(1),title:d.string(),url:d.string().optional(),raw:d.record(d.string(),d.unknown()).optional()}),oo=d.discriminatedUnion("subjectType",[sy,ay,cy]),uy=d.discriminatedUnion("mode",[d.object({mode:d.literal("single"),subject:oo}),d.object({mode:d.literal("collection"),subjects:d.array(oo)})]),ly=d.object({id:d.string(),stepDefinitionId:d.string(),type:d.string(),status:d.enum(["pending","running","waiting_for_children","completed","failed","skipped"]),startedAt:d.string().optional(),completedAt:d.string().optional(),output:d.unknown().optional(),error:d.string().optional(),childJobIds:d.array(d.string()).optional(),iterations:d.array(d.object({index:d.number().int(),stepExecutions:d.array(d.record(d.string(),d.unknown())),startedAt:d.string(),completedAt:d.string().optional()})).optional()}),Ki=d.object({id:d.string(),workflowId:d.string(),status:iy,subjectContext:uy.optional(),selection:eo.optional(),batchId:d.string().optional(),parentJobId:d.string().optional(),parentStepExecutionId:d.string().optional(),fanOutIndex:d.number().int().optional(),retryOf:d.string().optional(),workflowSnapshot:ht.optional(),context:d.record(d.string(),d.unknown()),worktreePath:d.string().optional(),branch:d.string().optional(),worktreeDeletedAt:d.string().optional(),currentStepId:d.string().optional(),currentStepExecutionId:d.string().optional(),stepHistory:d.array(ly),createdAt:d.string(),updatedAt:d.string(),completedAt:d.string().optional()}),Qu=d.object({id:d.string(),workflowId:d.string(),selection:eo,resolvedSubjects:d.array(oo),jobIds:d.array(d.string()),status:d.enum(["running","completed","completed_with_issues","failed","cancelled"]),triggeredBy:d.enum(["schedule","view_bulk","multiselect"]),scheduleId:d.string().optional(),notificationOverride:fr.optional(),notificationSent:d.boolean(),createdAt:d.string(),completedAt:d.string().optional()}),dy=d.discriminatedUnion("kind",[d.object({kind:d.literal("job"),job:Ki}),d.object({kind:d.literal("batch"),batch:Qu})]),py=d.object({ok:d.boolean(),service:d.string(),timestamp:d.string()}),fy=d.object({providerId:d.string(),secretKey:d.string(),configured:d.boolean()}),my=d.object({error:d.string()}),hy=d.object({type:d.string(),timestamp:d.string()}).passthrough(),yy=tt,gy=d.object({id:d.string().min(1),source:d.enum(["example","community","official"]),name:d.string().min(1),description:d.string(),workflowDefinition:tt}),wy=Ur,by=Ot.partial().omit({id:!0}),Sy=d.record(d.string(),Ki.nullable()),xy=nn,vy=d.object({settings:rn,restartRequired:d.literal(!0)}),Iy=d.object({settings:rn,restartRequired:d.boolean()}),_=d.object({id:d.string().min(1)}),Gi=d.object({limit:d.string().optional().openapi({description:"Max items to return (default 50)"}),offset:d.string().optional().openapi({description:"Number of items to skip (default 0)"})})});import{z as I}from"zod";function g(r,e){return{description:e,content:{"application/json":{schema:r}}}}function B(r){return{type:"array",items:r}}function w(r,...e){let t={400:"Validation error",404:"Resource not found",409:"Conflict"};return Object.fromEntries(e.map(n=>[String(n),g(r.ErrorResponse,t[n]??"Error")]))}function Yu(r,e){r.registerPath({method:"get",path:"/health",tags:["Health"],summary:"Health check",responses:{200:g(e.HealthResponse,"Service is healthy")}}),r.registerPath({method:"get",path:"/workflows",tags:["Workflows"],summary:"List workflow definitions",request:{query:I.object({subjectHandling:I.enum(["per-subject","collection"]).optional()})},responses:{200:g(B(e.WorkflowDefinition),"Workflow definitions"),...w(e,400)}}),r.registerPath({method:"get",path:"/workflows/{id}",tags:["Workflows"],summary:"Get a workflow definition",request:{params:_},responses:{200:g(e.WorkflowDefinition,"Workflow definition"),...w(e,404)}}),r.registerPath({method:"post",path:"/workflows",tags:["Workflows"],summary:"Create a workflow definition",request:{body:{required:!0,content:{"application/json":{schema:e.WorkflowDefinitionInput}}}},responses:{201:g(e.WorkflowDefinition,"Created workflow definition"),...w(e,400)}}),r.registerPath({method:"patch",path:"/workflows/{id}",tags:["Workflows"],summary:"Update a workflow definition",request:{params:_,body:{required:!0,content:{"application/json":{schema:e.UpdateWorkflowBody}}}},responses:{200:g(e.WorkflowDefinition,"Updated workflow definition"),...w(e,400,404)}}),r.registerPath({method:"delete",path:"/workflows/{id}",tags:["Workflows"],summary:"Delete a workflow definition",description:"Deletes the live workflow definition. Running Jobs keep executing from the snapshot captured at Job creation.",request:{params:_},responses:{204:{description:"Workflow deleted"},...w(e,404)}}),r.registerPath({method:"get",path:"/workflow-library",tags:["Workflow Library"],summary:"List bundled workflow library entries",responses:{200:g(B(e.WorkflowLibraryEntry),"Workflow library entries")}}),r.registerPath({method:"post",path:"/workflow-library/{id}/add",tags:["Workflow Library"],summary:"Copy a library entry into the workspace as a new workflow",request:{params:_},responses:{201:g(e.WorkflowDefinition,"Created workflow definition"),...w(e,400,404)}}),r.registerPath({method:"get",path:"/views",tags:["Views"],summary:"List subject views",request:{query:I.object({subjectType:re.optional()})},responses:{200:g(B(e.SubjectView),"Subject views"),...w(e,400)}}),r.registerPath({method:"get",path:"/views/{id}",tags:["Views"],summary:"Get a subject view",request:{params:_},responses:{200:g(e.SubjectView,"Subject view"),...w(e,404)}}),r.registerPath({method:"get",path:"/views/{id}/subjects",tags:["Views"],summary:"Preview subjects matching a view",description:"Live provider query for the View's saved filter. Same resolution path as launch() for { mode: 'view' }. Does not create Jobs or snapshots.",request:{params:_},responses:{200:g(B(e.Subject),"Matching subjects"),...w(e,404,400)}}),r.registerPath({method:"patch",path:"/views/reorder",tags:["Views"],summary:"Reorder views within a subject type group",request:{body:{required:!0,content:{"application/json":{schema:e.ReorderViewsBody}}}},responses:{200:g(B(e.SubjectView),"Reordered views for the subject type"),...w(e,400)}}),r.registerPath({method:"post",path:"/views",tags:["Views"],summary:"Create a subject view",request:{body:{required:!0,content:{"application/json":{schema:e.CreateSubjectViewBody}}}},responses:{201:g(e.SubjectView,"Created subject view"),...w(e,400)}}),r.registerPath({method:"patch",path:"/views/{id}",tags:["Views"],summary:"Update a subject view",request:{params:_,body:{required:!0,content:{"application/json":{schema:e.UpdateViewBody}}}},responses:{200:g(e.SubjectView,"Updated subject view"),...w(e,400,404)}}),r.registerPath({method:"delete",path:"/views/{id}",tags:["Views"],summary:"Delete a subject view",request:{params:_},responses:{204:{description:"Subject view deleted"},...w(e,404)}}),r.registerPath({method:"get",path:"/jobs",tags:["Jobs"],summary:"List jobs",request:{query:Gi.extend({workflowId:I.string().optional(),status:I.enum(["pending","planning","waiting_for_human","waiting_for_children","implementing","testing","completed","failed","cancelled"]).optional(),batchId:I.string().optional(),parentJobId:I.string().optional(),topLevelOnly:I.enum(["true","false"]).optional().openapi({description:"When true, exclude jobs that belong to a batch or a parent (sub_workflow) job"}),terminal:I.enum(["true","false"]).optional().openapi({description:"When true, only completed/failed/cancelled jobs. When false, only in-progress jobs. Omitted: no terminality filter."}),liveWorktree:I.enum(["true","false"]).optional().openapi({description:"When true, only jobs with a worktreePath that has not been deleted from the management page."})})},responses:{200:g(B(e.Job),"Jobs"),...w(e,400)}}),r.registerPath({method:"post",path:"/jobs/delete-worktrees",tags:["Jobs"],summary:"Delete live worktree folders for terminal jobs",request:{body:{required:!0,content:{"application/json":{schema:e.DeleteWorktreesBody}}}},responses:{200:g(B(e.Job),"Jobs after worktree deletion"),...w(e,400,404,409)}}),r.registerPath({method:"get",path:"/jobs/{id}",tags:["Jobs"],summary:"Get a job",request:{params:_},responses:{200:g(e.Job,"Job"),...w(e,404)}}),r.registerPath({method:"post",path:"/jobs",tags:["Jobs"],summary:"Start a single job",request:{body:{required:!0,content:{"application/json":{schema:e.CreateJobBody}}}},responses:{201:g(e.Job,"Started job"),...w(e,400,404)}}),r.registerPath({method:"post",path:"/jobs/latest-by-subject",tags:["Jobs"],summary:"Latest job per subject for a workflow",request:{body:{required:!0,content:{"application/json":{schema:e.LatestBySubjectBody}}}},responses:{200:g(e.LatestBySubjectResponse,"Latest job keyed by subject id"),...w(e,400)}}),r.registerPath({method:"post",path:"/jobs/{id}/resume",tags:["Jobs"],summary:"Resume a job waiting for human input",request:{params:_,body:{required:!0,content:{"application/json":{schema:e.ResumeJobBody}}}},responses:{200:g(e.Job,"Resumed job"),...w(e,400,404,409)}}),r.registerPath({method:"post",path:"/jobs/{id}/retry",tags:["Jobs"],summary:"Retry a failed job as a new linked job",request:{params:_},responses:{200:g(e.Job,"Retry job"),...w(e,404,409)}}),r.registerPath({method:"post",path:"/jobs/{id}/retry-step",tags:["Jobs"],summary:"Retry the failed step of a job in place",request:{params:_},responses:{200:g(e.Job,"Job after retrying the failed step"),...w(e,404,409)}}),r.registerPath({method:"post",path:"/jobs/{id}/cancel",tags:["Jobs"],summary:"Cancel a non-terminal job",request:{params:_},responses:{200:g(e.Job,"Cancelled job"),...w(e,404,409)}}),r.registerPath({method:"get",path:"/batches",tags:["Batches"],summary:"List job batches",request:{query:Gi.extend({workflowId:I.string().optional()})},responses:{200:g(B(e.JobBatch),"Job batches")}}),r.registerPath({method:"get",path:"/batches/{id}",tags:["Batches"],summary:"Get a job batch",request:{params:_},responses:{200:g(e.JobBatch,"Job batch"),...w(e,404)}}),r.registerPath({method:"get",path:"/batches/{id}/jobs",tags:["Batches"],summary:"List jobs in a batch",request:{params:_},responses:{200:g(B(e.Job),"Jobs in the batch"),...w(e,404)}}),r.registerPath({method:"post",path:"/batches",tags:["Batches"],summary:"Launch a per-subject batch or collection run",description:"Resolves subject selection and starts a JobBatch for per-subject workflows (even for one subject) or a single Job for collection workflows.",request:{body:{required:!0,content:{"application/json":{schema:e.LaunchBody}}}},responses:{201:g(e.LaunchResponse,"Launch result"),...w(e,400,404)}}),r.registerPath({method:"post",path:"/batches/{id}/cancel",tags:["Batches"],summary:"Cancel a running job batch",request:{params:_},responses:{200:g(e.JobBatch,"Cancelled batch"),...w(e,404,409)}}),r.registerPath({method:"get",path:"/workflow-shortcuts",tags:["Workflow shortcuts"],summary:"List workflow shortcuts",responses:{200:g(B(e.WorkflowShortcut),"Workflow shortcuts")}}),r.registerPath({method:"get",path:"/workflow-shortcuts/{id}",tags:["Workflow shortcuts"],summary:"Get a workflow shortcut",request:{params:_},responses:{200:g(e.WorkflowShortcut,"Workflow shortcut"),...w(e,404)}}),r.registerPath({method:"post",path:"/workflow-shortcuts",tags:["Workflow shortcuts"],summary:"Create a workflow shortcut",request:{body:{required:!0,content:{"application/json":{schema:e.CreateWorkflowShortcutBody}}}},responses:{201:g(e.WorkflowShortcut,"Created workflow shortcut"),...w(e,400,404)}}),r.registerPath({method:"patch",path:"/workflow-shortcuts/reorder",tags:["Workflow shortcuts"],summary:"Reorder workflow shortcuts",request:{body:{required:!0,content:{"application/json":{schema:e.ReorderShortcutsBody}}}},responses:{200:g(B(e.WorkflowShortcut),"Reordered workflow shortcuts"),...w(e,400)}}),r.registerPath({method:"patch",path:"/workflow-shortcuts/{id}",tags:["Workflow shortcuts"],summary:"Update a workflow shortcut",request:{params:_,body:{required:!0,content:{"application/json":{schema:e.UpdateWorkflowShortcutBody}}}},responses:{200:g(e.WorkflowShortcut,"Updated workflow shortcut"),...w(e,400,404)}}),r.registerPath({method:"delete",path:"/workflow-shortcuts/{id}",tags:["Workflow shortcuts"],summary:"Delete a workflow shortcut",request:{params:_},responses:{204:{description:"Workflow shortcut deleted"},...w(e,404)}}),r.registerPath({method:"get",path:"/context-files",tags:["Context Files"],summary:"List context files",responses:{200:g(B(e.ContextFile),"Context files")}}),r.registerPath({method:"get",path:"/context-files/{id}",tags:["Context Files"],summary:"Get a context file",request:{params:_},responses:{200:g(e.ContextFile,"Context file"),...w(e,404)}}),r.registerPath({method:"post",path:"/context-files",tags:["Context Files"],summary:"Create a context file",request:{body:{required:!0,content:{"application/json":{schema:e.CreateContextFileBody}}}},responses:{201:g(e.ContextFile,"Created context file"),...w(e,400)}}),r.registerPath({method:"patch",path:"/context-files/{id}",tags:["Context Files"],summary:"Update a context file",request:{params:_,body:{required:!0,content:{"application/json":{schema:e.UpdateContextFileBody}}}},responses:{200:g(e.ContextFile,"Updated context file"),...w(e,400,404)}}),r.registerPath({method:"delete",path:"/context-files/{id}",tags:["Context Files"],summary:"Delete a context file",request:{params:_},responses:{204:{description:"Context file deleted"},...w(e,404)}}),r.registerPath({method:"get",path:"/local-repositories",tags:["Local Repositories"],summary:"List local repositories",responses:{200:g(B(e.LocalRepository),"Local repositories")}}),r.registerPath({method:"get",path:"/local-repositories/{id}",tags:["Local Repositories"],summary:"Get a local repository",request:{params:_},responses:{200:g(e.LocalRepository,"Local repository"),...w(e,404)}}),r.registerPath({method:"post",path:"/local-repositories",tags:["Local Repositories"],summary:"Create a local repository",request:{body:{required:!0,content:{"application/json":{schema:e.CreateLocalRepositoryBody}}}},responses:{201:g(e.LocalRepository,"Created local repository"),...w(e,400)}}),r.registerPath({method:"patch",path:"/local-repositories/{id}",tags:["Local Repositories"],summary:"Update a local repository",request:{params:_,body:{required:!0,content:{"application/json":{schema:e.UpdateLocalRepositoryBody}}}},responses:{200:g(e.LocalRepository,"Updated local repository"),...w(e,400,404)}}),r.registerPath({method:"delete",path:"/local-repositories/{id}",tags:["Local Repositories"],summary:"Delete a local repository",request:{params:_},responses:{204:{description:"Local repository deleted"},...w(e,404)}}),r.registerPath({method:"get",path:"/filesystem/browse",tags:["Filesystem"],summary:"List a host directory",request:{query:I.object({path:I.string().optional(),mode:I.enum(["directories","files"]).optional(),extensions:I.string().optional()})},responses:{200:g(e.FilesystemBrowseResult,"Directory listing"),...w(e,400)}}),r.registerPath({method:"get",path:"/schedules",tags:["Schedules"],summary:"List schedules",request:{query:I.object({enabled:I.enum(["true","false"]).optional()})},responses:{200:g(B(e.Schedule),"Schedules"),...w(e,400)}}),r.registerPath({method:"get",path:"/schedules/{id}",tags:["Schedules"],summary:"Get a schedule",request:{params:_},responses:{200:g(e.Schedule,"Schedule"),...w(e,404)}}),r.registerPath({method:"post",path:"/schedules",tags:["Schedules"],summary:"Create a schedule",description:"CRUD only \u2014 creating or enabling a schedule does not cause it to fire yet.",request:{body:{required:!0,content:{"application/json":{schema:e.Schedule}}}},responses:{201:g(e.Schedule,"Created schedule"),...w(e,400)}}),r.registerPath({method:"patch",path:"/schedules/{id}",tags:["Schedules"],summary:"Update a schedule",request:{params:_,body:{required:!0,content:{"application/json":{schema:e.UpdateScheduleBody}}}},responses:{200:g(e.Schedule,"Updated schedule"),...w(e,400,404)}}),r.registerPath({method:"delete",path:"/schedules/{id}",tags:["Schedules"],summary:"Delete a schedule",request:{params:_},responses:{204:{description:"Schedule deleted"},...w(e,404)}}),r.registerPath({method:"get",path:"/providers/status",tags:["Providers"],summary:"Provider secret configuration status",description:"Reports whether each known provider API key is set. Returns key *names* only \u2014 never secret values.",responses:{200:g(B(e.ProviderStatus),"Provider configuration status")}}),r.registerPath({method:"post",path:"/providers/preview-models",tags:["Providers"],summary:"Preview models available to an agent API key",description:"Lookup only \u2014 does not persist settings or secrets. Send apiKey to try a typed key before save, or instanceId to use the already-stored key (never echoed).",request:{body:{required:!0,content:{"application/json":{schema:e.PreviewModelsBody}}}},responses:{200:g(B(e.PreviewModel),"Models available to the key"),...w(e,400,404)}}),r.registerPath({method:"get",path:"/providers/{providerId}/query-templates",tags:["Providers"],summary:"List query templates for a provider",description:"Named, pre-built query templates owned by the provider. Providers with none yet (e.g. documentation) return an empty list. The client never constructs `query` itself \u2014 it submits templateId + params to the resolve endpoint.",request:{params:I.object({providerId:I.string().min(1)})},responses:{200:g(B(e.QueryTemplate),"Query templates")}}),r.registerPath({method:"get",path:"/providers/{providerId}/actions",tags:["Providers"],summary:"List extended actions for a provider",description:"Opt-in capabilities beyond the portable five ProviderAction operations. Providers that do not implement ExtendedActionProvider return an empty list \u2014 that is a normal, expected case, not an error.",request:{params:I.object({providerId:I.string().min(1)})},responses:{200:g(B(e.ProviderActionDescriptor),"Extended actions")}}),r.registerPath({method:"post",path:"/providers/{providerId}/query-templates/{templateId}/resolve",tags:["Providers"],summary:"Resolve a query template to a concrete query",description:"Provider-specific query-shape knowledge stays server-side. Returns the `query` object to store on a SubjectView, along with template provenance the client attaches separately.",request:{params:I.object({providerId:I.string().min(1),templateId:I.string().min(1)}),body:{required:!0,content:{"application/json":{schema:e.ResolveQueryTemplateBody}}}},responses:{200:g(e.ResolveQueryTemplateResponse,"Resolved query"),...w(e,400,404)}}),r.registerPath({method:"get",path:"/settings",tags:["Settings"],summary:"Get engine settings",description:"Persisted provider configuration. Never includes secret values \u2014 those live in SecretStore.",responses:{200:g(e.EngineSettings,"Current engine settings")}}),r.registerPath({method:"patch",path:"/settings",tags:["Settings"],summary:"Update engine settings",description:"Partial merge. restartRequired is true when providerInstances is in the patch (instance bindings are boot-time). Changing defaultAgentInstanceId takes effect on the next agent step with no restart.",request:{body:{required:!0,content:{"application/json":{schema:e.UpdateSettingsBody}}}},responses:{200:g(e.SettingsPatchResponse,"Updated settings"),...w(e,400)}}),r.registerPath({method:"get",path:"/provider-instances",tags:["Settings"],summary:"List provider instances",responses:{200:g(B(e.ProviderInstanceConfig),"Configured provider instances")}}),r.registerPath({method:"post",path:"/provider-instances",tags:["Settings"],summary:"Create a provider instance",description:"Persists the instance. restartRequired is always true \u2014 bindings are boot-time. For agent instances, defaultAgent atomically replaces EngineSettings.defaultAgentInstanceId in the same write.",request:{body:{required:!0,content:{"application/json":{schema:e.CreateProviderInstanceBody}}}},responses:{201:g(e.ProviderInstanceMutationResponse,"Created instance settings"),...w(e,400,409)}}),r.registerPath({method:"get",path:"/provider-instances/{id}",tags:["Settings"],summary:"Get a provider instance",request:{params:I.object({id:I.string().min(1)})},responses:{200:g(e.ProviderInstanceConfig,"Provider instance"),...w(e,404)}}),r.registerPath({method:"patch",path:"/provider-instances/{id}",tags:["Settings"],summary:"Update a provider instance",request:{params:I.object({id:I.string().min(1)}),body:{required:!0,content:{"application/json":{schema:e.UpdateProviderInstanceBody}}}},responses:{200:g(e.ProviderInstanceMutationResponse,"Updated instance settings"),...w(e,400,404)}}),r.registerPath({method:"delete",path:"/provider-instances/{id}",tags:["Settings"],summary:"Delete a provider instance",request:{params:I.object({id:I.string().min(1)})},responses:{200:g(e.ProviderInstanceMutationResponse,"Updated settings after delete"),...w(e,404)}}),r.registerPath({method:"post",path:"/secrets/{key}",tags:["Settings"],summary:"Store a secret",description:"Writes to SecretStore. The response never includes the secret value.",request:{params:I.object({key:I.string().min(1)}),body:{required:!0,content:{"application/json":{schema:e.SetSecretBody}}}},responses:{204:{description:"Secret stored"},...w(e,400)}}),r.registerPath({method:"get",path:"/events",tags:["Events"],summary:"Subscribe to engine events (SSE)",description:"Server-Sent Events stream. Each event `data` field is a JSON EngineEvent. Optionally filter by jobId and/or batchId.",request:{query:I.object({jobId:I.string().optional(),batchId:I.string().optional()})},responses:{200:{description:"SSE stream of engine events",content:{"text/event-stream":{schema:e.EngineEvent}}}}})}var Zu=l(()=>{"use strict";C();zi()});import{OpenAPIRegistry as _y,OpenApiGeneratorV31 as Ey}from"@asteasolutions/zod-to-openapi";function el(){if(io)return io;let r=new _y,e=Xu(r);return Yu(r,e),io=new Ey(r.definitions).generateDocument({openapi:"3.1.0",info:{title:"Knoflows Engine API",version:"0.1.0",description:"REST API for workflow definitions, jobs, batches, schedules, views, and live events."},servers:[{url:"/api"}]}),io}var io,tl=l(()=>{"use strict";zi();Zu()});import{Controller as Py,Get as Ry,Header as ky}from"@nestjs/common";var rl,Qi,Ir,nl=l(()=>{"use strict";tl();rl=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Qi=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},Ir=class{getOpenApiDocument(){return el()}};rl([Ry("openapi.json"),ky("Content-Type","application/json"),Qi("design:type",Function),Qi("design:paramtypes",[]),Qi("design:returntype",void 0)],Ir.prototype,"getOpenApiDocument",null);Ir=rl([Py()],Ir)});import{Controller as Ay,Get as Xi,Inject as so,Param as ao,Post as ol,Body as il,HttpCode as sl}from"@nestjs/common";var Ht,H,Te,Me,al=l(()=>{"use strict";Ko();oi();ii();ci();C();ne();Ht=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},H=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},Te=function(r,e){return function(t,n){e(t,n,r)}},Me=class{providerStatus;queryTemplates;extendedActions;previewModels;constructor(e,t,n,o){this.providerStatus=e,this.queryTemplates=t,this.extendedActions=n,this.previewModels=o}async status(){return this.providerStatus.list()}previewAvailableModels(e){return this.previewModels.preview(e)}listQueryTemplates(e){return this.queryTemplates.list(e)}listExtendedActions(e){return this.extendedActions.list(e)}async resolveQueryTemplate(e,t,n){return{query:await this.queryTemplates.resolve(e,t,n.params)}}};Ht([Xi("status"),H("design:type",Function),H("design:paramtypes",[]),H("design:returntype",Promise)],Me.prototype,"status",null);Ht([ol("preview-models"),sl(200),Te(0,il(new v(an))),H("design:type",Function),H("design:paramtypes",[Object]),H("design:returntype",Promise)],Me.prototype,"previewAvailableModels",null);Ht([Xi(":providerId/query-templates"),Te(0,ao("providerId")),H("design:type",Function),H("design:paramtypes",[String]),H("design:returntype",Promise)],Me.prototype,"listQueryTemplates",null);Ht([Xi(":providerId/actions"),Te(0,ao("providerId")),H("design:type",Function),H("design:paramtypes",[String]),H("design:returntype",Promise)],Me.prototype,"listExtendedActions",null);Ht([ol(":providerId/query-templates/:templateId/resolve"),sl(200),Te(0,ao("providerId")),Te(1,ao("templateId")),Te(2,il(new v(Nr))),H("design:type",Function),H("design:paramtypes",[String,String,Object]),H("design:returntype",Promise)],Me.prototype,"resolveQueryTemplate",null);Me=Ht([Ay("providers"),Te(0,so(rt)),Te(1,so(nt)),Te(2,so(ot)),Te(3,so(it)),H("design:paramtypes",[rt,nt,ot,it])],Me)});import{Body as Cy,Controller as Ty,Get as Oy,Inject as $y,Patch as qy}from"@nestjs/common";var Yi,Rt,cl,Vt,ul=l(()=>{"use strict";C();Pe();ne();Yi=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Rt=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},cl=function(r,e){return function(t,n){e(t,n,r)}},Vt=class{settings;constructor(e){this.settings=e}get(){return this.settings.get()}async update(e){return{settings:await this.settings.update(e),restartRequired:Qa(e)}}};Yi([Oy(),Rt("design:type",Function),Rt("design:paramtypes",[]),Rt("design:returntype",Promise)],Vt.prototype,"get",null);Yi([qy(),cl(0,Cy(new v(nn))),Rt("design:type",Function),Rt("design:paramtypes",[Object]),Rt("design:returntype",Promise)],Vt.prototype,"update",null);Vt=Yi([Ty("settings"),cl(0,$y(P)),Rt("design:paramtypes",[P])],Vt)});function Zi(r){let{current:e,instance:t,defaultAgent:n,isCreate:o}=r;return $t(t)?n===!0?t.id:n===!1?e===t.id?null:e??null:o&&!e?t.id:e??null:e===t.id?null:e??null}function ll(r){let{defaultAgent:e,...t}=r;return t}var dl=l(()=>{"use strict";C()});import{Body as pl,Controller as By,Delete as Dy,Get as fl,HttpCode as Fy,Inject as Ny,Param as es,Patch as Jy,Post as Ly}from"@nestjs/common";var Gt,V,Kt,We,ml=l(()=>{"use strict";C();Pe();R();ne();dl();Gt=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},V=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},Kt=function(r,e){return function(t,n){e(t,n,r)}},We=class{settings;constructor(e){this.settings=e}async list(){return(await this.settings.get()).providerInstances??[]}async get(e){let t=(await this.settings.get()).providerInstances?.find(n=>n.id===e);if(!t)throw new y(`Provider instance not found: ${e}`);return t}async create(e){let t=ll(e),n=await this.settings.get(),o=[...n.providerInstances??[]];if(o.some(s=>s.id===t.id))throw new J(`Provider instance already exists: ${t.id}`);return o.push(t),{settings:await this.settings.update({providerInstances:o,defaultAgentInstanceId:Zi({current:n.defaultAgentInstanceId,instance:t,defaultAgent:e.defaultAgent,isCreate:!0})}),restartRequired:!0}}async update(e,t){let n=await this.settings.get(),o=[...n.providerInstances??[]],i=o.findIndex(c=>c.id===e);if(i<0)throw new y(`Provider instance not found: ${e}`);let a={...o[i],...t.displayName!=null?{displayName:t.displayName}:{},...t.config!=null?{config:t.config}:{},...t.secretKey!=null?{secretKey:t.secretKey}:{}};return t.expiresOn!==void 0&&(t.expiresOn?a.expiresOn=t.expiresOn:delete a.expiresOn),o[i]=a,{settings:await this.settings.update({providerInstances:o,defaultAgentInstanceId:Zi({current:n.defaultAgentInstanceId,instance:a,defaultAgent:t.defaultAgent,isCreate:!1})}),restartRequired:!0}}async remove(e){let t=await this.settings.get(),n=(t.providerInstances??[]).filter(s=>s.id!==e);if(n.length===(t.providerInstances??[]).length)throw new y(`Provider instance not found: ${e}`);let o=t.defaultAgentInstanceId===e?null:t.defaultAgentInstanceId??null;return{settings:await this.settings.update({providerInstances:n,defaultAgentInstanceId:o}),restartRequired:!0}}};Gt([fl(),V("design:type",Function),V("design:paramtypes",[]),V("design:returntype",Promise)],We.prototype,"list",null);Gt([fl(":id"),Kt(0,es("id")),V("design:type",Function),V("design:paramtypes",[String]),V("design:returntype",Promise)],We.prototype,"get",null);Gt([Ly(),Kt(0,pl(new v(on))),V("design:type",Function),V("design:paramtypes",[Object]),V("design:returntype",Promise)],We.prototype,"create",null);Gt([Jy(":id"),Kt(0,es("id")),Kt(1,pl(new v(sn))),V("design:type",Function),V("design:paramtypes",[String,Object]),V("design:returntype",Promise)],We.prototype,"update",null);Gt([Dy(":id"),Fy(200),Kt(0,es("id")),V("design:type",Function),V("design:paramtypes",[String]),V("design:returntype",Promise)],We.prototype,"remove",null);We=Gt([By("provider-instances"),Kt(0,Ny(P)),V("design:paramtypes",[P])],We)});import{Body as Uy,Controller as My,HttpCode as Wy,Inject as Hy,Param as Vy,Post as Ky}from"@nestjs/common";var hl,co,ts,jr,yl=l(()=>{"use strict";Oe();R();ne();Vi();hl=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},co=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},ts=function(r,e){return function(t,n){e(t,n,r)}},jr=class{secrets;constructor(e){this.secrets=e}async set(e,t){let n=e.trim();if(!n)throw new h("Secret key must not be empty");await this.secrets.set(n,t.value)}};hl([Ky(":key"),Wy(204),ts(0,Vy("key")),ts(1,Uy(new v(no))),co("design:type",Function),co("design:paramtypes",[String,Object]),co("design:returntype",Promise)],jr.prototype,"set",null);jr=hl([My("secrets"),ts(0,Hy(fe)),co("design:paramtypes",[Function])],jr)});import{readFile as Gy}from"node:fs/promises";async function rs(r){try{await Gy(r,"utf8")}catch(e){let t=e instanceof Error?e.message:String(e);throw new h(`Cannot read context file at '${r}': ${t}`)}}var gl=l(()=>{"use strict";R()});import{Body as wl,Controller as zy,Delete as Qy,Get as bl,HttpCode as Xy,Inject as Yy,Param as ns,Patch as Zy,Post as eg}from"@nestjs/common";import{randomUUID as tg}from"node:crypto";var Qt,K,zt,He,Sl=l(()=>{"use strict";C();Dr();R();ne();gl();Qt=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},K=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},zt=function(r,e){return function(t,n){e(t,n,r)}},He=class{files;constructor(e){this.files=e}async list(){return this.files.list()}async get(e){let t=await this.files.get(e);if(!t)throw new y(`Context file not found: ${e}`);return t}async create(e){return await rs(e.path),this.files.create({id:e.id??tg(),name:e.name,description:e.description,tier:e.tier,path:e.path})}async update(e,t){let n=await this.files.get(e);if(!n)throw new y(`Context file not found: ${e}`);let o=t.path??n.path;await rs(o);let i=await this.files.update(e,t);if(!i)throw new y(`Context file not found: ${e}`);return i}async remove(e){if(!await this.files.delete(e))throw new y(`Context file not found: ${e}`)}};Qt([bl(),K("design:type",Function),K("design:paramtypes",[]),K("design:returntype",Promise)],He.prototype,"list",null);Qt([bl(":id"),zt(0,ns("id")),K("design:type",Function),K("design:paramtypes",[String]),K("design:returntype",Promise)],He.prototype,"get",null);Qt([eg(),zt(0,wl(new v(Vr))),K("design:type",Function),K("design:paramtypes",[Object]),K("design:returntype",Promise)],He.prototype,"create",null);Qt([Zy(":id"),zt(0,ns("id")),zt(1,wl(new v(Kr))),K("design:type",Function),K("design:paramtypes",[String,Object]),K("design:returntype",Promise)],He.prototype,"update",null);Qt([Qy(":id"),Xy(204),zt(0,ns("id")),K("design:type",Function),K("design:paramtypes",[String]),K("design:returntype",Promise)],He.prototype,"remove",null);He=Qt([zy("context-files"),zt(0,Yy(ae)),K("design:paramtypes",[ae])],He)});import{execFile as rg}from"node:child_process";import{stat as ng}from"node:fs/promises";import{resolve as os}from"node:path";import{promisify as og}from"node:util";async function is(r){let e=os(r);try{if((await ig("git",["-C",e,"rev-parse","--is-inside-work-tree"],{encoding:"utf8",windowsHide:!0})).stdout.trim()!=="true")throw new Error("not a work tree")}catch(t){let n=t instanceof Error?t.message:String(t);throw new h(`'${r}' is not a git repository: ${n}`)}}async function ss(r,e){let t=os(r),n=os(e?.trim()?e.trim():Dn(t));if(Fn(t,n))throw new h(`Worktree base '${n}' must not be inside the repository at '${t}'`);try{if(!(await ng(n)).isDirectory())throw new h(`Worktree base '${n}' exists and is not a directory`)}catch(o){if(o instanceof h)throw o}}var ig,xl=l(()=>{"use strict";R();xi();ig=og(rg)});import{Body as vl,Controller as sg,Delete as ag,Get as Il,HttpCode as cg,Inject as ug,Param as as,Patch as lg,Post as dg}from"@nestjs/common";import{randomUUID as pg}from"node:crypto";var Yt,G,Xt,Ve,jl=l(()=>{"use strict";C();Fr();R();ne();xl();Yt=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},G=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},Xt=function(r,e){return function(t,n){e(t,n,r)}},Ve=class{repos;constructor(e){this.repos=e}async list(){return this.repos.list()}async get(e){let t=await this.repos.get(e);if(!t)throw new y(`Local repository not found: ${e}`);return t}async create(e){return await is(e.localPath),await ss(e.localPath,e.worktreeBasePath),this.repos.create({id:e.id??pg(),name:e.name,localPath:e.localPath,...e.worktreeBasePath?{worktreeBasePath:e.worktreeBasePath}:{}})}async update(e,t){let n=await this.repos.get(e);if(!n)throw new y(`Local repository not found: ${e}`);let o=t.localPath??n.localPath,i=t.worktreeBasePath!==void 0?t.worktreeBasePath:n.worktreeBasePath;await is(o),await ss(o,i);let s=await this.repos.update(e,t);if(!s)throw new y(`Local repository not found: ${e}`);return s}async remove(e){if(!await this.repos.delete(e))throw new y(`Local repository not found: ${e}`)}};Yt([Il(),G("design:type",Function),G("design:paramtypes",[]),G("design:returntype",Promise)],Ve.prototype,"list",null);Yt([Il(":id"),Xt(0,as("id")),G("design:type",Function),G("design:paramtypes",[String]),G("design:returntype",Promise)],Ve.prototype,"get",null);Yt([dg(),Xt(0,vl(new v(zr))),G("design:type",Function),G("design:paramtypes",[Object]),G("design:returntype",Promise)],Ve.prototype,"create",null);Yt([lg(":id"),Xt(0,as("id")),Xt(1,vl(new v(Qr))),G("design:type",Function),G("design:paramtypes",[String,Object]),G("design:returntype",Promise)],Ve.prototype,"update",null);Yt([ag(":id"),cg(204),Xt(0,as("id")),G("design:type",Function),G("design:paramtypes",[String]),G("design:returntype",Promise)],Ve.prototype,"remove",null);Ve=Yt([sg("local-repositories"),Xt(0,ug(ce)),G("design:paramtypes",[ce])],Ve)});import{readdir as fg,stat as mg}from"node:fs/promises";import{homedir as hg}from"node:os";import{join as yg,resolve as gg}from"node:path";async function _l(r,e={}){let t=r?.trim()?r.trim():hg(),n=gg(t),o;try{o=await mg(n)}catch(s){throw new h(`Cannot browse '${n}': ${s instanceof Error?s.message:String(s)}`)}if(!o.isDirectory())throw new h(`Cannot browse '${n}': not a directory`);let i;try{i=(await fg(n,{encoding:"utf8",withFileTypes:!0})).filter(a=>a.name!=="."&&a.name!=="..").map(a=>({name:a.name,path:yg(n,a.name),isDirectory:a.isDirectory()})).filter(a=>wg(a,e)).sort((a,u)=>a.isDirectory!==u.isDirectory?a.isDirectory?-1:1:a.name.localeCompare(u.name))}catch(s){throw new h(`Cannot browse '${n}': ${s instanceof Error?s.message:String(s)}`)}return{path:n,entries:i}}function El(r){if(r==null||r.trim()==="")return;let e=r.split(",").map(t=>Rl(t)).filter(t=>t!=null);return e.length>0?e:void 0}function Pl(r){if(!(r==null||r.trim()==="")){if(r==="directories"||r==="files")return r;throw new h(`Invalid browse mode '${r}'`)}}function wg(r,e){if(e.mode==="directories")return r.isDirectory;if(r.isDirectory)return!0;let t=e.extensions?.map(o=>Rl(o)).filter(Boolean);if(!t?.length)return!0;let n=r.name.toLowerCase();return t.some(o=>n.endsWith(o))}function Rl(r){let e=r.trim().toLowerCase();if(e.length!==0)return e.startsWith(".")?e:`.${e}`}var kl=l(()=>{"use strict";R()});import{Controller as bg,Get as Sg,Query as ls}from"@nestjs/common";var Al,cs,us,_r,Cl=l(()=>{"use strict";kl();Al=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},cs=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},us=function(r,e){return function(t,n){e(t,n,r)}},_r=class{async browse(e,t,n){return _l(e,{mode:Pl(t),extensions:El(n)})}};Al([Sg("browse"),us(0,ls("path")),us(1,ls("mode")),us(2,ls("extensions")),cs("design:type",Function),cs("design:paramtypes",[String,String,String]),cs("design:returntype",Promise)],_r.prototype,"browse",null);_r=Al([bg("filesystem")],_r)});import{Module as vg}from"@nestjs/common";import{APP_FILTER as Ig}from"@nestjs/core";var xg,uo,Tl=l(()=>{"use strict";mr();_i();On();du();wu();Eu();Ru();Tu();Bu();Fu();Lu();Hu();nl();al();ul();ml();yl();Sl();jl();Cl();Cn();Io();xg=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},uo=class{};uo=xg([vg({imports:[Re,Jt,at,st,At],controllers:[Ne,Ut,Se,ke,oe,Le,Ue,vr,Ir,Me,Vt,We,jr,He,Ve,_r],providers:[{provide:Ig,useClass:Un}]})],uo)});import{Module as _g}from"@nestjs/common";var jg,lo,Ol=l(()=>{"use strict";ms();hs();ys();Cn();On();mr();_i();Tl();jg=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},lo=class{};lo=jg([_g({imports:[Er,Pr,st,at,Re,Jt,uo],controllers:[Zt]})],lo)});import{apiReference as Eg}from"@scalar/nestjs-api-reference";function $l(r){r.use("/api/docs",Eg({url:"/api/openapi.json",pageTitle:"Knoflows Engine API"}))}var ql=l(()=>{"use strict"});import{createServer as Pg}from"node:net";function Bl(r){return typeof r=="object"&&r!==null&&"code"in r&&r.code==="EADDRINUSE"}async function ds(r,e=20){for(let t=0;t<e;t+=1){let n=r+t;if(await Rg(n))return n}throw new Error(`No free port found in ${r}\u2013${r+e-1}`)}function Rg(r){return new Promise(e=>{let t=Pg();t.once("error",()=>{e(!1)}),t.once("listening",()=>{t.close(()=>e(!0))}),t.listen(r)})}var Dl=l(()=>{"use strict"});import{Catch as Cg,HttpStatus as po,NotFoundException as Tg}from"@nestjs/common";import{existsSync as Fl,statSync as Og}from"node:fs";import{extname as Nl,join as ps,normalize as $g,relative as qg,sep as Bg}from"node:path";function Jl(r){return(e,t,n)=>{if(e.method!=="GET"&&e.method!=="HEAD"){n();return}if((e.path??"").startsWith("/api")){n();return}let o=Dg(e.path??"/");if(o){let i=ps(r,o);if(Fg(r,i)){t.sendFile(o,{root:r},s=>{s&&n()});return}}if(Ll(e)){Ul(t,r,i=>{i&&!t.headersSent&&t.status(po.NOT_FOUND).end()});return}t.status(po.NOT_FOUND).end()}}function Ll(r){if(r.method!=="GET"&&r.method!=="HEAD")return!1;let e=r.path??"";if(e.startsWith("/api"))return!1;let t=Nl(e);return!(t&&t!==".html")}function Ul(r,e,t){r.sendFile("index.html",{root:e},t)}function Dg(r){if(r==="/"||r==="")return"index.html";let e=$g(r.replace(/^\/+/,""));return!e||e==="."||e.startsWith("..")||!Nl(e)?null:e}function Fg(r,e){if(!Fl(e))return!1;try{if(!Og(e).isFile())return!1}catch{return!1}let t=qg(r,e);return t!==""&&!t.startsWith(`..${Bg}`)&&!t.startsWith("..")}function Ml(r){return ps(r,"index.html")}var kg,Ag,fo,Wl=l(()=>{"use strict";kg=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Ag=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},fo=class{staticRoot;constructor(e){this.staticRoot=e}catch(e,t){let n=t.switchToHttp(),o=n.getRequest(),i=n.getResponse();if(Ll(o)&&Fl(ps(this.staticRoot,"index.html"))){Ul(i,this.staticRoot,u=>{u&&!i.headersSent&&i.status(po.NOT_FOUND).json({statusCode:po.NOT_FOUND,message:"UI index.html could not be served"})});return}let s=e.getStatus(),a=e.getResponse();i.status(s).json(typeof a=="string"?{statusCode:s,message:a}:a)}};fo=kg([Cg(Tg),Ag("design:paramtypes",[String])],fo)});import{existsSync as Ng}from"node:fs";import{dirname as Jg,join as mo}from"node:path";import{fileURLToPath as Lg}from"node:url";function Hl(){let r=Jg(Lg(import.meta.url)),e=[mo(r,"../static"),mo(r,"../../static"),mo(r,"static")];for(let t of e)if(Ng(mo(t,"index.html")))return t;return null}var Vl=l(()=>{"use strict"});var Vg={};import"reflect-metadata";import{existsSync as Ug}from"node:fs";import{Logger as Mg}from"@nestjs/common";import{NestFactory as Wg}from"@nestjs/core";async function Hg(){let r=await Wg.create(lo);r.enableCors(),r.setGlobalPrefix("api"),$l(r);let e=Hl(),t=e?Ml(e):null;e&&t&&Ug(t)?(ho.log(`Serving UI from ${e}`),r.use(Jl(e)),r.useGlobalFilters(new fo(e))):ho.warn("No UI found (static/index.html missing). GET / will 404; /api still works. Rebuild with `npm run build:release` before publishing.");let n=Number(process.env.PORT??3e3);if(!Number.isInteger(n)||n<1||n>65535)throw new Error(`Invalid PORT: ${process.env.PORT}`);let o=await ds(n);for(let i=0;i<5;i+=1)try{await r.listen(o),o!==n?ho.warn(`Port ${n} is in use; listening on ${o} instead`):ho.log(`Listening on http://localhost:${o}`);return}catch(s){if(!Bl(s))throw s;o=await ds(o+1)}throw new Error(`Could not bind a free port starting at ${n}`)}var ho,Kl=l(()=>{"use strict";Ol();ql();Dl();Wl();Vl();ho=new Mg("Bootstrap");Hg()});import{readFileSync as Kg}from"node:fs";function Gg(){let r=Kg(new URL("../package.json",import.meta.url),"utf8");return JSON.parse(r).version}var yo=process.argv.slice(2);yo.includes("--version")||yo.includes("-v")?console.log(Gg()):yo.includes("--help")||yo.includes("-h")?console.log(["Usage: knoflows [options]","","Starts the knoflows engine (REST API + bundled web client).","","Options:"," -v, --version Print the engine version and exit"," -h, --help Print this message and exit","","Environment:"," PORT Preferred HTTP port (default 3000). If taken, the next free port is used."," KNO_SQLITE_PATH SQLite file path, or :memory: for an ephemeral database"].join(`
34
- `)):await Promise.resolve().then(()=>(Kl(),Vg));
101
+ Testing: {{testing-review}}`,outputFormat:"free_text"}],notificationPolicy:{triggers:["on_fail","on_complete"]}}},Vi=[Tg,Og];for(let n of Vi)tl(n)});import{Controller as $g,Get as qg,Inject as Dg,Param as Bg,Post as Fg}from"@nestjs/common";var Qi,Ct,al,Kt,cl=l(()=>{"use strict";St();R();sl();no();Qi=function(n,e,t,r){var o=arguments.length,i=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Ct=function(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)},al=function(n,e){return function(t,r){e(t,r,n)}},Kt=class{workflows;constructor(e){this.workflows=e}list(){return ol()}async add(e){let t=il(e);if(!t)throw new g(`Workflow library entry not found: ${e}`);let r=structuredClone(t.workflowDefinition);return delete r.id,ht(this.workflows,r)}};Qi([qg(),Ct("design:type",Function),Ct("design:paramtypes",[]),Ct("design:returntype",Array)],Kt.prototype,"list",null);Qi([Fg(":id/add"),al(0,Bg("id")),Ct("design:type",Function),Ct("design:paramtypes",[String]),Ct("design:returntype",Promise)],Kt.prototype,"add",null);Kt=Qi([$g("workflow-library"),al(0,Dg(D)),Ct("design:paramtypes",[D])],Kt)});import{Body as Xi,Controller as Ng,Delete as Jg,Get as Yi,HttpCode as Lg,Inject as zi,Param as so,Patch as ul,Post as Ug,Query as Mg}from"@nestjs/common";var gt,$,je,_e,ll=l(()=>{"use strict";C();Wn();St();R();ae();eo();Mt();Bi();gt=function(n,e,t,r){var o=arguments.length,i=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},$=function(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)},je=function(n,e){return function(t,r){e(t,r,n)}},_e=class{views;workflows;providers;constructor(e,t,r){this.views=e,this.workflows=t,this.providers=r}async list(e){if(e!=null&&e!==""){let t=oe.safeParse(e);if(!t.success)throw new h(`Invalid subjectType filter: ${e}`);return this.views.list({subjectType:t.data})}return this.views.list({})}async reorder(e){let t=[];for(let i of e.viewIds){let s=await this.views.get(i);if(!s)throw new h(`Unknown view id in reorder: ${i}`);t.push(s)}if(new Set(t.map(i=>i.subjectType)).size!==1)throw new h("All viewIds in a reorder request must share the same subjectType");return await this.views.reorder(e.viewIds)}async listSubjects(e){return Gr(e,this.views,this.providers)}async get(e){let t=await this.views.get(e);if(!t)throw new g(`SubjectView not found: ${e}`);return t}async create(e){return await this.assertBinding(e.workflowId,e.subjectType),this.views.create(e)}async update(e,t){let r=await this.views.get(e);if(!r)throw new g(`SubjectView not found: ${e}`);await this.assertBinding(t.workflowId??r.workflowId,t.subjectType??r.subjectType);let o=await this.views.update(e,t);if(!o)throw new g(`SubjectView not found: ${e}`);return o}async remove(e){if(!await this.views.delete(e))throw new g(`SubjectView not found: ${e}`)}async assertBinding(e,t){let r=await this.workflows.get(e);Nu(r,e,t)}};gt([Yi(),je(0,Mg("subjectType")),$("design:type",Function),$("design:paramtypes",[String]),$("design:returntype",Promise)],_e.prototype,"list",null);gt([ul("reorder"),je(0,Xi(new v(Yn))),$("design:type",Function),$("design:paramtypes",[Object]),$("design:returntype",Promise)],_e.prototype,"reorder",null);gt([Yi(":id/subjects"),je(0,so("id")),$("design:type",Function),$("design:paramtypes",[String]),$("design:returntype",Promise)],_e.prototype,"listSubjects",null);gt([Yi(":id"),je(0,so("id")),$("design:type",Function),$("design:paramtypes",[String]),$("design:returntype",Promise)],_e.prototype,"get",null);gt([Ug(),je(0,Xi(new v(zn))),$("design:type",Function),$("design:paramtypes",[Object]),$("design:returntype",Promise)],_e.prototype,"create",null);gt([ul(":id"),je(0,so("id")),je(1,Xi(new v(Xn))),$("design:type",Function),$("design:paramtypes",[String,Object]),$("design:returntype",Promise)],_e.prototype,"update",null);gt([Jg(":id"),Lg(204),je(0,so("id")),$("design:type",Function),$("design:paramtypes",[String]),$("design:returntype",Promise)],_e.prototype,"remove",null);_e=gt([Ng("views"),je(0,zi(ue)),je(1,zi(D)),je(2,zi(U)),$("design:paramtypes",[ue,D,U])],_e)});import{Body as Zi,Controller as Wg,Delete as Hg,Get as pl,HttpCode as Gg,Inject as dl,Param as es,Patch as fl,Post as Kg}from"@nestjs/common";var Tt,N,yt,qe,ml=l(()=>{"use strict";C();ei();St();R();ae();eo();Tt=function(n,e,t,r){var o=arguments.length,i=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},N=function(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)},yt=function(n,e){return function(t,r){e(t,r,n)}},qe=class{shortcuts;workflows;constructor(e,t){this.shortcuts=e,this.workflows=t}async list(){return this.shortcuts.list()}async reorder(e){for(let t of e.shortcutIds)if(!await this.shortcuts.get(t))throw new h(`Unknown shortcut id in reorder: ${t}`);return this.shortcuts.reorder(e.shortcutIds)}async get(e){let t=await this.shortcuts.get(e);if(!t)throw new g(`WorkflowShortcut not found: ${e}`);return t}async create(e){return await this.assertBinding(e.workflowId),this.shortcuts.create(e)}async update(e,t){let r=await this.shortcuts.get(e);if(!r)throw new g(`WorkflowShortcut not found: ${e}`);await this.assertBinding(t.workflowId??r.workflowId);let o=await this.shortcuts.update(e,t);if(!o)throw new g(`WorkflowShortcut not found: ${e}`);return o}async remove(e){if(!await this.shortcuts.delete(e))throw new g(`WorkflowShortcut not found: ${e}`)}async assertBinding(e){let t=await this.workflows.get(e);Ju(t,e)}};Tt([pl(),N("design:type",Function),N("design:paramtypes",[]),N("design:returntype",Promise)],qe.prototype,"list",null);Tt([fl("reorder"),yt(0,Zi(new v(lr))),N("design:type",Function),N("design:paramtypes",[Object]),N("design:returntype",Promise)],qe.prototype,"reorder",null);Tt([pl(":id"),yt(0,es("id")),N("design:type",Function),N("design:paramtypes",[String]),N("design:returntype",Promise)],qe.prototype,"get",null);Tt([Kg(),yt(0,Zi(new v(cr))),N("design:type",Function),N("design:paramtypes",[Object]),N("design:returntype",Promise)],qe.prototype,"create",null);Tt([fl(":id"),yt(0,es("id")),yt(1,Zi(new v(ur))),N("design:type",Function),N("design:paramtypes",[String,Object]),N("design:returntype",Promise)],qe.prototype,"update",null);Tt([Hg(":id"),Gg(204),yt(0,es("id")),N("design:type",Function),N("design:paramtypes",[String]),N("design:returntype",Promise)],qe.prototype,"remove",null);qe=Tt([Wg("workflow-shortcuts"),yt(0,dl(Je)),yt(1,dl(D)),N("design:paramtypes",[Je,D])],qe)});function ao(n,e,t=50){let r=n!=null&&n!==""?Number(n):t,o=e!=null&&e!==""?Number(e):0;return!Number.isFinite(r)||r<1?{limit:t,offset:Math.max(0,o||0)}:!Number.isFinite(o)||o<0?{limit:r,offset:0}:{limit:Math.floor(r),offset:Math.floor(o)}}function co(n,e,t){return n.slice(t,t+e)}var ts=l(()=>{"use strict"});import{z as J}from"zod";var uo,lo,po,fo,mo,ns=l(()=>{"use strict";uo=J.object({workflowId:J.string().min(1),subjectId:J.string().min(1).optional(),inputValues:J.record(J.string(),J.unknown())}),lo=J.object({response:J.unknown()}),po=J.object({workflowId:J.string().min(1),subjectIds:J.array(J.string().min(1))}),fo=J.object({jobIds:J.array(J.string().min(1)).min(1)}),mo=J.object({overrideParams:J.record(J.string(),J.unknown()).optional()})});import{Body as An,Controller as Vg,Get as is,HttpCode as hl,Inject as rs,Param as Cn,Post as Ot,Query as He}from"@nestjs/common";import"zod";function os(n,e){if(!(n==null||n==="")){if(n==="true")return!0;if(n==="false")return!1;throw new h(`Invalid ${e} filter: ${n}`)}}var Ie,I,q,Qg,ne,gl=l(()=>{"use strict";Yr();bn();R();ae();ts();ns();Kr();Ie=function(n,e,t,r){var o=arguments.length,i=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},I=function(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)},q=function(n,e){return function(t,r){e(t,r,n)}},Qg=["pending","planning","waiting_for_human","waiting_for_children","implementing","testing","completed","failed","cancelled"];ne=class{jobs;runner;agentGate;constructor(e,t,r){this.jobs=e,this.runner=t,this.agentGate=r}async list(e,t,r,o,i,s,a,u,c){if(t!=null&&t!==""&&!Qg.includes(t))throw new h(`Invalid status filter: ${t}`);let d=os(i,"topLevelOnly"),m=os(s,"terminal"),w=os(a,"liveWorktree"),{limit:S,offset:k}=ao(u,c),_=await this.jobs.list({...e?{workflowId:e}:{},...t?{status:t}:{},...r?{batchId:r}:{},...o?{parentJobId:o}:{},...d===!0?{topLevelOnly:!0}:{},...m!==void 0?{terminal:m}:{},...w===!0?{liveWorktree:!0}:{}});return co(_,S,k)}listQueued(){return this.agentGate.listQueued()}async latestBySubject(e){return this.jobs.latestBySubject(e.workflowId,e.subjectIds)}async deleteWorktrees(e){return this.runner.deleteWorktrees(e.jobIds)}async get(e){let t=await this.jobs.get(e);if(!t)throw new g(`Job not found: ${e}`);return t}async create(e){return this.runner.start({workflowId:e.workflowId,...e.subjectId?{subjectId:e.subjectId}:{},inputValues:e.inputValues})}async resume(e,t){return this.runner.resume(e,t.response)}async retry(e){return this.runner.retryFailedJob(e)}async retryStep(e,t){return this.runner.retryFailedStep(e,t.overrideParams)}async cancel(e){return this.runner.cancelJob(e)}};Ie([is(),q(0,He("workflowId")),q(1,He("status")),q(2,He("batchId")),q(3,He("parentJobId")),q(4,He("topLevelOnly")),q(5,He("terminal")),q(6,He("liveWorktree")),q(7,He("limit")),q(8,He("offset")),I("design:type",Function),I("design:paramtypes",[String,String,String,String,String,String,String,String,String]),I("design:returntype",Promise)],ne.prototype,"list",null);Ie([is("queued"),I("design:type",Function),I("design:paramtypes",[]),I("design:returntype",Array)],ne.prototype,"listQueued",null);Ie([Ot("latest-by-subject"),hl(200),q(0,An(new v(po))),I("design:type",Function),I("design:paramtypes",[Object]),I("design:returntype",Promise)],ne.prototype,"latestBySubject",null);Ie([Ot("delete-worktrees"),hl(200),q(0,An(new v(fo))),I("design:type",Function),I("design:paramtypes",[Object]),I("design:returntype",Promise)],ne.prototype,"deleteWorktrees",null);Ie([is(":id"),q(0,Cn("id")),I("design:type",Function),I("design:paramtypes",[String]),I("design:returntype",Promise)],ne.prototype,"get",null);Ie([Ot(),q(0,An(new v(uo))),I("design:type",Function),I("design:paramtypes",[Object]),I("design:returntype",Promise)],ne.prototype,"create",null);Ie([Ot(":id/resume"),q(0,Cn("id")),q(1,An(new v(lo))),I("design:type",Function),I("design:paramtypes",[String,Object]),I("design:returntype",Promise)],ne.prototype,"resume",null);Ie([Ot(":id/retry"),q(0,Cn("id")),I("design:type",Function),I("design:paramtypes",[String]),I("design:returntype",Promise)],ne.prototype,"retry",null);Ie([Ot(":id/retry-step"),q(0,Cn("id")),q(1,An(new v(mo))),I("design:type",Function),I("design:paramtypes",[String,Object]),I("design:returntype",Promise)],ne.prototype,"retryStep",null);Ie([Ot(":id/cancel"),q(0,Cn("id")),I("design:type",Function),I("design:paramtypes",[String]),I("design:returntype",Promise)],ne.prototype,"cancel",null);ne=Ie([Vg("jobs"),q(0,rs(X)),q(1,rs(xe)),q(2,rs(Se)),I("design:paramtypes",[X,xe,Se])],ne)});import{z as re}from"zod";var ho,go,ss=l(()=>{"use strict";C();ho=re.discriminatedUnion("mode",[re.object({mode:re.literal("view"),viewId:re.string().min(1)}),re.object({mode:re.literal("manual"),subjectType:oe,subjectIds:re.array(re.string().min(1))})]),go=re.object({workflowId:re.string().min(1),selection:ho,triggeredBy:re.enum(["schedule","view_bulk","multiselect"]),notificationOverride:Sn.optional(),inputValues:re.record(re.string(),re.unknown())})});import{Body as zg,Controller as Xg,Get as us,Inject as as,Param as ls,Post as yl,Query as cs}from"@nestjs/common";import"zod";var Vt,H,De,Ge,wl=l(()=>{"use strict";Yr();Hn();bn();R();ae();ts();ss();Vt=function(n,e,t,r){var o=arguments.length,i=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},H=function(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)},De=function(n,e){return function(t,r){e(t,r,n)}},Ge=class{batches;jobs;runner;constructor(e,t,r){this.batches=e,this.jobs=t,this.runner=r}async list(e,t,r){let{limit:o,offset:i}=ao(t,r),s=await this.batches.list(e?{workflowId:e}:{});return co(s,o,i)}async get(e){let t=await this.batches.get(e);if(!t)throw new g(`JobBatch not found: ${e}`);return t}async listJobs(e){if(!await this.batches.get(e))throw new g(`JobBatch not found: ${e}`);return this.jobs.list({batchId:e})}async launch(e){let t=await this.runner.launch({workflowId:e.workflowId,selection:e.selection,triggeredBy:e.triggeredBy,...e.notificationOverride?{notificationOverride:e.notificationOverride}:{},inputValues:e.inputValues});return"resolvedSubjects"in t&&"jobIds"in t?{kind:"batch",batch:t}:{kind:"job",job:t}}async cancel(e){return this.runner.cancelBatch(e)}};Vt([us(),De(0,cs("workflowId")),De(1,cs("limit")),De(2,cs("offset")),H("design:type",Function),H("design:paramtypes",[String,String,String]),H("design:returntype",Promise)],Ge.prototype,"list",null);Vt([us(":id"),De(0,ls("id")),H("design:type",Function),H("design:paramtypes",[String]),H("design:returntype",Promise)],Ge.prototype,"get",null);Vt([us(":id/jobs"),De(0,ls("id")),H("design:type",Function),H("design:paramtypes",[String]),H("design:returntype",Promise)],Ge.prototype,"listJobs",null);Vt([yl(),De(0,zg(new v(go))),H("design:type",Function),H("design:paramtypes",[Object]),H("design:returntype",Promise)],Ge.prototype,"launch",null);Vt([yl(":id/cancel"),De(0,ls("id")),H("design:type",Function),H("design:paramtypes",[String]),H("design:returntype",Promise)],Ge.prototype,"cancel",null);Ge=Vt([Xg("batches"),De(0,as(le)),De(1,as(X)),De(2,as(xe)),H("design:paramtypes",[le,X,xe])],Ge)});import{Body as bl,Controller as Yg,Delete as Zg,Get as Sl,HttpCode as ey,Inject as ty,Param as ds,Patch as ny,Post as ry,Query as oy}from"@nestjs/common";var Qt,G,$t,Ke,xl=l(()=>{"use strict";C();Yo();R();ae();Qt=function(n,e,t,r){var o=arguments.length,i=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},G=function(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)},$t=function(n,e){return function(t,r){e(t,r,n)}},Ke=class{schedules;constructor(e){this.schedules=e}async list(e){if(e==null||e==="")return this.schedules.list();if(e!=="true"&&e!=="false")throw new h(`Invalid enabled filter: ${e}`);return this.schedules.list({enabled:e==="true"})}async get(e){let t=await this.schedules.get(e);if(!t)throw new g(`Schedule not found: ${e}`);return t}async create(e){return this.schedules.create(e)}async update(e,t){let r=await this.schedules.update(e,t);if(!r)throw new g(`Schedule not found: ${e}`);return r}async remove(e){if(!await this.schedules.delete(e))throw new g(`Schedule not found: ${e}`)}};Qt([Sl(),$t(0,oy("enabled")),G("design:type",Function),G("design:paramtypes",[String]),G("design:returntype",Promise)],Ke.prototype,"list",null);Qt([Sl(":id"),$t(0,ds("id")),G("design:type",Function),G("design:paramtypes",[String]),G("design:returntype",Promise)],Ke.prototype,"get",null);Qt([ry(),$t(0,bl(new v(Jt))),G("design:type",Function),G("design:paramtypes",[Object]),G("design:returntype",Promise)],Ke.prototype,"create",null);Qt([ny(":id"),$t(0,ds("id")),$t(1,bl(new v(Jt.partial().omit({id:!0})))),G("design:type",Function),G("design:paramtypes",[String,Object]),G("design:returntype",Promise)],Ke.prototype,"update",null);Qt([Zg(":id"),ey(204),$t(0,ds("id")),G("design:type",Function),G("design:paramtypes",[String]),G("design:returntype",Promise)],Ke.prototype,"remove",null);Ke=Qt([Yg("schedules"),$t(0,ty(Ne)),G("design:paramtypes",[Ne])],Ke)});import{Controller as iy,Inject as sy,Query as vl,Sse as ay}from"@nestjs/common";import{Observable as _l}from"rxjs";var jl,yo,ps,Tn,Il=l(()=>{"use strict";Lr();jl=function(n,e,t,r){var o=arguments.length,i=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},yo=function(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)},ps=function(n,e){return function(t,r){e(t,r,n)}},Tn=class{events;constructor(e){this.events=e}stream(e,t){return new _l(r=>{let o=this.events.subscribe(i=>{let s=i;e!=null&&e!==""&&(!("jobId"in s)||s.jobId!==e)||t!=null&&t!==""&&(!("batchId"in s)||s.batchId!==t)||r.next({data:s})});return()=>{o()}})}};jl([ay(),ps(0,vl("jobId")),ps(1,vl("batchId")),yo("design:type",Function),yo("design:paramtypes",[String,String]),yo("design:returntype",_l)],Tn.prototype,"stream",null);Tn=jl([iy("events"),ps(0,sy(we)),yo("design:paramtypes",[we])],Tn)});import{extendZodWithOpenApi as cy}from"@asteasolutions/zod-to-openapi";import{z as uy}from"zod";var El=l(()=>{"use strict";cy(uy)});import{z as Pl}from"zod";var wo,fs=l(()=>{"use strict";wo=Pl.object({value:Pl.string().min(1)})});import{z as Ee}from"zod";var PR,ly,Rl,kl=l(()=>{"use strict";PR=Ee.object({path:Ee.string().optional(),mode:Ee.enum(["directories","files"]).optional(),extensions:Ee.string().optional()}),ly=Ee.object({name:Ee.string().min(1),path:Ee.string().min(1),isDirectory:Ee.boolean()}),Rl=Ee.object({path:Ee.string().min(1),entries:Ee.array(ly)})});import{z as p}from"zod";function Cy(n){let e=p.toJSONSchema(n),{$schema:t,...r}=e;return r}function Cl(n){let e=(t,r)=>n.registerComponent("schemas",t,Cy(r)).ref;return{WorkflowDefinition:e("WorkflowDefinition",xn),WorkflowDefinitionInput:e("WorkflowDefinitionInput",it),UpdateWorkflowBody:e("UpdateWorkflowBody",jy),SubjectView:e("SubjectView",Qn),CreateSubjectViewBody:e("CreateSubjectViewBody",zn),ReorderViewsBody:e("ReorderViewsBody",Yn),UpdateViewBody:e("UpdateViewBody",Iy),WorkflowShortcut:e("WorkflowShortcut",ar),CreateWorkflowShortcutBody:e("CreateWorkflowShortcutBody",cr),UpdateWorkflowShortcutBody:e("UpdateWorkflowShortcutBody",ur),ReorderShortcutsBody:e("ReorderShortcutsBody",lr),Schedule:e("Schedule",Jt),UpdateScheduleBody:e("UpdateScheduleBody",Ey),EngineSettings:e("EngineSettings",pr),UpdateSettingsBody:e("UpdateSettingsBody",Ry),SettingsPatchResponse:e("SettingsPatchResponse",Ay),ProviderInstanceConfig:e("ProviderInstanceConfig",dr),CreateProviderInstanceBody:e("CreateProviderInstanceBody",mr),UpdateProviderInstanceBody:e("UpdateProviderInstanceBody",hr),ProviderInstanceMutationResponse:e("ProviderInstanceMutationResponse",ky),SetSecretBody:e("SetSecretBody",wo),CreateJobBody:e("CreateJobBody",uo),ResumeJobBody:e("ResumeJobBody",lo),RetryStepBody:e("RetryStepBody",mo),LatestBySubjectBody:e("LatestBySubjectBody",po),LatestBySubjectResponse:e("LatestBySubjectResponse",Py),LaunchBody:e("LaunchBody",go),Job:e("Job",ms),QueuedAgentStep:e("QueuedAgentStep",yy),JobBatch:e("JobBatch",Al),LaunchResponse:e("LaunchResponse",wy),HealthResponse:e("HealthResponse",by),ProviderStatus:e("ProviderStatus",Sy),QueryTemplate:e("QueryTemplate",xa),ProviderActionDescriptor:e("ProviderActionDescriptor",va),PreviewModelsBody:e("PreviewModelsBody",gr),PreviewModel:e("PreviewModel",yc),ResolveQueryTemplateBody:e("ResolveQueryTemplateBody",Vn),ResolveQueryTemplateResponse:e("ResolveQueryTemplateResponse",ja),ErrorResponse:e("ErrorResponse",xy),EngineEvent:e("EngineEvent",vy),Subject:e("Subject",bo),WorkflowLibraryEntry:e("WorkflowLibraryEntry",_y),ContextFile:e("ContextFile",tr),CreateContextFileBody:e("CreateContextFileBody",nr),UpdateContextFileBody:e("UpdateContextFileBody",rr),LocalRepository:e("LocalRepository",or),CreateLocalRepositoryBody:e("CreateLocalRepositoryBody",ir),UpdateLocalRepositoryBody:e("UpdateLocalRepositoryBody",sr),DeleteWorktreesBody:e("DeleteWorktreesBody",fo),FilesystemBrowseResult:e("FilesystemBrowseResult",Rl),ImportWorkflowBody:e("ImportWorkflowBody",ro),ImportConflictResponse:e("ImportConflictResponse",Ku)}}var dy,py,fy,my,bo,hy,gy,yy,ms,Al,wy,by,Sy,xy,vy,jy,_y,Iy,Ey,Py,Ry,ky,Ay,P,hs,gs=l(()=>{"use strict";El();C();ns();ss();fs();kl();Gi();dy=p.enum(["pending","planning","waiting_for_human","waiting_for_children","implementing","testing","completed","failed","cancelled"]),py=p.object({subjectType:p.literal("ticket"),id:p.string(),source:p.string().min(1),title:p.string(),description:p.string().optional(),status:p.string(),assignee:p.string().optional(),url:p.string().optional(),raw:p.record(p.string(),p.unknown()).optional()}),fy=p.object({subjectType:p.literal("pull_request"),id:p.string(),source:p.string().min(1),title:p.string(),description:p.string().optional(),sourceBranch:p.string(),targetBranch:p.string(),author:p.string().optional(),url:p.string().optional(),raw:p.record(p.string(),p.unknown()).optional()}),my=p.object({subjectType:p.literal("documentation"),id:p.string(),source:p.string().min(1),title:p.string(),url:p.string().optional(),raw:p.record(p.string(),p.unknown()).optional()}),bo=p.discriminatedUnion("subjectType",[py,fy,my]),hy=p.discriminatedUnion("mode",[p.object({mode:p.literal("single"),subject:bo}),p.object({mode:p.literal("collection"),subjects:p.array(bo)})]),gy=p.object({id:p.string(),stepDefinitionId:p.string(),type:p.string(),status:p.enum(["pending","queued","running","waiting_for_children","completed","failed","skipped"]),startedAt:p.string().optional(),completedAt:p.string().optional(),output:p.unknown().optional(),error:p.string().optional(),failureDetails:p.record(p.string(),p.unknown()).optional(),childJobIds:p.array(p.string()).optional(),iterations:p.array(p.object({index:p.number().int(),stepExecutions:p.array(p.record(p.string(),p.unknown())),startedAt:p.string(),completedAt:p.string().optional()})).optional()}),yy=p.object({jobId:p.string(),stepExecutionId:p.string(),agentInstanceId:p.string(),enqueuedAt:p.string()}),ms=p.object({id:p.string(),workflowId:p.string(),status:dy,subjectContext:hy.optional(),selection:ho.optional(),batchId:p.string().optional(),parentJobId:p.string().optional(),parentStepExecutionId:p.string().optional(),fanOutIndex:p.number().int().optional(),retryOf:p.string().optional(),workflowSnapshot:xn.optional(),context:p.record(p.string(),p.unknown()),worktreePath:p.string().optional(),branch:p.string().optional(),worktreeDeletedAt:p.string().optional(),currentStepId:p.string().optional(),currentStepExecutionId:p.string().optional(),stepHistory:p.array(gy),createdAt:p.string(),updatedAt:p.string(),completedAt:p.string().optional()}),Al=p.object({id:p.string(),workflowId:p.string(),selection:ho,resolvedSubjects:p.array(bo),jobIds:p.array(p.string()),status:p.enum(["running","completed","completed_with_issues","failed","cancelled"]),triggeredBy:p.enum(["schedule","view_bulk","multiselect"]),scheduleId:p.string().optional(),notificationOverride:Sn.optional(),notificationSent:p.boolean(),createdAt:p.string(),completedAt:p.string().optional()}),wy=p.discriminatedUnion("kind",[p.object({kind:p.literal("job"),job:ms}),p.object({kind:p.literal("batch"),batch:Al})]),by=p.object({ok:p.boolean(),service:p.string(),timestamp:p.string()}),Sy=p.object({providerId:p.string(),secretKey:p.string(),configured:p.boolean()}),xy=p.object({error:p.string()}),vy=p.object({type:p.string(),timestamp:p.string()}).passthrough(),jy=it,_y=p.object({id:p.string().min(1),source:p.enum(["example","community","official"]),name:p.string().min(1),description:p.string(),workflowDefinition:it}),Iy=Xn,Ey=Jt.partial().omit({id:!0}),Py=p.record(p.string(),ms.nullable()),Ry=fr,ky=p.object({settings:pr,restartRequired:p.literal(!0)}),Ay=p.object({settings:pr,restartRequired:p.boolean()}),P=p.object({id:p.string().min(1)}),hs=p.object({limit:p.string().optional().openapi({description:"Max items to return (default 50)"}),offset:p.string().optional().openapi({description:"Number of items to skip (default 0)"})})});import{z as j}from"zod";function y(n,e){return{description:e,content:{"application/json":{schema:n}}}}function F(n){return{type:"array",items:n}}function b(n,...e){let t={400:"Validation error",404:"Resource not found",409:"Conflict"};return Object.fromEntries(e.map(r=>[String(r),y(n.ErrorResponse,t[r]??"Error")]))}function Tl(n,e){n.registerPath({method:"get",path:"/health",tags:["Health"],summary:"Health check",responses:{200:y(e.HealthResponse,"Service is healthy")}}),n.registerPath({method:"get",path:"/workflows",tags:["Workflows"],summary:"List workflow definitions",request:{query:j.object({subjectHandling:j.enum(["per-subject","collection"]).optional()})},responses:{200:y(F(e.WorkflowDefinition),"Workflow definitions"),...b(e,400)}}),n.registerPath({method:"get",path:"/workflows/instructions",tags:["Workflows"],summary:"Download generated agent authoring instructions",description:"Markdown generated at request time from the live StepDefinition Zod schema via z.toJSONSchema().",responses:{200:{description:"Markdown agent instructions",content:{"text/markdown":{schema:{type:"string"}}}}}}),n.registerPath({method:"post",path:"/workflows/import",tags:["Workflows"],summary:"Import a workflow definition from a JSON file",description:"Validates with the input schema (ids optional), assigns missing ids only, and preserves existing ids. If the file has an id that already exists and resolution is omitted, returns 409 with no write.",request:{body:{required:!0,content:{"application/json":{schema:e.ImportWorkflowBody}}}},responses:{200:y(e.WorkflowDefinition,"Updated existing workflow"),201:y(e.WorkflowDefinition,"Created workflow definition"),...b(e,400),409:y(e.ImportConflictResponse,"A workflow with this id already exists")}}),n.registerPath({method:"get",path:"/workflows/{id}/export",tags:["Workflows"],summary:"Export a workflow definition as stored (ids preserved)",request:{params:P},responses:{200:y(e.WorkflowDefinition,"Workflow definition"),...b(e,404)}}),n.registerPath({method:"get",path:"/workflows/{id}",tags:["Workflows"],summary:"Get a workflow definition",request:{params:P},responses:{200:y(e.WorkflowDefinition,"Workflow definition"),...b(e,404)}}),n.registerPath({method:"post",path:"/workflows",tags:["Workflows"],summary:"Create a workflow definition",request:{body:{required:!0,content:{"application/json":{schema:e.WorkflowDefinitionInput}}}},responses:{201:y(e.WorkflowDefinition,"Created workflow definition"),...b(e,400)}}),n.registerPath({method:"patch",path:"/workflows/{id}",tags:["Workflows"],summary:"Update a workflow definition",request:{params:P,body:{required:!0,content:{"application/json":{schema:e.UpdateWorkflowBody}}}},responses:{200:y(e.WorkflowDefinition,"Updated workflow definition"),...b(e,400,404)}}),n.registerPath({method:"delete",path:"/workflows/{id}",tags:["Workflows"],summary:"Delete a workflow definition",description:"Deletes the live workflow definition. Running Jobs keep executing from the snapshot captured at Job creation.",request:{params:P},responses:{204:{description:"Workflow deleted"},...b(e,404)}}),n.registerPath({method:"get",path:"/workflow-library",tags:["Workflow Library"],summary:"List bundled workflow library entries",responses:{200:y(F(e.WorkflowLibraryEntry),"Workflow library entries")}}),n.registerPath({method:"post",path:"/workflow-library/{id}/add",tags:["Workflow Library"],summary:"Copy a library entry into the workspace as a new workflow",request:{params:P},responses:{201:y(e.WorkflowDefinition,"Created workflow definition"),...b(e,400,404)}}),n.registerPath({method:"get",path:"/views",tags:["Views"],summary:"List subject views",request:{query:j.object({subjectType:oe.optional()})},responses:{200:y(F(e.SubjectView),"Subject views"),...b(e,400)}}),n.registerPath({method:"get",path:"/views/{id}",tags:["Views"],summary:"Get a subject view",request:{params:P},responses:{200:y(e.SubjectView,"Subject view"),...b(e,404)}}),n.registerPath({method:"get",path:"/views/{id}/subjects",tags:["Views"],summary:"Preview subjects matching a view",description:"Live provider query for the View's saved filter. Same resolution path as launch() for { mode: 'view' }. Does not create Jobs or snapshots.",request:{params:P},responses:{200:y(F(e.Subject),"Matching subjects"),...b(e,404,400)}}),n.registerPath({method:"patch",path:"/views/reorder",tags:["Views"],summary:"Reorder views within a subject type group",request:{body:{required:!0,content:{"application/json":{schema:e.ReorderViewsBody}}}},responses:{200:y(F(e.SubjectView),"Reordered views for the subject type"),...b(e,400)}}),n.registerPath({method:"post",path:"/views",tags:["Views"],summary:"Create a subject view",request:{body:{required:!0,content:{"application/json":{schema:e.CreateSubjectViewBody}}}},responses:{201:y(e.SubjectView,"Created subject view"),...b(e,400)}}),n.registerPath({method:"patch",path:"/views/{id}",tags:["Views"],summary:"Update a subject view",request:{params:P,body:{required:!0,content:{"application/json":{schema:e.UpdateViewBody}}}},responses:{200:y(e.SubjectView,"Updated subject view"),...b(e,400,404)}}),n.registerPath({method:"delete",path:"/views/{id}",tags:["Views"],summary:"Delete a subject view",request:{params:P},responses:{204:{description:"Subject view deleted"},...b(e,404)}}),n.registerPath({method:"get",path:"/jobs",tags:["Jobs"],summary:"List jobs",request:{query:hs.extend({workflowId:j.string().optional(),status:j.enum(["pending","planning","waiting_for_human","waiting_for_children","implementing","testing","completed","failed","cancelled"]).optional(),batchId:j.string().optional(),parentJobId:j.string().optional(),topLevelOnly:j.enum(["true","false"]).optional().openapi({description:"When true, exclude jobs that belong to a batch or a parent (sub_workflow) job"}),terminal:j.enum(["true","false"]).optional().openapi({description:"When true, only completed/failed/cancelled jobs. When false, only in-progress jobs. Omitted: no terminality filter."}),liveWorktree:j.enum(["true","false"]).optional().openapi({description:"When true, only jobs with a worktreePath that has not been deleted from the management page."})})},responses:{200:y(F(e.Job),"Jobs"),...b(e,400)}}),n.registerPath({method:"get",path:"/jobs/queued",tags:["Jobs"],summary:"List agent steps waiting for a concurrency slot",responses:{200:y(F(e.QueuedAgentStep),"Queued agent steps")}}),n.registerPath({method:"post",path:"/jobs/delete-worktrees",tags:["Jobs"],summary:"Delete live worktree folders for terminal jobs",request:{body:{required:!0,content:{"application/json":{schema:e.DeleteWorktreesBody}}}},responses:{200:y(F(e.Job),"Jobs after worktree deletion"),...b(e,400,404,409)}}),n.registerPath({method:"get",path:"/jobs/{id}",tags:["Jobs"],summary:"Get a job",request:{params:P},responses:{200:y(e.Job,"Job"),...b(e,404)}}),n.registerPath({method:"post",path:"/jobs",tags:["Jobs"],summary:"Start a single job",request:{body:{required:!0,content:{"application/json":{schema:e.CreateJobBody}}}},responses:{201:y(e.Job,"Started job"),...b(e,400,404)}}),n.registerPath({method:"post",path:"/jobs/latest-by-subject",tags:["Jobs"],summary:"Latest job per subject for a workflow",request:{body:{required:!0,content:{"application/json":{schema:e.LatestBySubjectBody}}}},responses:{200:y(e.LatestBySubjectResponse,"Latest job keyed by subject id"),...b(e,400)}}),n.registerPath({method:"post",path:"/jobs/{id}/resume",tags:["Jobs"],summary:"Resume a job waiting for human input",request:{params:P,body:{required:!0,content:{"application/json":{schema:e.ResumeJobBody}}}},responses:{200:y(e.Job,"Resumed job"),...b(e,400,404,409)}}),n.registerPath({method:"post",path:"/jobs/{id}/retry",tags:["Jobs"],summary:"Retry a failed job as a new linked job",request:{params:P},responses:{200:y(e.Job,"Retry job"),...b(e,404,409)}}),n.registerPath({method:"post",path:"/jobs/{id}/retry-step",tags:["Jobs"],summary:"Retry the failed step of a job in place",request:{params:P,body:{required:!1,content:{"application/json":{schema:e.RetryStepBody}}}},responses:{200:y(e.Job,"Job after retrying the failed step"),...b(e,400,404,409)}}),n.registerPath({method:"post",path:"/jobs/{id}/cancel",tags:["Jobs"],summary:"Cancel a non-terminal job",request:{params:P},responses:{200:y(e.Job,"Cancelled job"),...b(e,404,409)}}),n.registerPath({method:"get",path:"/batches",tags:["Batches"],summary:"List job batches",request:{query:hs.extend({workflowId:j.string().optional()})},responses:{200:y(F(e.JobBatch),"Job batches")}}),n.registerPath({method:"get",path:"/batches/{id}",tags:["Batches"],summary:"Get a job batch",request:{params:P},responses:{200:y(e.JobBatch,"Job batch"),...b(e,404)}}),n.registerPath({method:"get",path:"/batches/{id}/jobs",tags:["Batches"],summary:"List jobs in a batch",request:{params:P},responses:{200:y(F(e.Job),"Jobs in the batch"),...b(e,404)}}),n.registerPath({method:"post",path:"/batches",tags:["Batches"],summary:"Launch a per-subject batch or collection run",description:"Resolves subject selection and starts a JobBatch for per-subject workflows (even for one subject) or a single Job for collection workflows.",request:{body:{required:!0,content:{"application/json":{schema:e.LaunchBody}}}},responses:{201:y(e.LaunchResponse,"Launch result"),...b(e,400,404)}}),n.registerPath({method:"post",path:"/batches/{id}/cancel",tags:["Batches"],summary:"Cancel a running job batch",request:{params:P},responses:{200:y(e.JobBatch,"Cancelled batch"),...b(e,404,409)}}),n.registerPath({method:"get",path:"/workflow-shortcuts",tags:["Workflow shortcuts"],summary:"List workflow shortcuts",responses:{200:y(F(e.WorkflowShortcut),"Workflow shortcuts")}}),n.registerPath({method:"get",path:"/workflow-shortcuts/{id}",tags:["Workflow shortcuts"],summary:"Get a workflow shortcut",request:{params:P},responses:{200:y(e.WorkflowShortcut,"Workflow shortcut"),...b(e,404)}}),n.registerPath({method:"post",path:"/workflow-shortcuts",tags:["Workflow shortcuts"],summary:"Create a workflow shortcut",request:{body:{required:!0,content:{"application/json":{schema:e.CreateWorkflowShortcutBody}}}},responses:{201:y(e.WorkflowShortcut,"Created workflow shortcut"),...b(e,400,404)}}),n.registerPath({method:"patch",path:"/workflow-shortcuts/reorder",tags:["Workflow shortcuts"],summary:"Reorder workflow shortcuts",request:{body:{required:!0,content:{"application/json":{schema:e.ReorderShortcutsBody}}}},responses:{200:y(F(e.WorkflowShortcut),"Reordered workflow shortcuts"),...b(e,400)}}),n.registerPath({method:"patch",path:"/workflow-shortcuts/{id}",tags:["Workflow shortcuts"],summary:"Update a workflow shortcut",request:{params:P,body:{required:!0,content:{"application/json":{schema:e.UpdateWorkflowShortcutBody}}}},responses:{200:y(e.WorkflowShortcut,"Updated workflow shortcut"),...b(e,400,404)}}),n.registerPath({method:"delete",path:"/workflow-shortcuts/{id}",tags:["Workflow shortcuts"],summary:"Delete a workflow shortcut",request:{params:P},responses:{204:{description:"Workflow shortcut deleted"},...b(e,404)}}),n.registerPath({method:"get",path:"/context-files",tags:["Context Files"],summary:"List context files",responses:{200:y(F(e.ContextFile),"Context files")}}),n.registerPath({method:"get",path:"/context-files/{id}",tags:["Context Files"],summary:"Get a context file",request:{params:P},responses:{200:y(e.ContextFile,"Context file"),...b(e,404)}}),n.registerPath({method:"post",path:"/context-files",tags:["Context Files"],summary:"Create a context file",request:{body:{required:!0,content:{"application/json":{schema:e.CreateContextFileBody}}}},responses:{201:y(e.ContextFile,"Created context file"),...b(e,400)}}),n.registerPath({method:"patch",path:"/context-files/{id}",tags:["Context Files"],summary:"Update a context file",request:{params:P,body:{required:!0,content:{"application/json":{schema:e.UpdateContextFileBody}}}},responses:{200:y(e.ContextFile,"Updated context file"),...b(e,400,404)}}),n.registerPath({method:"delete",path:"/context-files/{id}",tags:["Context Files"],summary:"Delete a context file",request:{params:P},responses:{204:{description:"Context file deleted"},...b(e,404)}}),n.registerPath({method:"get",path:"/local-repositories",tags:["Local Repositories"],summary:"List local repositories",responses:{200:y(F(e.LocalRepository),"Local repositories")}}),n.registerPath({method:"get",path:"/local-repositories/{id}",tags:["Local Repositories"],summary:"Get a local repository",request:{params:P},responses:{200:y(e.LocalRepository,"Local repository"),...b(e,404)}}),n.registerPath({method:"post",path:"/local-repositories",tags:["Local Repositories"],summary:"Create a local repository",request:{body:{required:!0,content:{"application/json":{schema:e.CreateLocalRepositoryBody}}}},responses:{201:y(e.LocalRepository,"Created local repository"),...b(e,400)}}),n.registerPath({method:"patch",path:"/local-repositories/{id}",tags:["Local Repositories"],summary:"Update a local repository",request:{params:P,body:{required:!0,content:{"application/json":{schema:e.UpdateLocalRepositoryBody}}}},responses:{200:y(e.LocalRepository,"Updated local repository"),...b(e,400,404)}}),n.registerPath({method:"delete",path:"/local-repositories/{id}",tags:["Local Repositories"],summary:"Delete a local repository",request:{params:P},responses:{204:{description:"Local repository deleted"},...b(e,404)}}),n.registerPath({method:"get",path:"/filesystem/browse",tags:["Filesystem"],summary:"List a host directory",request:{query:j.object({path:j.string().optional(),mode:j.enum(["directories","files"]).optional(),extensions:j.string().optional()})},responses:{200:y(e.FilesystemBrowseResult,"Directory listing"),...b(e,400)}}),n.registerPath({method:"get",path:"/schedules",tags:["Schedules"],summary:"List schedules",request:{query:j.object({enabled:j.enum(["true","false"]).optional()})},responses:{200:y(F(e.Schedule),"Schedules"),...b(e,400)}}),n.registerPath({method:"get",path:"/schedules/{id}",tags:["Schedules"],summary:"Get a schedule",request:{params:P},responses:{200:y(e.Schedule,"Schedule"),...b(e,404)}}),n.registerPath({method:"post",path:"/schedules",tags:["Schedules"],summary:"Create a schedule",description:"CRUD only \u2014 creating or enabling a schedule does not cause it to fire yet.",request:{body:{required:!0,content:{"application/json":{schema:e.Schedule}}}},responses:{201:y(e.Schedule,"Created schedule"),...b(e,400)}}),n.registerPath({method:"patch",path:"/schedules/{id}",tags:["Schedules"],summary:"Update a schedule",request:{params:P,body:{required:!0,content:{"application/json":{schema:e.UpdateScheduleBody}}}},responses:{200:y(e.Schedule,"Updated schedule"),...b(e,400,404)}}),n.registerPath({method:"delete",path:"/schedules/{id}",tags:["Schedules"],summary:"Delete a schedule",request:{params:P},responses:{204:{description:"Schedule deleted"},...b(e,404)}}),n.registerPath({method:"get",path:"/providers/status",tags:["Providers"],summary:"Provider secret configuration status",description:"Reports whether each known provider API key is set. Returns key *names* only \u2014 never secret values.",responses:{200:y(F(e.ProviderStatus),"Provider configuration status")}}),n.registerPath({method:"post",path:"/providers/preview-models",tags:["Providers"],summary:"Preview models available to an agent API key",description:"Lookup only \u2014 does not persist settings or secrets. Send apiKey to try a typed key before save, or instanceId to use the already-stored key (never echoed).",request:{body:{required:!0,content:{"application/json":{schema:e.PreviewModelsBody}}}},responses:{200:y(F(e.PreviewModel),"Models available to the key"),...b(e,400,404)}}),n.registerPath({method:"get",path:"/providers/{providerId}/query-templates",tags:["Providers"],summary:"List query templates for a provider",description:"Named, pre-built query templates owned by the provider. Providers with none yet (e.g. documentation) return an empty list. The client never constructs `query` itself \u2014 it submits templateId + params to the resolve endpoint.",request:{params:j.object({providerId:j.string().min(1)})},responses:{200:y(F(e.QueryTemplate),"Query templates")}}),n.registerPath({method:"get",path:"/providers/{providerId}/actions",tags:["Providers"],summary:"List extended actions for a provider",description:"Opt-in capabilities beyond the portable five ProviderAction operations. Providers that do not implement ExtendedActionProvider return an empty list \u2014 that is a normal, expected case, not an error.",request:{params:j.object({providerId:j.string().min(1)})},responses:{200:y(F(e.ProviderActionDescriptor),"Extended actions")}}),n.registerPath({method:"post",path:"/providers/{providerId}/query-templates/{templateId}/resolve",tags:["Providers"],summary:"Resolve a query template to a concrete query",description:"Provider-specific query-shape knowledge stays server-side. Returns the `query` object to store on a SubjectView, along with template provenance the client attaches separately.",request:{params:j.object({providerId:j.string().min(1),templateId:j.string().min(1)}),body:{required:!0,content:{"application/json":{schema:e.ResolveQueryTemplateBody}}}},responses:{200:y(e.ResolveQueryTemplateResponse,"Resolved query"),...b(e,400,404)}}),n.registerPath({method:"get",path:"/settings",tags:["Settings"],summary:"Get engine settings",description:"Persisted provider configuration. Never includes secret values \u2014 those live in SecretStore.",responses:{200:y(e.EngineSettings,"Current engine settings")}}),n.registerPath({method:"patch",path:"/settings",tags:["Settings"],summary:"Update engine settings",description:"Partial merge. restartRequired is true when providerInstances is in the patch (instance bindings are boot-time). Changing defaultAgentInstanceId takes effect on the next agent step with no restart.",request:{body:{required:!0,content:{"application/json":{schema:e.UpdateSettingsBody}}}},responses:{200:y(e.SettingsPatchResponse,"Updated settings"),...b(e,400)}}),n.registerPath({method:"get",path:"/provider-instances",tags:["Settings"],summary:"List provider instances",responses:{200:y(F(e.ProviderInstanceConfig),"Configured provider instances")}}),n.registerPath({method:"post",path:"/provider-instances",tags:["Settings"],summary:"Create a provider instance",description:"Persists the instance. restartRequired is always true \u2014 bindings are boot-time. For agent instances, defaultAgent atomically replaces EngineSettings.defaultAgentInstanceId in the same write.",request:{body:{required:!0,content:{"application/json":{schema:e.CreateProviderInstanceBody}}}},responses:{201:y(e.ProviderInstanceMutationResponse,"Created instance settings"),...b(e,400,409)}}),n.registerPath({method:"get",path:"/provider-instances/{id}",tags:["Settings"],summary:"Get a provider instance",request:{params:j.object({id:j.string().min(1)})},responses:{200:y(e.ProviderInstanceConfig,"Provider instance"),...b(e,404)}}),n.registerPath({method:"patch",path:"/provider-instances/{id}",tags:["Settings"],summary:"Update a provider instance",request:{params:j.object({id:j.string().min(1)}),body:{required:!0,content:{"application/json":{schema:e.UpdateProviderInstanceBody}}}},responses:{200:y(e.ProviderInstanceMutationResponse,"Updated instance settings"),...b(e,400,404)}}),n.registerPath({method:"delete",path:"/provider-instances/{id}",tags:["Settings"],summary:"Delete a provider instance",request:{params:j.object({id:j.string().min(1)})},responses:{200:y(e.ProviderInstanceMutationResponse,"Updated settings after delete"),...b(e,404)}}),n.registerPath({method:"post",path:"/secrets/{key}",tags:["Settings"],summary:"Store a secret",description:"Writes to SecretStore. The response never includes the secret value.",request:{params:j.object({key:j.string().min(1)}),body:{required:!0,content:{"application/json":{schema:e.SetSecretBody}}}},responses:{204:{description:"Secret stored"},...b(e,400)}}),n.registerPath({method:"get",path:"/events",tags:["Events"],summary:"Subscribe to engine events (SSE)",description:"Server-Sent Events stream. Each event `data` field is a JSON EngineEvent. Optionally filter by jobId and/or batchId.",request:{query:j.object({jobId:j.string().optional(),batchId:j.string().optional()})},responses:{200:{description:"SSE stream of engine events",content:{"text/event-stream":{schema:e.EngineEvent}}}}})}var Ol=l(()=>{"use strict";C();gs()});import{OpenAPIRegistry as Ty,OpenApiGeneratorV31 as Oy}from"@asteasolutions/zod-to-openapi";function $l(){if(So)return So;let n=new Ty,e=Cl(n);return Tl(n,e),So=new Oy(n.definitions).generateDocument({openapi:"3.1.0",info:{title:"Knoflows Engine API",version:"0.1.0",description:"REST API for workflow definitions, jobs, batches, schedules, views, and live events."},servers:[{url:"/api"}]}),So}var So,ql=l(()=>{"use strict";gs();Ol()});import{Controller as $y,Get as qy,Header as Dy}from"@nestjs/common";var Dl,ys,On,Bl=l(()=>{"use strict";ql();Dl=function(n,e,t,r){var o=arguments.length,i=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},ys=function(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)},On=class{getOpenApiDocument(){return $l()}};Dl([qy("openapi.json"),Dy("Content-Type","application/json"),ys("design:type",Function),ys("design:paramtypes",[]),ys("design:returntype",void 0)],On.prototype,"getOpenApiDocument",null);On=Dl([$y()],On)});import{Controller as By,Get as ws,Inject as xo,Param as vo,Post as Fl,Body as Nl,HttpCode as Jl}from"@nestjs/common";var zt,K,Be,Ve,Ll=l(()=>{"use strict";pi();ji();_i();Pi();C();ae();zt=function(n,e,t,r){var o=arguments.length,i=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},K=function(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)},Be=function(n,e){return function(t,r){e(t,r,n)}},Ve=class{providerStatus;queryTemplates;extendedActions;previewModels;constructor(e,t,r,o){this.providerStatus=e,this.queryTemplates=t,this.extendedActions=r,this.previewModels=o}async status(){return this.providerStatus.list()}previewAvailableModels(e){return this.previewModels.preview(e)}listQueryTemplates(e){return this.queryTemplates.list(e)}listExtendedActions(e){return this.extendedActions.list(e)}async resolveQueryTemplate(e,t,r){return{query:await this.queryTemplates.resolve(e,t,r.params)}}};zt([ws("status"),K("design:type",Function),K("design:paramtypes",[]),K("design:returntype",Promise)],Ve.prototype,"status",null);zt([Fl("preview-models"),Jl(200),Be(0,Nl(new v(gr))),K("design:type",Function),K("design:paramtypes",[Object]),K("design:returntype",Promise)],Ve.prototype,"previewAvailableModels",null);zt([ws(":providerId/query-templates"),Be(0,vo("providerId")),K("design:type",Function),K("design:paramtypes",[String]),K("design:returntype",Promise)],Ve.prototype,"listQueryTemplates",null);zt([ws(":providerId/actions"),Be(0,vo("providerId")),K("design:type",Function),K("design:paramtypes",[String]),K("design:returntype",Promise)],Ve.prototype,"listExtendedActions",null);zt([Fl(":providerId/query-templates/:templateId/resolve"),Jl(200),Be(0,vo("providerId")),Be(1,vo("templateId")),Be(2,Nl(new v(Vn))),K("design:type",Function),K("design:paramtypes",[String,String,Object]),K("design:returntype",Promise)],Ve.prototype,"resolveQueryTemplate",null);Ve=zt([By("providers"),Be(0,xo(st)),Be(1,xo(at)),Be(2,xo(ct)),Be(3,xo(ut)),K("design:paramtypes",[st,at,ct,ut])],Ve)});import{Body as Fy,Controller as Ny,Get as Jy,Inject as Ly,Patch as Uy}from"@nestjs/common";var bs,qt,Ul,Xt,Ml=l(()=>{"use strict";C();ye();ae();bs=function(n,e,t,r){var o=arguments.length,i=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},qt=function(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)},Ul=function(n,e){return function(t,r){e(t,r,n)}},Xt=class{settings;constructor(e){this.settings=e}get(){return this.settings.get()}async update(e){return{settings:await this.settings.update(e),restartRequired:Ec(e)}}};bs([Jy(),qt("design:type",Function),qt("design:paramtypes",[]),qt("design:returntype",Promise)],Xt.prototype,"get",null);bs([Uy(),Ul(0,Fy(new v(fr))),qt("design:type",Function),qt("design:paramtypes",[Object]),qt("design:returntype",Promise)],Xt.prototype,"update",null);Xt=bs([Ny("settings"),Ul(0,Ly(E)),qt("design:paramtypes",[E])],Xt)});function Ss(n){let{current:e,instance:t,defaultAgent:r,isCreate:o}=n;return Oe(t)?r===!0?t.id:r===!1?e===t.id?null:e??null:o&&!e?t.id:e??null:e===t.id?null:e??null}function Wl(n){let{defaultAgent:e,...t}=n;return t}var Hl=l(()=>{"use strict";C()});import{Body as Gl,Controller as My,Delete as Wy,Get as Kl,HttpCode as Hy,Inject as Gy,Param as xs,Patch as Ky,Post as Vy}from"@nestjs/common";var Zt,V,Yt,Qe,Vl=l(()=>{"use strict";C();ye();R();ae();Hl();Zt=function(n,e,t,r){var o=arguments.length,i=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},V=function(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)},Yt=function(n,e){return function(t,r){e(t,r,n)}},Qe=class{settings;constructor(e){this.settings=e}async list(){return(await this.settings.get()).providerInstances??[]}async get(e){let t=(await this.settings.get()).providerInstances?.find(r=>r.id===e);if(!t)throw new g(`Provider instance not found: ${e}`);return t}async create(e){let t=Wl(e),r=await this.settings.get(),o=[...r.providerInstances??[]];if(o.some(s=>s.id===t.id))throw new B(`Provider instance already exists: ${t.id}`);return o.push(t),{settings:await this.settings.update({providerInstances:o,defaultAgentInstanceId:Ss({current:r.defaultAgentInstanceId,instance:t,defaultAgent:e.defaultAgent,isCreate:!0})}),restartRequired:!0}}async update(e,t){let r=await this.settings.get(),o=[...r.providerInstances??[]],i=o.findIndex(c=>c.id===e);if(i<0)throw new g(`Provider instance not found: ${e}`);let a={...o[i],...t.displayName!=null?{displayName:t.displayName}:{},...t.config!=null?{config:t.config}:{},...t.secretKey!=null?{secretKey:t.secretKey}:{}};return t.expiresOn!==void 0&&(t.expiresOn?a.expiresOn=t.expiresOn:delete a.expiresOn),t.maxConcurrent!=null&&a.kind==="agent"&&(a.maxConcurrent=t.maxConcurrent),o[i]=a,{settings:await this.settings.update({providerInstances:o,defaultAgentInstanceId:Ss({current:r.defaultAgentInstanceId,instance:a,defaultAgent:t.defaultAgent,isCreate:!1})}),restartRequired:!0}}async remove(e){let t=await this.settings.get(),r=(t.providerInstances??[]).filter(s=>s.id!==e);if(r.length===(t.providerInstances??[]).length)throw new g(`Provider instance not found: ${e}`);let o=t.defaultAgentInstanceId===e?null:t.defaultAgentInstanceId??null;return{settings:await this.settings.update({providerInstances:r,defaultAgentInstanceId:o}),restartRequired:!0}}};Zt([Kl(),V("design:type",Function),V("design:paramtypes",[]),V("design:returntype",Promise)],Qe.prototype,"list",null);Zt([Kl(":id"),Yt(0,xs("id")),V("design:type",Function),V("design:paramtypes",[String]),V("design:returntype",Promise)],Qe.prototype,"get",null);Zt([Vy(),Yt(0,Gl(new v(mr))),V("design:type",Function),V("design:paramtypes",[Object]),V("design:returntype",Promise)],Qe.prototype,"create",null);Zt([Ky(":id"),Yt(0,xs("id")),Yt(1,Gl(new v(hr))),V("design:type",Function),V("design:paramtypes",[String,Object]),V("design:returntype",Promise)],Qe.prototype,"update",null);Zt([Wy(":id"),Hy(200),Yt(0,xs("id")),V("design:type",Function),V("design:paramtypes",[String]),V("design:returntype",Promise)],Qe.prototype,"remove",null);Qe=Zt([My("provider-instances"),Yt(0,Gy(E)),V("design:paramtypes",[E])],Qe)});import{Body as Qy,Controller as zy,HttpCode as Xy,Inject as Yy,Param as Zy,Post as ew}from"@nestjs/common";var Ql,jo,vs,$n,zl=l(()=>{"use strict";Fe();R();ae();fs();Ql=function(n,e,t,r){var o=arguments.length,i=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},jo=function(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)},vs=function(n,e){return function(t,r){e(t,r,n)}},$n=class{secrets;constructor(e){this.secrets=e}async set(e,t){let r=e.trim();if(!r)throw new h("Secret key must not be empty");await this.secrets.set(r,t.value)}};Ql([ew(":key"),Xy(204),vs(0,Zy("key")),vs(1,Qy(new v(wo))),jo("design:type",Function),jo("design:paramtypes",[String,Object]),jo("design:returntype",Promise)],$n.prototype,"set",null);$n=Ql([zy("secrets"),vs(0,Yy(he)),jo("design:paramtypes",[Function])],$n)});import{readFile as tw}from"node:fs/promises";async function js(n){try{await tw(n,"utf8")}catch(e){let t=e instanceof Error?e.message:String(e);throw new h(`Cannot read context file at '${n}': ${t}`)}}var Xl=l(()=>{"use strict";R()});import{Body as Yl,Controller as nw,Delete as rw,Get as Zl,HttpCode as ow,Inject as iw,Param as _s,Patch as sw,Post as aw}from"@nestjs/common";import{randomUUID as cw}from"node:crypto";var tn,Q,en,ze,ed=l(()=>{"use strict";C();Gn();R();ae();Xl();tn=function(n,e,t,r){var o=arguments.length,i=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Q=function(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)},en=function(n,e){return function(t,r){e(t,r,n)}},ze=class{files;constructor(e){this.files=e}async list(){return this.files.list()}async get(e){let t=await this.files.get(e);if(!t)throw new g(`Context file not found: ${e}`);return t}async create(e){return await js(e.path),this.files.create({id:e.id??cw(),name:e.name,description:e.description,tier:e.tier,path:e.path})}async update(e,t){let r=await this.files.get(e);if(!r)throw new g(`Context file not found: ${e}`);let o=t.path??r.path;await js(o);let i=await this.files.update(e,t);if(!i)throw new g(`Context file not found: ${e}`);return i}async remove(e){if(!await this.files.delete(e))throw new g(`Context file not found: ${e}`)}};tn([Zl(),Q("design:type",Function),Q("design:paramtypes",[]),Q("design:returntype",Promise)],ze.prototype,"list",null);tn([Zl(":id"),en(0,_s("id")),Q("design:type",Function),Q("design:paramtypes",[String]),Q("design:returntype",Promise)],ze.prototype,"get",null);tn([aw(),en(0,Yl(new v(nr))),Q("design:type",Function),Q("design:paramtypes",[Object]),Q("design:returntype",Promise)],ze.prototype,"create",null);tn([sw(":id"),en(0,_s("id")),en(1,Yl(new v(rr))),Q("design:type",Function),Q("design:paramtypes",[String,Object]),Q("design:returntype",Promise)],ze.prototype,"update",null);tn([rw(":id"),ow(204),en(0,_s("id")),Q("design:type",Function),Q("design:paramtypes",[String]),Q("design:returntype",Promise)],ze.prototype,"remove",null);ze=tn([nw("context-files"),en(0,iw(de)),Q("design:paramtypes",[de])],ze)});import{execFile as uw}from"node:child_process";import{stat as lw}from"node:fs/promises";import{resolve as Is}from"node:path";import{promisify as dw}from"node:util";async function Es(n){let e=Is(n);try{if((await pw("git",["-C",e,"rev-parse","--is-inside-work-tree"],{encoding:"utf8",windowsHide:!0})).stdout.trim()!=="true")throw new Error("not a work tree")}catch(t){let r=t instanceof Error?t.message:String(t);throw new h(`'${n}' is not a git repository: ${r}`)}}async function Ps(n,e){let t=Is(n),r=Is(e?.trim()?e.trim():Vr(t));if(Qr(t,r))throw new h(`Worktree base '${r}' must not be inside the repository at '${t}'`);try{if(!(await lw(r)).isDirectory())throw new h(`Worktree base '${r}' exists and is not a directory`)}catch(o){if(o instanceof h)throw o}}var pw,td=l(()=>{"use strict";R();Ji();pw=dw(uw)});import{Body as nd,Controller as fw,Delete as mw,Get as rd,HttpCode as hw,Inject as gw,Param as Rs,Patch as yw,Post as ww}from"@nestjs/common";import{randomUUID as bw}from"node:crypto";var rn,z,nn,Xe,od=l(()=>{"use strict";C();Kn();R();ae();td();rn=function(n,e,t,r){var o=arguments.length,i=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},z=function(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)},nn=function(n,e){return function(t,r){e(t,r,n)}},Xe=class{repos;constructor(e){this.repos=e}async list(){return this.repos.list()}async get(e){let t=await this.repos.get(e);if(!t)throw new g(`Local repository not found: ${e}`);return t}async create(e){return await Es(e.localPath),await Ps(e.localPath,e.worktreeBasePath),this.repos.create({id:e.id??bw(),name:e.name,localPath:e.localPath,...e.worktreeBasePath?{worktreeBasePath:e.worktreeBasePath}:{},...e.defaultBranch?{defaultBranch:e.defaultBranch}:{}})}async update(e,t){let r=await this.repos.get(e);if(!r)throw new g(`Local repository not found: ${e}`);let o=t.localPath??r.localPath,i=t.worktreeBasePath!==void 0?t.worktreeBasePath:r.worktreeBasePath;await Es(o),await Ps(o,i);let s=await this.repos.update(e,t);if(!s)throw new g(`Local repository not found: ${e}`);return s}async remove(e){if(!await this.repos.delete(e))throw new g(`Local repository not found: ${e}`)}};rn([rd(),z("design:type",Function),z("design:paramtypes",[]),z("design:returntype",Promise)],Xe.prototype,"list",null);rn([rd(":id"),nn(0,Rs("id")),z("design:type",Function),z("design:paramtypes",[String]),z("design:returntype",Promise)],Xe.prototype,"get",null);rn([ww(),nn(0,nd(new v(ir))),z("design:type",Function),z("design:paramtypes",[Object]),z("design:returntype",Promise)],Xe.prototype,"create",null);rn([yw(":id"),nn(0,Rs("id")),nn(1,nd(new v(sr))),z("design:type",Function),z("design:paramtypes",[String,Object]),z("design:returntype",Promise)],Xe.prototype,"update",null);rn([mw(":id"),hw(204),nn(0,Rs("id")),z("design:type",Function),z("design:paramtypes",[String]),z("design:returntype",Promise)],Xe.prototype,"remove",null);Xe=rn([fw("local-repositories"),nn(0,gw(pe)),z("design:paramtypes",[pe])],Xe)});import{readdir as Sw,stat as xw}from"node:fs/promises";import{homedir as vw}from"node:os";import{join as jw,resolve as _w}from"node:path";async function id(n,e={}){let t=n?.trim()?n.trim():vw(),r=_w(t),o;try{o=await xw(r)}catch(s){throw new h(`Cannot browse '${r}': ${s instanceof Error?s.message:String(s)}`)}if(!o.isDirectory())throw new h(`Cannot browse '${r}': not a directory`);let i;try{i=(await Sw(r,{encoding:"utf8",withFileTypes:!0})).filter(a=>a.name!=="."&&a.name!=="..").map(a=>({name:a.name,path:jw(r,a.name),isDirectory:a.isDirectory()})).filter(a=>Iw(a,e)).sort((a,u)=>a.isDirectory!==u.isDirectory?a.isDirectory?-1:1:a.name.localeCompare(u.name))}catch(s){throw new h(`Cannot browse '${r}': ${s instanceof Error?s.message:String(s)}`)}return{path:r,entries:i}}function sd(n){if(n==null||n.trim()==="")return;let e=n.split(",").map(t=>cd(t)).filter(t=>t!=null);return e.length>0?e:void 0}function ad(n){if(!(n==null||n.trim()==="")){if(n==="directories"||n==="files")return n;throw new h(`Invalid browse mode '${n}'`)}}function Iw(n,e){if(e.mode==="directories")return n.isDirectory;if(n.isDirectory)return!0;let t=e.extensions?.map(o=>cd(o)).filter(Boolean);if(!t?.length)return!0;let r=n.name.toLowerCase();return t.some(o=>r.endsWith(o))}function cd(n){let e=n.trim().toLowerCase();if(e.length!==0)return e.startsWith(".")?e:`.${e}`}var ud=l(()=>{"use strict";R()});import{Controller as Ew,Get as Pw,Query as Cs}from"@nestjs/common";var ld,ks,As,qn,dd=l(()=>{"use strict";ud();ld=function(n,e,t,r){var o=arguments.length,i=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},ks=function(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)},As=function(n,e){return function(t,r){e(t,r,n)}},qn=class{async browse(e,t,r){return id(e,{mode:ad(t),extensions:sd(r)})}};ld([Pw("browse"),As(0,Cs("path")),As(1,Cs("mode")),As(2,Cs("extensions")),ks("design:type",Function),ks("design:paramtypes",[String,String,String]),ks("design:returntype",Promise)],qn.prototype,"browse",null);qn=ld([Ew("filesystem")],qn)});import{Module as kw}from"@nestjs/common";import{APP_FILTER as Aw}from"@nestjs/core";var Rw,_o,pd=l(()=>{"use strict";_n();Wi();Ur();Fu();el();cl();ll();ml();gl();wl();xl();Il();Bl();Ll();Ml();Vl();zl();ed();od();dd();Jr();Bo();Rw=function(n,e,t,r){var o=arguments.length,i=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},_o=class{};_o=Rw([kw({imports:[$e,Gt,dt,lt,Ft],controllers:[me,Kt,_e,qe,ne,Ge,Ke,Tn,On,Ve,Xt,Qe,$n,ze,Xe,qn],providers:[{provide:Aw,useClass:Zr}]})],_o)});import{Module as Tw}from"@nestjs/common";var Cw,Io,fd=l(()=>{"use strict";qs();Ds();Bs();Jr();Ur();_n();Wi();pd();Cw=function(n,e,t,r){var o=arguments.length,i=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Io=class{};Io=Cw([Tw({imports:[Dn,Bn,lt,dt,$e,Gt,_o],controllers:[on]})],Io)});import{apiReference as Ow}from"@scalar/nestjs-api-reference";function md(n){n.use("/api/docs",Ow({url:"/api/openapi.json",pageTitle:"Knoflows Engine API"}))}var hd=l(()=>{"use strict"});import{createServer as $w}from"node:net";function gd(n){return typeof n=="object"&&n!==null&&"code"in n&&n.code==="EADDRINUSE"}async function Ts(n,e=20){for(let t=0;t<e;t+=1){let r=n+t;if(await qw(r))return r}throw new Error(`No free port found in ${n}\u2013${n+e-1}`)}function qw(n){return new Promise(e=>{let t=$w();t.once("error",()=>{e(!1)}),t.once("listening",()=>{t.close(()=>e(!0))}),t.listen(n)})}var yd=l(()=>{"use strict"});import{Catch as Fw,HttpStatus as Eo,NotFoundException as Nw}from"@nestjs/common";import{existsSync as wd,statSync as Jw}from"node:fs";import{extname as bd,join as Os,normalize as Lw,relative as Uw,sep as Mw}from"node:path";function Sd(n){return(e,t,r)=>{if(e.method!=="GET"&&e.method!=="HEAD"){r();return}if((e.path??"").startsWith("/api")){r();return}let o=Ww(e.path??"/");if(o){let i=Os(n,o);if(Hw(n,i)){t.sendFile(o,{root:n},s=>{s&&r()});return}}if(xd(e)){vd(t,n,i=>{i&&!t.headersSent&&t.status(Eo.NOT_FOUND).end()});return}t.status(Eo.NOT_FOUND).end()}}function xd(n){if(n.method!=="GET"&&n.method!=="HEAD")return!1;let e=n.path??"";if(e.startsWith("/api"))return!1;let t=bd(e);return!(t&&t!==".html")}function vd(n,e,t){n.sendFile("index.html",{root:e},t)}function Ww(n){if(n==="/"||n==="")return"index.html";let e=Lw(n.replace(/^\/+/,""));return!e||e==="."||e.startsWith("..")||!bd(e)?null:e}function Hw(n,e){if(!wd(e))return!1;try{if(!Jw(e).isFile())return!1}catch{return!1}let t=Uw(n,e);return t!==""&&!t.startsWith(`..${Mw}`)&&!t.startsWith("..")}function jd(n){return Os(n,"index.html")}var Dw,Bw,Po,_d=l(()=>{"use strict";Dw=function(n,e,t,r){var o=arguments.length,i=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Bw=function(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)},Po=class{staticRoot;constructor(e){this.staticRoot=e}catch(e,t){let r=t.switchToHttp(),o=r.getRequest(),i=r.getResponse();if(xd(o)&&wd(Os(this.staticRoot,"index.html"))){vd(i,this.staticRoot,u=>{u&&!i.headersSent&&i.status(Eo.NOT_FOUND).json({statusCode:Eo.NOT_FOUND,message:"UI index.html could not be served"})});return}let s=e.getStatus(),a=e.getResponse();i.status(s).json(typeof a=="string"?{statusCode:s,message:a}:a)}};Po=Dw([Fw(Nw),Bw("design:paramtypes",[String])],Po)});import{existsSync as Gw}from"node:fs";import{dirname as Kw,join as Ro}from"node:path";import{fileURLToPath as Vw}from"node:url";function Id(){let n=Kw(Vw(import.meta.url)),e=[Ro(n,"../static"),Ro(n,"../../static"),Ro(n,"static")];for(let t of e)if(Gw(Ro(t,"index.html")))return t;return null}var Ed=l(()=>{"use strict"});var Zw={};import"reflect-metadata";import{existsSync as Qw}from"node:fs";import{Logger as zw}from"@nestjs/common";import{NestFactory as Xw}from"@nestjs/core";async function Yw(){let n=await Xw.create(Io);n.enableCors(),n.setGlobalPrefix("api"),md(n);let e=Id(),t=e?jd(e):null;e&&t&&Qw(t)?(ko.log(`Serving UI from ${e}`),n.use(Sd(e)),n.useGlobalFilters(new Po(e))):ko.warn("No UI found (static/index.html missing). GET / will 404; /api still works. Rebuild with `npm run build:release` before publishing.");let r=Number(process.env.PORT??3e3);if(!Number.isInteger(r)||r<1||r>65535)throw new Error(`Invalid PORT: ${process.env.PORT}`);let o=await Ts(r);for(let i=0;i<5;i+=1)try{await n.listen(o),o!==r?ko.warn(`Port ${r} is in use; listening on ${o} instead`):ko.log(`Listening on http://localhost:${o}`);return}catch(s){if(!gd(s))throw s;o=await Ts(o+1)}throw new Error(`Could not bind a free port starting at ${r}`)}var ko,Pd=l(()=>{"use strict";fd();hd();yd();_d();Ed();ko=new zw("Bootstrap");Yw()});import{readFileSync as eb}from"node:fs";function tb(){let n=eb(new URL("../package.json",import.meta.url),"utf8");return JSON.parse(n).version}var Ao=process.argv.slice(2);Ao.includes("--version")||Ao.includes("-v")?console.log(tb()):Ao.includes("--help")||Ao.includes("-h")?console.log(["Usage: knoflows [options]","","Starts the knoflows engine (REST API + bundled web client).","","Options:"," -v, --version Print the engine version and exit"," -h, --help Print this message and exit","","Environment:"," PORT Preferred HTTP port (default 3000). If taken, the next free port is used."," KNO_SQLITE_PATH SQLite file path, or :memory: for an ephemeral database"].join(`
102
+ `)):await Promise.resolve().then(()=>(Pd(),Zw));