@knoflows/engine 0.1.0-alpha.3 → 0.1.0-alpha.5

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 (45) hide show
  1. package/dist/engine.js +21 -11
  2. package/package.json +4 -3
  3. package/static/assets/i18n/en.json +36 -2
  4. package/static/assets/i18n/es.json +36 -2
  5. package/static/{chunk-C40TdCIk.js → chunk--cAlvNjP.js} +1 -1
  6. package/static/{chunk-CCjvFBCX.js → chunk-3tEYpnqu.js} +1 -1
  7. package/static/chunk-4TrlkpZx.js +1 -0
  8. package/static/chunk-99HzEG7y.js +1 -0
  9. package/static/{chunk-ZijlINsH.js → chunk-B4PXIvtd.js} +1 -1
  10. package/static/chunk-BEPCHPAV.js +1 -0
  11. package/static/{chunk-CeFjDLjY.js → chunk-BJ_zTxjo.js} +1 -1
  12. package/static/chunk-BaL0hYvK.js +1 -0
  13. package/static/{chunk-DK8z5vU5.js → chunk-BnjE7sDc.js} +1 -1
  14. package/static/{chunk-CSPhdKAb.js → chunk-BqWiMcNp.js} +1 -1
  15. package/static/{chunk-Cnkrtkdu.js → chunk-BvGpCrD9.js} +1 -1
  16. package/static/{chunk-BDOL5Qby.js → chunk-Byfh9OPw.js} +1 -1
  17. package/static/chunk-C5kOvUkS.js +1 -0
  18. package/static/chunk-C67ITweo.js +1 -0
  19. package/static/{chunk-Dw1tJgiv.js → chunk-CECejZs9.js} +1 -1
  20. package/static/{chunk-CPxI4OjB.js → chunk-CWRAmEOi.js} +1 -1
  21. package/static/{chunk-KyBZUWGU.js → chunk-Ca9rxJZS.js} +1 -1
  22. package/static/chunk-CbG3rfKf.js +66 -0
  23. package/static/chunk-Cdhqfnmn.js +1 -0
  24. package/static/chunk-Cgq1n6kP.js +1 -0
  25. package/static/chunk-CpxvtoPc.js +1 -0
  26. package/static/{chunk-Csk1w6sD.js → chunk-D6KYmz2w.js} +1 -1
  27. package/static/{chunk-DS9-TMN6.js → chunk-DGw7ID-A.js} +1 -1
  28. package/static/{chunk-C50zASMN.js → chunk-DS5k0b_s.js} +1 -1
  29. package/static/{chunk-DyP6QbgY.js → chunk-DZ8K8fY1.js} +1 -1
  30. package/static/{chunk-8DHqiag3.js → chunk-DrMwVUpq.js} +1 -1
  31. package/static/{chunk-DI-Ex2sC.js → chunk-VW6e_Kls.js} +1 -1
  32. package/static/{chunk-BJLDaNHl.js → chunk-jDfyi4_G.js} +1 -1
  33. package/static/chunk-qdbp1qcP.js +1 -0
  34. package/static/chunk-smuNKEab.js +5 -0
  35. package/static/index.html +1 -1
  36. package/static/main-5C7K2447.js +249 -0
  37. package/static/chunk-B4GVyu_H.js +0 -1
  38. package/static/chunk-B5hULR_G.js +0 -1
  39. package/static/chunk-BQYw1slv.js +0 -1
  40. package/static/chunk-BU5DKI8R.js +0 -1
  41. package/static/chunk-BquD19tF.js +0 -5
  42. package/static/chunk-C9CuVcTl.js +0 -1
  43. package/static/chunk-CgvdAwRh.js +0 -1
  44. package/static/chunk-DxRo8m4J.js +0 -66
  45. package/static/main-BK4MAPTK.js +0 -249
package/dist/engine.js CHANGED
@@ -1,17 +1,17 @@
1
1
  #!/usr/bin/env node
2
- var p=(o,t)=>()=>(o&&(t=o(o=0)),t);import{Controller as ws,Get as Ss}from"@nestjs/common";var kn,Ro,te,Nn=p(()=>{"use strict";kn=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},Ro=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},te=class{getHealth(){return{ok:!0,service:"kno-engine",timestamp:new Date().toISOString()}}};kn([Ss(),Ro("design:type",Function),Ro("design:paramtypes",[]),Ro("design:returntype",Object)],te.prototype,"getHealth",null);te=kn([ws("health")],te)});import{Module as js}from"@nestjs/common";var _s,_e,Cn=p(()=>{"use strict";_s=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},_e=class{};_e=_s([js({})],_e)});import{Module as xs}from"@nestjs/common";var Is,je,Dn=p(()=>{"use strict";Is=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},je=class{};je=Is([xs({})],je)});var Pt,Ie=p(()=>{"use strict";Pt=Symbol("TICKET_PROVIDER")});import{randomUUID as Es}from"node:crypto";function vs(o,t){return Object.entries(t).every(([e,n])=>o[e]===n)}var xe,$n=p(()=>{"use strict";xe=class{tickets;comments;constructor(t=[]){this.tickets=new Map(t.map(e=>[e.id,structuredClone(e)])),this.comments=new Map}async get(t){let e=this.tickets.get(t);if(!e)throw new Error(`Ticket not found: ${t}`);return structuredClone(e)}async query(t){return[...this.tickets.values()].filter(e=>vs(e,t)).map(e=>structuredClone(e))}async getComments(t){return await this.get(t),structuredClone(this.comments.get(t)??[])}async postComment(t,e){await this.get(t);let n=this.comments.get(t)??[];n.push({id:Es(),subjectId:t,body:e,createdAt:new Date().toISOString()}),this.comments.set(t,n)}async updateStatus(t,e){let n=this.tickets.get(t);if(!n)throw new Error(`Ticket not found: ${t}`);n.status=e}}});var At,Ee=p(()=>{"use strict";At=Symbol("REPO_PROVIDER")});import{randomUUID as Ts}from"node:crypto";function Os(o,t){return Object.entries(t).every(([e,n])=>e==="status"?o.raw?.status===n:o[e]===n)}var ve,qn=p(()=>{"use strict";ve=class{pullRequests;comments;constructor(t=[]){this.pullRequests=new Map(t.map(e=>[e.id,structuredClone(e)])),this.comments=new Map}async get(t){let e=this.pullRequests.get(t);if(!e)throw new Error(`Pull request not found: ${t}`);return structuredClone(e)}async query(t){return[...this.pullRequests.values()].filter(e=>Os(e,t)).map(e=>structuredClone(e))}async getComments(t){return await this.get(t),structuredClone(this.comments.get(t)??[])}async postComment(t,e){await this.get(t);let n=this.comments.get(t)??[];n.push({id:Ts(),subjectId:t,body:e,createdAt:new Date().toISOString()}),this.comments.set(t,n)}async updateStatus(t,e){let n=this.pullRequests.get(t);if(!n)throw new Error(`Pull request not found: ${t}`);n.raw={...n.raw??{},status:e}}}});var kt,Te=p(()=>{"use strict";kt=Symbol("DOCUMENTATION_PROVIDER")});import{randomUUID as Rs}from"node:crypto";var Ps,Oe,Ln=p(()=>{"use strict";Ps=new Set(["github_wiki","gitlab_wiki","azure_wiki","web"]),Oe=class{pages;contentById;comments;constructor(t=[]){this.pages=new Map,this.contentById=new Map,this.comments=new Map;for(let e of t){let{content:n,...i}=e;this.pages.set(i.id,structuredClone(i)),n!==void 0&&this.contentById.set(i.id,n)}}async get(t){let e=this.pages.get(t);if(!e)throw new Error(`Documentation page not found: ${t}`);return structuredClone(e)}async getContent(t){await this.get(t);let e=this.contentById.get(t);if(e===void 0)throw new Error(`Documentation content not found: ${t}`);return e}async query(t){let e=t.pageIds;if(!Array.isArray(e))throw new Error("Documentation query requires { pageIds: string[] }");let n=[];for(let i of e)n.push(await this.get(String(i)));return n}async getComments(t){let e=await this.get(t);return this.assertCommentsSupported(e),structuredClone(this.comments.get(t)??[])}async postComment(t,e){let n=await this.get(t);this.assertCommentsSupported(n);let i=this.comments.get(t)??[];i.push({id:Rs(),subjectId:t,body:e,createdAt:new Date().toISOString()}),this.comments.set(t,i)}assertCommentsSupported(t){if(Ps.has(t.source))throw new Error(`Comments are not supported for documentation source '${t.source}'`)}}});var ee,Po=p(()=>{"use strict";ee=Symbol("AGENT_PROVIDER")});import{createCipheriv as As,createDecipheriv as ks,randomBytes as Bn}from"node:crypto";import{mkdir as Jn,readFile as Fn,writeFile as Un}from"node:fs/promises";import{join as ko}from"node:path";function ct(o){return`kno.${o}.apiKey`}function $s(o){return ko(o,"secrets")}function Vn(o){return new No($s(o.dataDir),o.keyring)}function qs(o){try{return o(Re,"__kno_probe__").getPassword(),!0}catch(t){return Co(t)}}function Co(o){let t=o instanceof Error?o.message:String(o);return/noentry|no matching entry|not found|no such/i.test(t)}var Re,Mn,Ns,Ao,Cs,Ds,No,H,yt=p(()=>{"use strict";Re="kno-flows";Mn="aes-256-gcm",Ns=12,Ao=32,Cs="master.key",Ds="store.json",No=class{secretsDir;keyring;keyringResolved=!1;masterKey=null;constructor(t,e){this.secretsDir=t,this.keyring=e,e!==void 0&&(this.keyringResolved=!0)}async get(t){let e=await this.resolveKeyring();if(e)try{let n=e(Re,t).getPassword();if(n!=null)return n}catch(n){Co(n)||this.disableKeyring()}return this.fileGet(t)}async set(t,e){let n=await this.resolveKeyring();if(n)try{n(Re,t).setPassword(e),await this.fileDelete(t);return}catch{this.disableKeyring()}await this.fileSet(t,e)}async delete(t){let e=await this.resolveKeyring();if(e)try{e(Re,t).deletePassword()}catch(n){Co(n)||this.disableKeyring()}await this.fileDelete(t)}disableKeyring(){this.keyring=null,this.keyringResolved=!0}async resolveKeyring(){if(this.keyringResolved)return this.keyring??null;this.keyringResolved=!0;try{let{Entry:t}=await import("@napi-rs/keyring"),e=(n,i)=>new t(n,i);return qs(e)?(this.keyring=e,e):(this.keyring=null,null)}catch{return this.keyring=null,null}}async fileGet(t){let n=(await this.readStore())[t];return n?this.decrypt(n):null}async fileSet(t,e){let n=await this.readStore();n[t]=await this.encrypt(e),await this.writeStore(n)}async fileDelete(t){let e=await this.readStore();t in e&&(delete e[t],await this.writeStore(e))}async readStore(){try{let t=await Fn(this.storePath(),"utf8"),e=JSON.parse(t);if(e==null||typeof e!="object"||Array.isArray(e))throw new Error(`Corrupt secret store at ${this.storePath()}`);return e}catch(t){if(t.code==="ENOENT")return{};throw t}}async writeStore(t){await Jn(this.secretsDir,{recursive:!0}),await Un(this.storePath(),JSON.stringify(t,null,2),{encoding:"utf8",mode:384})}async encrypt(t){let e=await this.loadOrCreateMasterKey(),n=Bn(Ns),i=As(Mn,e,n),r=Buffer.concat([i.update(t,"utf8"),i.final()]);return{iv:n.toString("base64"),tag:i.getAuthTag().toString("base64"),ciphertext:r.toString("base64")}}async decrypt(t){let e=await this.loadOrCreateMasterKey(),n=ks(Mn,e,Buffer.from(t.iv,"base64"));return n.setAuthTag(Buffer.from(t.tag,"base64")),Buffer.concat([n.update(Buffer.from(t.ciphertext,"base64")),n.final()]).toString("utf8")}async loadOrCreateMasterKey(){if(this.masterKey)return this.masterKey;await Jn(this.secretsDir,{recursive:!0});let t=this.masterKeyPath();try{let n=(await Fn(t,"utf8")).trim(),i=Buffer.from(n,"hex");if(i.length!==Ao)throw new Error(`Secret store master key at ${t} is not ${Ao} bytes`);return this.masterKey=i,i}catch(n){if(n.code!=="ENOENT")throw n}let e=Bn(Ao);return await Un(t,e.toString("hex"),{encoding:"utf8",mode:384}),this.masterKey=e,e}storePath(){return ko(this.secretsDir,Ds)}masterKeyPath(){return ko(this.secretsDir,Cs)}};H=Symbol("SECRET_STORE")});function Pe(o){let t=ct(o),e=Fs[o]??o;return new Error(`${e} API key not configured \u2014 set '${t}' via the setup script`)}function Kn(o){let t=new Map;for(let n of o){let i=n.content.trim();if(!i)continue;let r=t.get(n.tier)??[];r.push(i),t.set(n.tier,r)}let e=[];for(let n of Bs){let i=t.get(n);i?.length&&e.push(`## ${Ls[n]}
2
+ var p=(o,t)=>()=>(o&&(t=o(o=0)),t);import{Controller as Ea,Get as va}from"@nestjs/common";var fn,Zo,fe,mn=p(()=>{"use strict";fn=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},Zo=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},fe=class{getHealth(){return{ok:!0,service:"kno-engine",timestamp:new Date().toISOString()}}};fn([va(),Zo("design:type",Function),Zo("design:paramtypes",[]),Zo("design:returntype",Object)],fe.prototype,"getHealth",null);fe=fn([Ea("health")],fe)});import{Module as Ra}from"@nestjs/common";var Ta,Ce,hn=p(()=>{"use strict";Ta=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},Ce=class{};Ce=Ta([Ra({})],Ce)});import{Module as Pa}from"@nestjs/common";var Oa,De,bn=p(()=>{"use strict";Oa=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},De=class{};De=Oa([Pa({})],De)});var Ut,Be=p(()=>{"use strict";Ut=Symbol("TICKET_PROVIDER")});import{randomUUID as ka}from"node:crypto";function Aa(o,t){return Object.entries(t).every(([e,r])=>o[e]===r)}var $e,wn=p(()=>{"use strict";$e=class{tickets;comments;constructor(t=[]){this.tickets=new Map(t.map(e=>[e.id,structuredClone(e)])),this.comments=new Map}async get(t){let e=this.tickets.get(t);if(!e)throw new Error(`Ticket not found: ${t}`);return structuredClone(e)}async query(t){return[...this.tickets.values()].filter(e=>Aa(e,t)).map(e=>structuredClone(e))}async getComments(t){return await this.get(t),structuredClone(this.comments.get(t)??[])}async postComment(t,e){await this.get(t);let r=this.comments.get(t)??[];r.push({id:ka(),subjectId:t,body:e,createdAt:new Date().toISOString()}),this.comments.set(t,r)}async updateStatus(t,e){let r=this.tickets.get(t);if(!r)throw new Error(`Ticket not found: ${t}`);r.status=e}}});var Ft,Le=p(()=>{"use strict";Ft=Symbol("REPO_PROVIDER")});import{randomUUID as Na}from"node:crypto";function qa(o,t){return Object.entries(t).every(([e,r])=>e==="status"?o.raw?.status===r:o[e]===r)}var Ue,yn=p(()=>{"use strict";Ue=class{pullRequests;comments;constructor(t=[]){this.pullRequests=new Map(t.map(e=>[e.id,structuredClone(e)])),this.comments=new Map}async get(t){let e=this.pullRequests.get(t);if(!e)throw new Error(`Pull request not found: ${t}`);return structuredClone(e)}async query(t){return[...this.pullRequests.values()].filter(e=>qa(e,t)).map(e=>structuredClone(e))}async getComments(t){return await this.get(t),structuredClone(this.comments.get(t)??[])}async postComment(t,e){await this.get(t);let r=this.comments.get(t)??[];r.push({id:Na(),subjectId:t,body:e,createdAt:new Date().toISOString()}),this.comments.set(t,r)}async updateStatus(t,e){let r=this.pullRequests.get(t);if(!r)throw new Error(`Pull request not found: ${t}`);r.raw={...r.raw??{},status:e}}}});var Jt,Fe=p(()=>{"use strict";Jt=Symbol("DOCUMENTATION_PROVIDER")});import{randomUUID as Ca}from"node:crypto";var Da,Je,gn=p(()=>{"use strict";Da=new Set(["github_wiki","gitlab_wiki","azure_wiki","web"]),Je=class{pages;contentById;comments;constructor(t=[]){this.pages=new Map,this.contentById=new Map,this.comments=new Map;for(let e of t){let{content:r,...i}=e;this.pages.set(i.id,structuredClone(i)),r!==void 0&&this.contentById.set(i.id,r)}}async get(t){let e=this.pages.get(t);if(!e)throw new Error(`Documentation page not found: ${t}`);return structuredClone(e)}async getContent(t){await this.get(t);let e=this.contentById.get(t);if(e===void 0)throw new Error(`Documentation content not found: ${t}`);return e}async query(t){let e=t.pageIds;if(!Array.isArray(e))throw new Error("Documentation query requires { pageIds: string[] }");let r=[];for(let i of e)r.push(await this.get(String(i)));return r}async getComments(t){let e=await this.get(t);return this.assertCommentsSupported(e),structuredClone(this.comments.get(t)??[])}async postComment(t,e){let r=await this.get(t);this.assertCommentsSupported(r);let i=this.comments.get(t)??[];i.push({id:Ca(),subjectId:t,body:e,createdAt:new Date().toISOString()}),this.comments.set(t,i)}assertCommentsSupported(t){if(Da.has(t.source))throw new Error(`Comments are not supported for documentation source '${t.source}'`)}}});var me,tr=p(()=>{"use strict";me=Symbol("AGENT_PROVIDER")});import{createCipheriv as Ba,createDecipheriv as $a,randomBytes as Sn}from"node:crypto";import{mkdir as jn,readFile as _n,writeFile as In}from"node:fs/promises";import{join as or}from"node:path";function St(o){return`kno.${o}.apiKey`}function Ja(o){return or(o,"secrets")}function En(o){return new rr(Ja(o.dataDir),o.keyring)}function Ma(o){try{return o(Me,"__kno_probe__").getPassword(),!0}catch(t){return nr(t)}}function nr(o){let t=o instanceof Error?o.message:String(o);return/noentry|no matching entry|not found|no such/i.test(t)}var Me,xn,La,er,Ua,Fa,rr,ot,Tt=p(()=>{"use strict";Me="kno-flows";xn="aes-256-gcm",La=12,er=32,Ua="master.key",Fa="store.json",rr=class{secretsDir;keyring;keyringResolved=!1;masterKey=null;constructor(t,e){this.secretsDir=t,this.keyring=e,e!==void 0&&(this.keyringResolved=!0)}async get(t){let e=await this.resolveKeyring();if(e)try{let r=e(Me,t).getPassword();if(r!=null)return r}catch(r){nr(r)||this.disableKeyring()}return this.fileGet(t)}async set(t,e){let r=await this.resolveKeyring();if(r)try{r(Me,t).setPassword(e),await this.fileDelete(t);return}catch{this.disableKeyring()}await this.fileSet(t,e)}async delete(t){let e=await this.resolveKeyring();if(e)try{e(Me,t).deletePassword()}catch(r){nr(r)||this.disableKeyring()}await this.fileDelete(t)}disableKeyring(){this.keyring=null,this.keyringResolved=!0}async resolveKeyring(){if(this.keyringResolved)return this.keyring??null;this.keyringResolved=!0;try{let{Entry:t}=await import("@napi-rs/keyring"),e=(r,i)=>new t(r,i);return Ma(e)?(this.keyring=e,e):(this.keyring=null,null)}catch{return this.keyring=null,null}}async fileGet(t){let r=(await this.readStore())[t];return r?this.decrypt(r):null}async fileSet(t,e){let r=await this.readStore();r[t]=await this.encrypt(e),await this.writeStore(r)}async fileDelete(t){let e=await this.readStore();t in e&&(delete e[t],await this.writeStore(e))}async readStore(){try{let t=await _n(this.storePath(),"utf8"),e=JSON.parse(t);if(e==null||typeof e!="object"||Array.isArray(e))throw new Error(`Corrupt secret store at ${this.storePath()}`);return e}catch(t){if(t.code==="ENOENT")return{};throw t}}async writeStore(t){await jn(this.secretsDir,{recursive:!0}),await In(this.storePath(),JSON.stringify(t,null,2),{encoding:"utf8",mode:384})}async encrypt(t){let e=await this.loadOrCreateMasterKey(),r=Sn(La),i=Ba(xn,e,r),n=Buffer.concat([i.update(t,"utf8"),i.final()]);return{iv:r.toString("base64"),tag:i.getAuthTag().toString("base64"),ciphertext:n.toString("base64")}}async decrypt(t){let e=await this.loadOrCreateMasterKey(),r=$a(xn,e,Buffer.from(t.iv,"base64"));return r.setAuthTag(Buffer.from(t.tag,"base64")),Buffer.concat([r.update(Buffer.from(t.ciphertext,"base64")),r.final()]).toString("utf8")}async loadOrCreateMasterKey(){if(this.masterKey)return this.masterKey;await jn(this.secretsDir,{recursive:!0});let t=this.masterKeyPath();try{let r=(await _n(t,"utf8")).trim(),i=Buffer.from(r,"hex");if(i.length!==er)throw new Error(`Secret store master key at ${t} is not ${er} bytes`);return this.masterKey=i,i}catch(r){if(r.code!=="ENOENT")throw r}let e=Sn(er);return await In(t,e.toString("hex"),{encoding:"utf8",mode:384}),this.masterKey=e,e}storePath(){return or(this.secretsDir,Fa)}masterKeyPath(){return or(this.secretsDir,Ua)}};ot=Symbol("SECRET_STORE")});function Ve(o){let t=St(o),e=Ka[o]??o;return new Error(`${e} API key not configured \u2014 set '${t}' via the setup script`)}function vn(o){let t=new Map;for(let r of o){let i=r.content.trim();if(!i)continue;let n=t.get(r.tier)??[];n.push(i),t.set(r.tier,n)}let e=[];for(let r of Wa){let i=t.get(r);i?.length&&e.push(`## ${Va[r]}
3
3
  ${i.join(`
4
4
 
5
5
  `)}`)}return e.join(`
6
6
 
7
- `)}function oe(o){let t=[],e=Kn(o.knowledge);return e&&t.push(e),t.push(`# Objective
7
+ `)}function he(o){let t=[],e=vn(o.knowledge);return e&&t.push(e),t.push(`# Objective
8
8
  ${o.objective}`),t.push(`# Output format
9
- ${Js[o.outputFormat]}`),t.join(`
9
+ ${Xa[o.outputFormat]}`),t.join(`
10
10
 
11
- `)}function ne(o,t){return t==="free_text"?o:Xn(o)}function Xn(o){let t=[...o.matchAll(/```json\s*([\s\S]*?)```/gi)].map(i=>i[1].trim()),e=[...o.matchAll(/```\s*([\s\S]*?)```/g)].map(i=>i[1].trim()),n=[...t].reverse();n.length===0&&n.push(...[...e].reverse()),n.push(o.trim());for(let i of n)if(i)try{return JSON.parse(i)}catch{continue}throw new Error("No valid JSON block found in agent response")}var Ls,Bs,Js,Fs,Ae=p(()=>{"use strict";yt();Ls={user:"User preferences",organization:"Organization guidelines",project:"Project context"},Bs=["user","organization","project"],Js={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."},Fs={anthropic:"Anthropic",cursor:"Cursor"}});async function*Ms(o){let{query:t}=await import("@anthropic-ai/claude-agent-sdk"),e=o.options;yield*t({prompt:o.prompt,options:{permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,...e?.cwd?{cwd:e.cwd}:{},...e?.resume?{resume:e.resume}:{},...e?.env?{env:e.env}:{}}})}var Us,ke,Hn=p(()=>{"use strict";Ae();yt();Ae();Us=ct("anthropic"),ke=class{secrets;queryFn;constructor(t,e){this.secrets=t,this.queryFn=e}async run(t){let e=await this.requireApiKey(),n=oe(t),i={permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,env:{...process.env,ANTHROPIC_API_KEY:e}};t.cwd&&(i.cwd=t.cwd),t.sessionId&&(i.resume=t.sessionId);let r=this.queryFn??Ms,s,a,u;for await(let c of r({prompt:n,options:i}))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:ne(a,t.outputFormat),sessionId:s}}async requireApiKey(){let t=await this.secrets.get(Us);if(!t)throw Pe("anthropic");return t}}});function Ks(o,t){return{apiKey:o,model:{id:"composer-2.5"},local:{...t?{cwd:t}:{},settingSources:[]}}}async function Xs(){let{Agent:o}=await import("@cursor/sdk");return{create:t=>o.create({apiKey:t.apiKey,model:t.model,local:{...t.local?.cwd?{cwd:t.local.cwd}:{},settingSources:[]}}),resume:(t,e)=>o.resume(t,{apiKey:e.apiKey,model:e.model,local:{...e.local?.cwd?{cwd:e.local.cwd}:{},settingSources:[]}})}}var Vs,Ne,Wn=p(()=>{"use strict";Ae();yt();Vs=ct("cursor"),Ne=class{secrets;sdk;constructor(t,e){this.secrets=t,this.sdk=e}async run(t){let e=await this.requireApiKey(),n=oe(t),i=this.sdk??await Xs(),r=Ks(e,t.cwd),s=t.sessionId?await i.resume(t.sessionId,r):await i.create(r);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:ne(c,t.outputFormat),sessionId:s.agentId}}finally{await s[Symbol.asyncDispose]?.()}}async requireApiKey(){let t=await this.secrets.get(Vs);if(!t)throw Pe("cursor");return t}}});var re,Do=p(()=>{"use strict";re=Symbol("NOTIFICATION_PROVIDER")});var Ce,Gn=p(()=>{"use strict";Ce=class{async send(t){console.log("[notification]",JSON.stringify(t))}}});var ie,$o=p(()=>{"use strict";ie=Symbol("KNOWLEDGE_PROVIDER")});import{readdir as Hs,readFile as Ws}from"node:fs/promises";import{join as zn}from"node:path";var De,Yn=p(()=>{"use strict";De=class{baseDir;constructor(t){this.baseDir=t}async resolve(t,e){let n=zn(this.baseDir,t),i;try{i=await Hs(n)}catch(a){if(a.code==="ENOENT")return[];throw a}let r=i.filter(a=>a.endsWith(".md")).sort(),s=[];for(let a of r){let u=zn(n,a),c=await Ws(u,"utf8");s.push({tier:t,content:c,sourceRef:u})}return s}}});import{Module as zs}from"@nestjs/common";import{mkdirSync as Ys}from"node:fs";import{dirname as Qs,join as Zs}from"node:path";import{fileURLToPath as ta}from"node:url";var Gs,Qn,Bt,qo=p(()=>{"use strict";yt();Gs=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},Qn=Zs(Qs(ta(import.meta.url)),"../../data");Ys(Qn,{recursive:!0});Bt=class{};Bt=Gs([zs({providers:[{provide:H,useFactory:()=>Vn({dataDir:Qn})}],exports:[H]})],Bt)});import{index as ea,sqliteTable as oa,text as tt}from"drizzle-orm/sqlite-core";var et,$e=p(()=>{"use strict";et=oa("workflow_definitions",{id:tt("id").primaryKey(),name:tt("name").notNull(),description:tt("description"),appliesTo:tt("applies_to",{mode:"json"}).$type().notNull(),cardinality:tt("cardinality",{enum:["single","batch","aggregate"]}).notNull(),inputSchema:tt("input_schema",{mode:"json"}).$type().notNull(),steps:tt("steps",{mode:"json"}).$type().notNull(),notificationPolicy:tt("notification_policy",{mode:"json"}).$type().notNull(),createdAt:tt("created_at").notNull(),updatedAt:tt("updated_at").notNull()},o=>[ea("workflow_definitions_cardinality_idx").on(o.cardinality)])});import{index as Zn,integer as na,sqliteTable as ra,text as se}from"drizzle-orm/sqlite-core";var ot,Lo=p(()=>{"use strict";ot=ra("subject_views",{id:se("id").primaryKey(),name:se("name").notNull(),subjectType:se("subject_type").$type().notNull(),query:se("query",{mode:"json"}).$type().notNull(),description:se("description"),order:na("order").notNull().default(0)},o=>[Zn("subject_views_subject_type_idx").on(o.subjectType),Zn("subject_views_subject_type_order_idx").on(o.subjectType,o.order)])});import{index as tr,integer as ia,sqliteTable as sa,text as nt}from"drizzle-orm/sqlite-core";var wt,qe=p(()=>{"use strict";wt=sa("job_batches",{id:nt("id").primaryKey(),workflowId:nt("workflow_id").notNull(),selection:nt("selection",{mode:"json"}).$type().notNull(),resolvedSubjects:nt("resolved_subjects",{mode:"json"}).$type().notNull(),status:nt("status",{enum:["running","completed","completed_with_issues","failed"]}).notNull(),triggeredBy:nt("triggered_by",{enum:["schedule","view_bulk","multiselect"]}).notNull(),scheduleId:nt("schedule_id"),notificationOverride:nt("notification_override",{mode:"json"}).$type(),notificationSent:ia("notification_sent",{mode:"boolean"}).notNull(),createdAt:nt("created_at").notNull(),completedAt:nt("completed_at")},o=>[tr("job_batches_workflow_id_idx").on(o.workflowId),tr("job_batches_schedule_id_idx").on(o.scheduleId)])});import{index as Le,integer as aa,sqliteTable as ca,text as v}from"drizzle-orm/sqlite-core";var rt,ae=p(()=>{"use strict";$e();qe();rt=ca("jobs",{id:v("id").primaryKey(),workflowId:v("workflow_id").notNull().references(()=>et.id),status:v("status").$type().notNull(),selection:v("selection",{mode:"json"}).$type(),batchId:v("batch_id").references(()=>wt.id),parentJobId:v("parent_job_id"),parentStepExecutionId:v("parent_step_execution_id"),fanOutIndex:aa("fan_out_index"),retryOf:v("retry_of"),context:v("context",{mode:"json"}).$type().notNull(),worktreePath:v("worktree_path"),branch:v("branch"),currentStepId:v("current_step_id"),currentStepExecutionId:v("current_step_execution_id"),createdAt:v("created_at").notNull(),updatedAt:v("updated_at").notNull(),completedAt:v("completed_at")},o=>[Le("jobs_workflow_id_idx").on(o.workflowId),Le("jobs_status_idx").on(o.status),Le("jobs_batch_id_idx").on(o.batchId),Le("jobs_parent_job_id_idx").on(o.parentJobId)])});import{index as er,sqliteTable as ua,text as ce}from"drizzle-orm/sqlite-core";var Jt,Bo=p(()=>{"use strict";ae();Jt=ua("job_subjects",{id:ce("id").primaryKey(),jobId:ce("job_id").notNull().references(()=>rt.id),subjectType:ce("subject_type").$type().notNull(),subjectId:ce("subject_id").notNull(),snapshot:ce("snapshot",{mode:"json"}).$type().notNull()},o=>[er("job_subjects_job_id_idx").on(o.jobId),er("job_subjects_subject_lookup_idx").on(o.subjectType,o.subjectId)])});import{index as or,integer as da,sqliteTable as pa,text as W}from"drizzle-orm/sqlite-core";var Nt,Jo=p(()=>{"use strict";ae();Nt=pa("job_step_executions",{id:W("id").primaryKey(),jobId:W("job_id").notNull().references(()=>rt.id),stepDefinitionId:W("step_definition_id").notNull(),type:W("type").$type().notNull(),status:W("status").$type().notNull(),startedAt:W("started_at"),completedAt:W("completed_at"),output:W("output",{mode:"json"}).$type(),error:W("error"),childJobIds:W("child_job_ids",{mode:"json"}).$type(),parentStepExecutionId:W("parent_step_execution_id").references(()=>Nt.id),iterationIndex:da("iteration_index")},o=>[or("job_step_executions_job_id_idx").on(o.jobId),or("job_step_executions_parent_idx").on(o.parentStepExecutionId)])});import{index as la,integer as fa,sqliteTable as ma,text as ut}from"drizzle-orm/sqlite-core";var St,Fo=p(()=>{"use strict";St=ma("schedules",{id:ut("id").primaryKey(),workflowId:ut("workflow_id").notNull(),viewId:ut("view_id").notNull(),triggerType:ut("trigger_type",{enum:["cron"]}).notNull(),cadence:ut("cadence").notNull(),notificationOverride:ut("notification_override",{mode:"json"}).$type(),missedFirePolicy:ut("missed_fire_policy",{enum:["skip","catch_up"]}).notNull(),enabled:fa("enabled",{mode:"boolean"}).notNull(),lastFiredAt:ut("last_fired_at"),createdAt:ut("created_at").notNull()},o=>[la("schedules_enabled_idx").on(o.enabled)])});import{sqliteTable as ha,text as nr}from"drizzle-orm/sqlite-core";var ue,Ft,Uo=p(()=>{"use strict";ue="default",Ft=ha("settings",{id:nr("id").primaryKey(),data:nr("data",{mode:"json"}).$type().notNull()})});import{defineRelations as ba}from"drizzle-orm";var ga,rr,ir=p(()=>{"use strict";$e();Lo();ae();Bo();Jo();qe();Fo();Uo();ga={workflowDefinitions:et,subjectViews:ot,jobs:rt,jobSubjects:Jt,jobStepExecutions:Nt,jobBatches:wt,schedules:St,settings:Ft},rr=ba(ga,o=>({workflowDefinitions:{},subjectViews:{},schedules:{},settings:{},jobs:{subjects:o.many.jobSubjects({from:o.jobs.id,to:o.jobSubjects.jobId}),stepExecutions:o.many.jobStepExecutions({from:o.jobs.id,to:o.jobStepExecutions.jobId}),batch:o.one.jobBatches({from:o.jobs.batchId,to:o.jobBatches.id})},jobSubjects:{job:o.one.jobs({from:o.jobSubjects.jobId,to:o.jobs.id})},jobStepExecutions:{job:o.one.jobs({from:o.jobStepExecutions.jobId,to:o.jobs.id}),parent:o.one.jobStepExecutions({from:o.jobStepExecutions.parentStepExecutionId,to:o.jobStepExecutions.id,alias:"job_step_executions_parent"}),children:o.many.jobStepExecutions({from:o.jobStepExecutions.id,to:o.jobStepExecutions.parentStepExecutionId,alias:"job_step_executions_children"})},jobBatches:{jobs:o.many.jobs({from:o.jobBatches.id,to:o.jobs.batchId})}}))});import{drizzle as ya}from"drizzle-orm/node-sqlite";import{DatabaseSync as Ol}from"node:sqlite";function sr(o){return o.exec("PRAGMA foreign_keys = ON;"),ya({client:o,relations:rr})}var ar=p(()=>{"use strict";ir()});function wa(o,t,e){return o.prepare(`PRAGMA table_info(${t})`).all().some(i=>i.name===e)}function Sa(o){wa(o,"subject_views","order")||o.exec('ALTER TABLE subject_views ADD COLUMN "order" INTEGER NOT NULL DEFAULT 0'),o.exec(`
11
+ `)}function be(o,t){return t==="free_text"?o:Tn(o)}function Tn(o){let t=[...o.matchAll(/```json\s*([\s\S]*?)```/gi)].map(i=>i[1].trim()),e=[...o.matchAll(/```\s*([\s\S]*?)```/g)].map(i=>i[1].trim()),r=[...t].reverse();r.length===0&&r.push(...[...e].reverse()),r.push(o.trim());for(let i of r)if(i)try{return JSON.parse(i)}catch{continue}throw new Error("No valid JSON block found in agent response")}var Va,Wa,Xa,Ka,We=p(()=>{"use strict";Tt();Va={user:"User preferences",organization:"Organization guidelines",project:"Project context"},Wa=["user","organization","project"],Xa={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."},Ka={anthropic:"Anthropic",cursor:"Cursor"}});async function*Ga(o){let{query:t}=await import("@anthropic-ai/claude-agent-sdk"),e=o.options;yield*t({prompt:o.prompt,options:{permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,...e?.cwd?{cwd:e.cwd}:{},...e?.resume?{resume:e.resume}:{},...e?.env?{env:e.env}:{}}})}var Ha,Xe,Rn=p(()=>{"use strict";We();Tt();We();Ha=St("anthropic"),Xe=class{secrets;queryFn;constructor(t,e){this.secrets=t,this.queryFn=e}async run(t){let e=await this.requireApiKey(),r=he(t),i={permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,env:{...process.env,ANTHROPIC_API_KEY:e}};t.cwd&&(i.cwd=t.cwd),t.sessionId&&(i.resume=t.sessionId);let n=this.queryFn??Ga,s,a,u;for await(let c of n({prompt:r,options:i}))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:be(a,t.outputFormat),sessionId:s}}async requireApiKey(){let t=await this.secrets.get(Ha);if(!t)throw Ve("anthropic");return t}}});function Qa(o,t){return{apiKey:o,model:{id:"composer-2.5"},local:{...t?{cwd:t}:{},settingSources:[]}}}async function Ya(){let{Agent:o}=await import("@cursor/sdk");return{create:t=>o.create({apiKey:t.apiKey,model:t.model,local:{...t.local?.cwd?{cwd:t.local.cwd}:{},settingSources:[]}}),resume:(t,e)=>o.resume(t,{apiKey:e.apiKey,model:e.model,local:{...e.local?.cwd?{cwd:e.local.cwd}:{},settingSources:[]}})}}var za,Ke,On=p(()=>{"use strict";We();Tt();za=St("cursor"),Ke=class{secrets;sdk;constructor(t,e){this.secrets=t,this.sdk=e}async run(t){let e=await this.requireApiKey(),r=he(t),i=this.sdk??await Ya(),n=Qa(e,t.cwd),s=t.sessionId?await i.resume(t.sessionId,n):await i.create(n);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:be(c,t.outputFormat),sessionId:s.agentId}}finally{await s[Symbol.asyncDispose]?.()}}async requireApiKey(){let t=await this.secrets.get(za);if(!t)throw Ve("cursor");return t}}});var we,ir=p(()=>{"use strict";we=Symbol("NOTIFICATION_PROVIDER")});var He,Pn=p(()=>{"use strict";He=class{async send(t){console.log("[notification]",JSON.stringify(t))}}});var ye,sr=p(()=>{"use strict";ye=Symbol("KNOWLEDGE_PROVIDER")});import{readdir as Za,readFile as tc}from"node:fs/promises";import{join as kn}from"node:path";var Ge,An=p(()=>{"use strict";Ge=class{baseDir;constructor(t){this.baseDir=t}async resolve(t,e){let r=kn(this.baseDir,t),i;try{i=await Za(r)}catch(a){if(a.code==="ENOENT")return[];throw a}let n=i.filter(a=>a.endsWith(".md")).sort(),s=[];for(let a of n){let u=kn(r,a),c=await tc(u,"utf8");s.push({tier:t,content:c,sourceRef:u})}return s}}});import{Module as oc}from"@nestjs/common";import{mkdirSync as rc}from"node:fs";import{dirname as nc,join as ic}from"node:path";import{fileURLToPath as sc}from"node:url";var ec,Nn,Zt,ar=p(()=>{"use strict";Tt();ec=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},Nn=ic(nc(sc(import.meta.url)),"../../data");rc(Nn,{recursive:!0});Zt=class{};Zt=ec([oc({providers:[{provide:ot,useFactory:()=>En({dataDir:Nn})}],exports:[ot]})],Zt)});import{index as ac,sqliteTable as cc,text as at}from"drizzle-orm/sqlite-core";var ct,ze=p(()=>{"use strict";ct=cc("workflow_definitions",{id:at("id").primaryKey(),name:at("name").notNull(),description:at("description"),appliesTo:at("applies_to",{mode:"json"}).$type().notNull(),cardinality:at("cardinality",{enum:["single","batch","aggregate"]}).notNull(),inputSchema:at("input_schema",{mode:"json"}).$type().notNull(),steps:at("steps",{mode:"json"}).$type().notNull(),notificationPolicy:at("notification_policy",{mode:"json"}).$type().notNull(),createdAt:at("created_at").notNull(),updatedAt:at("updated_at").notNull()},o=>[ac("workflow_definitions_cardinality_idx").on(o.cardinality)])});import{index as qn,integer as uc,sqliteTable as lc,text as Mt}from"drizzle-orm/sqlite-core";var ut,cr=p(()=>{"use strict";ut=lc("subject_views",{id:Mt("id").primaryKey(),name:Mt("name").notNull(),subjectType:Mt("subject_type").$type().notNull(),workflowId:Mt("workflow_id").notNull(),query:Mt("query",{mode:"json"}).$type().notNull(),description:Mt("description"),queryTemplate:Mt("query_template",{mode:"json"}).$type(),order:uc("order").notNull().default(0)},o=>[qn("subject_views_subject_type_idx").on(o.subjectType),qn("subject_views_subject_type_order_idx").on(o.subjectType,o.order)])});import{index as Cn,integer as pc,sqliteTable as dc,text as lt}from"drizzle-orm/sqlite-core";var Rt,Qe=p(()=>{"use strict";Rt=dc("job_batches",{id:lt("id").primaryKey(),workflowId:lt("workflow_id").notNull(),selection:lt("selection",{mode:"json"}).$type().notNull(),resolvedSubjects:lt("resolved_subjects",{mode:"json"}).$type().notNull(),status:lt("status",{enum:["running","completed","completed_with_issues","failed"]}).notNull(),triggeredBy:lt("triggered_by",{enum:["schedule","view_bulk","multiselect"]}).notNull(),scheduleId:lt("schedule_id"),notificationOverride:lt("notification_override",{mode:"json"}).$type(),notificationSent:pc("notification_sent",{mode:"boolean"}).notNull(),createdAt:lt("created_at").notNull(),completedAt:lt("completed_at")},o=>[Cn("job_batches_workflow_id_idx").on(o.workflowId),Cn("job_batches_schedule_id_idx").on(o.scheduleId)])});import{index as Ye,integer as fc,sqliteTable as mc,text as A}from"drizzle-orm/sqlite-core";var N,ge=p(()=>{"use strict";ze();Qe();N=mc("jobs",{id:A("id").primaryKey(),workflowId:A("workflow_id").notNull().references(()=>ct.id),status:A("status").$type().notNull(),selection:A("selection",{mode:"json"}).$type(),batchId:A("batch_id").references(()=>Rt.id),parentJobId:A("parent_job_id"),parentStepExecutionId:A("parent_step_execution_id"),fanOutIndex:fc("fan_out_index"),retryOf:A("retry_of"),context:A("context",{mode:"json"}).$type().notNull(),worktreePath:A("worktree_path"),branch:A("branch"),currentStepId:A("current_step_id"),currentStepExecutionId:A("current_step_execution_id"),createdAt:A("created_at").notNull(),updatedAt:A("updated_at").notNull(),completedAt:A("completed_at")},o=>[Ye("jobs_workflow_id_idx").on(o.workflowId),Ye("jobs_status_idx").on(o.status),Ye("jobs_batch_id_idx").on(o.batchId),Ye("jobs_parent_job_id_idx").on(o.parentJobId)])});import{index as Dn,sqliteTable as hc,text as Se}from"drizzle-orm/sqlite-core";var pt,ur=p(()=>{"use strict";ge();pt=hc("job_subjects",{id:Se("id").primaryKey(),jobId:Se("job_id").notNull().references(()=>N.id),subjectType:Se("subject_type").$type().notNull(),subjectId:Se("subject_id").notNull(),snapshot:Se("snapshot",{mode:"json"}).$type().notNull()},o=>[Dn("job_subjects_job_id_idx").on(o.jobId),Dn("job_subjects_subject_lookup_idx").on(o.subjectType,o.subjectId)])});import{index as Bn,integer as bc,sqliteTable as wc,text as rt}from"drizzle-orm/sqlite-core";var Vt,lr=p(()=>{"use strict";ge();Vt=wc("job_step_executions",{id:rt("id").primaryKey(),jobId:rt("job_id").notNull().references(()=>N.id),stepDefinitionId:rt("step_definition_id").notNull(),type:rt("type").$type().notNull(),status:rt("status").$type().notNull(),startedAt:rt("started_at"),completedAt:rt("completed_at"),output:rt("output",{mode:"json"}).$type(),error:rt("error"),childJobIds:rt("child_job_ids",{mode:"json"}).$type(),parentStepExecutionId:rt("parent_step_execution_id").references(()=>Vt.id),iterationIndex:bc("iteration_index")},o=>[Bn("job_step_executions_job_id_idx").on(o.jobId),Bn("job_step_executions_parent_idx").on(o.parentStepExecutionId)])});import{index as yc,integer as gc,sqliteTable as Sc,text as Ot}from"drizzle-orm/sqlite-core";var Pt,pr=p(()=>{"use strict";Pt=Sc("schedules",{id:Ot("id").primaryKey(),viewId:Ot("view_id").notNull(),triggerType:Ot("trigger_type",{enum:["cron"]}).notNull(),cadence:Ot("cadence").notNull(),notificationOverride:Ot("notification_override",{mode:"json"}).$type(),missedFirePolicy:Ot("missed_fire_policy",{enum:["skip","catch_up"]}).notNull(),enabled:gc("enabled",{mode:"boolean"}).notNull(),lastFiredAt:Ot("last_fired_at"),createdAt:Ot("created_at").notNull()},o=>[yc("schedules_enabled_idx").on(o.enabled)])});import{integer as jc,sqliteTable as _c,text as je}from"drizzle-orm/sqlite-core";var dt,dr=p(()=>{"use strict";dt=_c("workflow_shortcuts",{id:je("id").primaryKey(),name:je("name").notNull(),workflowId:je("workflow_id").notNull(),inputValues:je("input_values",{mode:"json"}).$type().notNull(),lastJobId:je("last_job_id"),order:jc("order").notNull().default(0)})});import{sqliteTable as Ic,text as $n}from"drizzle-orm/sqlite-core";var _e,te,fr=p(()=>{"use strict";_e="default",te=Ic("settings",{id:$n("id").primaryKey(),data:$n("data",{mode:"json"}).$type().notNull()})});import{defineRelations as xc}from"drizzle-orm";var Ec,Ln,Un=p(()=>{"use strict";ze();cr();ge();ur();lr();Qe();pr();dr();fr();Ec={workflowDefinitions:ct,subjectViews:ut,jobs:N,jobSubjects:pt,jobStepExecutions:Vt,jobBatches:Rt,schedules:Pt,workflowShortcuts:dt,settings:te},Ln=xc(Ec,o=>({workflowDefinitions:{},subjectViews:{},schedules:{},workflowShortcuts:{},settings:{},jobs:{subjects:o.many.jobSubjects({from:o.jobs.id,to:o.jobSubjects.jobId}),stepExecutions:o.many.jobStepExecutions({from:o.jobs.id,to:o.jobStepExecutions.jobId}),batch:o.one.jobBatches({from:o.jobs.batchId,to:o.jobBatches.id})},jobSubjects:{job:o.one.jobs({from:o.jobSubjects.jobId,to:o.jobs.id})},jobStepExecutions:{job:o.one.jobs({from:o.jobStepExecutions.jobId,to:o.jobs.id}),parent:o.one.jobStepExecutions({from:o.jobStepExecutions.parentStepExecutionId,to:o.jobStepExecutions.id,alias:"job_step_executions_parent"}),children:o.many.jobStepExecutions({from:o.jobStepExecutions.id,to:o.jobStepExecutions.parentStepExecutionId,alias:"job_step_executions_children"})},jobBatches:{jobs:o.many.jobs({from:o.jobBatches.id,to:o.jobs.batchId})}}))});import{drizzle as vc}from"drizzle-orm/node-sqlite";import{DatabaseSync as pm}from"node:sqlite";function Fn(o){return o.exec("PRAGMA foreign_keys = ON;"),vc({client:o,relations:Ln})}var Jn=p(()=>{"use strict";Un()});function Ze(o,t,e){return o.prepare(`PRAGMA table_info(${t})`).all().some(i=>i.name===e)}function Tc(o){Ze(o,"subject_views","order")||o.exec('ALTER TABLE subject_views ADD COLUMN "order" INTEGER NOT NULL DEFAULT 0'),Ze(o,"subject_views","query_template")||o.exec("ALTER TABLE subject_views ADD COLUMN query_template TEXT"),Ze(o,"subject_views","workflow_id")||o.exec("ALTER TABLE subject_views ADD COLUMN workflow_id TEXT NOT NULL DEFAULT ''"),Ze(o,"schedules","workflow_id")&&o.exec("ALTER TABLE schedules DROP COLUMN workflow_id"),o.exec(`
12
12
  CREATE INDEX IF NOT EXISTS subject_views_subject_type_order_idx
13
13
  ON subject_views (subject_type, "order");
14
- `)}function Mo(o){o.exec(`
14
+ `)}function mr(o){o.exec(`
15
15
  PRAGMA foreign_keys = ON;
16
16
 
17
17
  CREATE TABLE IF NOT EXISTS workflow_definitions (
@@ -33,8 +33,10 @@ ${Js[o.outputFormat]}`),t.join(`
33
33
  id TEXT PRIMARY KEY NOT NULL,
34
34
  name TEXT NOT NULL,
35
35
  subject_type TEXT NOT NULL,
36
+ workflow_id TEXT NOT NULL,
36
37
  query TEXT NOT NULL,
37
38
  description TEXT,
39
+ query_template TEXT,
38
40
  "order" INTEGER NOT NULL DEFAULT 0
39
41
  );
40
42
  CREATE INDEX IF NOT EXISTS subject_views_subject_type_idx
@@ -111,7 +113,6 @@ ${Js[o.outputFormat]}`),t.join(`
111
113
 
112
114
  CREATE TABLE IF NOT EXISTS schedules (
113
115
  id TEXT PRIMARY KEY NOT NULL,
114
- workflow_id TEXT NOT NULL,
115
116
  view_id TEXT NOT NULL,
116
117
  trigger_type TEXT NOT NULL,
117
118
  cadence TEXT NOT NULL,
@@ -123,12 +124,21 @@ ${Js[o.outputFormat]}`),t.join(`
123
124
  );
124
125
  CREATE INDEX IF NOT EXISTS schedules_enabled_idx ON schedules (enabled);
125
126
 
127
+ CREATE TABLE IF NOT EXISTS workflow_shortcuts (
128
+ id TEXT PRIMARY KEY NOT NULL,
129
+ name TEXT NOT NULL,
130
+ workflow_id TEXT NOT NULL,
131
+ input_values TEXT NOT NULL,
132
+ last_job_id TEXT,
133
+ "order" INTEGER NOT NULL DEFAULT 0
134
+ );
135
+
126
136
  CREATE TABLE IF NOT EXISTS settings (
127
137
  id TEXT PRIMARY KEY NOT NULL,
128
138
  data TEXT NOT NULL
129
139
  );
130
- `),Sa(o)}var cr=p(()=>{"use strict"});import{Injectable as Ia}from"@nestjs/common";import{mkdirSync as xa}from"node:fs";import{dirname as Ea}from"node:path";import{fileURLToPath as va}from"node:url";import{DatabaseSync as ur}from"node:sqlite";var _a,ja,G,dr=p(()=>{"use strict";ar();cr();_a=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},ja=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},G=class{sqlite;db;constructor(){let e=process.env.KNO_SQLITE_PATH??va(new URL("../../data/kno.db",import.meta.url));e===":memory:"?this.sqlite=new ur(":memory:"):(xa(Ea(e),{recursive:!0}),this.sqlite=new ur(e)),this.db=sr(this.sqlite),Mo(this.sqlite)}async onModuleInit(){Mo(this.sqlite)}getDb(){return this.db}getSqlite(){return this.sqlite}};G=_a([Ia(),ja("design:paramtypes",[])],G)});import{Injectable as Ra}from"@nestjs/common";import{eq as pr}from"drizzle-orm";var Ta,Oa,L,Be=p(()=>{"use strict";$e();Ta=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},Oa=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},L=class{db;sqlite;constructor(t,e){this.db=t,this.sqlite=e}async create(t){let e=new Date().toISOString();return await this.db.insert(et).values({id:t.id,name:t.name,description:t.description??null,appliesTo:t.appliesTo,cardinality:t.cardinality,inputSchema:t.inputSchema,steps:t.steps,notificationPolicy:t.notificationPolicy,createdAt:e,updatedAt:e}),await this.get(t.id)}async get(t){let e=await this.db.query.workflowDefinitions.findFirst({where:{id:t}});return e?this.toDomain(e):null}async update(t,e){let n=await this.get(t);return n?(await this.db.update(et).set({name:e.name??n.name,description:e.description!==void 0?e.description??null:n.description??null,appliesTo:e.appliesTo??n.appliesTo,cardinality:e.cardinality??n.cardinality,inputSchema:e.inputSchema??n.inputSchema,steps:e.steps??n.steps,notificationPolicy:e.notificationPolicy??n.notificationPolicy,updatedAt:new Date().toISOString()}).where(pr(et.id,t)),this.get(t)):null}async list(t={}){return(t.cardinality?await this.db.query.workflowDefinitions.findMany({where:{cardinality:t.cardinality}}):await this.db.query.workflowDefinitions.findMany()).map(n=>this.toDomain(n))}async delete(t){if(!await this.get(t))return!1;try{this.sqlite?.exec("PRAGMA foreign_keys = OFF"),await this.db.delete(et).where(pr(et.id,t))}finally{this.sqlite?.exec("PRAGMA foreign_keys = ON")}return!0}toDomain(t){return{id:t.id,name:t.name,...t.description!=null?{description:t.description}:{},appliesTo:t.appliesTo,cardinality:t.cardinality,inputSchema:t.inputSchema,steps:t.steps,notificationPolicy:t.notificationPolicy}}};L=Ta([Ra(),Oa("design:paramtypes",[Object,Function])],L)});import{Injectable as ka}from"@nestjs/common";import{eq as Vo}from"drizzle-orm";var Pa,Aa,lr,B,Je=p(()=>{"use strict";Lo();Pa=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},Aa=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},lr=["ticket","pull_request","documentation"],B=class{db;constructor(t){this.db=t}async create(t){let e=await this.nextOrder(t.subjectType);return await this.db.insert(ot).values({id:t.id,name:t.name,subjectType:t.subjectType,query:t.query,description:t.description??null,order:e}),await this.get(t.id)}async get(t){let e=await this.db.query.subjectViews.findFirst({where:{id:t}});return e?this.toDomain(e):null}async update(t,e){let n=await this.get(t);return n?(await this.db.update(ot).set({name:e.name??n.name,subjectType:e.subjectType??n.subjectType,query:e.query??n.query,description:e.description!==void 0?e.description??null:n.description??null}).where(Vo(ot.id,t)),this.get(t)):null}async list(t={}){let e=t.subjectType?await this.db.query.subjectViews.findMany({where:{subjectType:t.subjectType}}):await this.db.query.subjectViews.findMany();return this.sortViews(e.map(n=>this.toDomain(n)))}async reorder(t){let e=[];for(let i of t){let r=await this.get(i);if(!r)return[];e.push(r)}let n=e[0].subjectType;if(!e.every(i=>i.subjectType===n))return[];for(let i=0;i<t.length;i+=1)await this.db.update(ot).set({order:i}).where(Vo(ot.id,t[i]));return this.list({subjectType:n})}async delete(t){return await this.get(t)?(await this.db.delete(ot).where(Vo(ot.id,t)),!0):!1}async nextOrder(t){let e=await this.db.query.subjectViews.findMany({where:{subjectType:t}});return e.length===0?0:Math.max(...e.map(n=>n.order))+1}sortViews(t){return[...t].sort((e,n)=>{let i=lr.indexOf(e.subjectType)-lr.indexOf(n.subjectType);return i!==0?i:e.order-n.order})}toDomain(t){return{id:t.id,name:t.name,subjectType:t.subjectType,query:t.query,order:t.order,...t.description!=null?{description:t.description}:{}}}};B=Pa([ka(),Aa("design:paramtypes",[Object])],B)});import{Injectable as Da}from"@nestjs/common";import{eq as Ko}from"drizzle-orm";import{randomUUID as $a}from"node:crypto";function qa(o){return o?o.mode==="single"?[o.subject]:o.subjects:[]}function La(o){if(o.length!==0)return o.length===1?{mode:"single",subject:o[0]}:{mode:"collection",subjects:o}}function mr(o,t,e=null,n=null){let i=[];for(let r of t)if(i.push({id:r.id,jobId:o,stepDefinitionId:r.stepDefinitionId,type:r.type,status:r.status,startedAt:r.startedAt??null,completedAt:r.completedAt??null,output:r.output??null,error:r.error??null,childJobIds:r.childJobIds??null,parentStepExecutionId:e,iterationIndex:n}),r.iterations)for(let s of r.iterations)i.push(...mr(o,s.stepExecutions,r.id,s.index));return i}function Ba(o){let t=new Map;for(let i of o){let r=i.parentStepExecutionId,s=t.get(r)??[];s.push(i),t.set(r,s)}let e=i=>{let r=t.get(i)??[];if(r.length===0)return;let s=new Map;for(let a of r){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(f=>fr(f,e(f.id)));return{index:a,stepExecutions:c,startedAt:Ja(c),...Ua(c)?{completedAt:Fa(c)}:{}}})};return(t.get(null)??[]).filter(i=>i.iterationIndex==null).map(i=>fr(i,e(i.id)))}function fr(o,t){return{id:o.id,stepDefinitionId:o.stepDefinitionId,type:o.type,status:o.status,...o.startedAt!=null?{startedAt:o.startedAt}:{},...o.completedAt!=null?{completedAt:o.completedAt}:{},...o.output!==null&&o.output!==void 0?{output:o.output}:{},...o.error!=null?{error:o.error}:{},...o.childJobIds!=null?{childJobIds:o.childJobIds}:{},...t&&t.length>0?{iterations:t}:{}}}function Ja(o){let t=o.map(e=>e.startedAt).filter(e=>e!=null);return t.length===0?"":t.reduce((e,n)=>e<n?e:n)}function Fa(o){return o.map(e=>e.completedAt).filter(e=>e!=null).reduce((e,n)=>e>n?e:n)}function Ua(o){return o.length>0&&o.every(t=>t.completedAt!=null)}var Na,Ca,x,Ut=p(()=>{"use strict";ae();Bo();Jo();Na=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},Ca=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},x=class{db;constructor(t){this.db=t}async create(t){return await this.db.insert(rt).values(this.jobToRow(t)),await this.replaceSubjects(t.id,t.subjectContext),await this.replaceStepExecutions(t.id,t.stepHistory),await this.get(t.id)}async get(t){let e=await this.db.query.jobs.findFirst({where:{id:t},with:{subjects:!0,stepExecutions:!0}});return e?this.toDomain(e,e.subjects,e.stepExecutions):null}async update(t,e){let n=await this.get(t);if(!n)return null;let i={...n,...e,id:t,context:e.context??n.context,stepHistory:e.stepHistory??n.stepHistory,updatedAt:e.updatedAt??new Date().toISOString()};return await this.db.update(rt).set({workflowId:i.workflowId,status:i.status,selection:i.selection??null,batchId:i.batchId??null,parentJobId:i.parentJobId??null,parentStepExecutionId:i.parentStepExecutionId??null,fanOutIndex:i.fanOutIndex??null,retryOf:i.retryOf??null,context:i.context,worktreePath:i.worktreePath??null,branch:i.branch??null,currentStepId:i.currentStepId??null,currentStepExecutionId:i.currentStepExecutionId??null,createdAt:i.createdAt,updatedAt:i.updatedAt,completedAt:i.completedAt??null}).where(Ko(rt.id,t)),e.subjectContext!==void 0&&await this.replaceSubjects(t,e.subjectContext),e.stepHistory!==void 0&&await this.replaceStepExecutions(t,e.stepHistory),this.get(t)}async list(t={}){let e={};t.workflowId!==void 0&&(e.workflowId=t.workflowId),t.status!==void 0&&(e.status=t.status),t.batchId!==void 0&&(e.batchId=t.batchId),t.parentJobId!==void 0&&(e.parentJobId=t.parentJobId),t.parentStepExecutionId!==void 0&&(e.parentStepExecutionId=t.parentStepExecutionId);let i=(Object.keys(e).length>0?await this.db.query.jobs.findMany({where:e,with:{subjects:!0,stepExecutions:!0}}):await this.db.query.jobs.findMany({with:{subjects:!0,stepExecutions:!0}})).map(r=>this.toDomain(r,r.subjects,r.stepExecutions));return t.topLevelOnly?i.filter(r=>r.batchId==null&&r.parentJobId==null):i}jobToRow(t){return{id:t.id,workflowId:t.workflowId,status:t.status,selection:t.selection??null,batchId:t.batchId??null,parentJobId:t.parentJobId??null,parentStepExecutionId:t.parentStepExecutionId??null,fanOutIndex:t.fanOutIndex??null,retryOf:t.retryOf??null,context:t.context,worktreePath:t.worktreePath??null,branch:t.branch??null,currentStepId:t.currentStepId??null,currentStepExecutionId:t.currentStepExecutionId??null,createdAt:t.createdAt,updatedAt:t.updatedAt,completedAt:t.completedAt??null}}async replaceSubjects(t,e){await this.db.delete(Jt).where(Ko(Jt.jobId,t));let n=qa(e);n.length!==0&&await this.db.insert(Jt).values(n.map(i=>({id:$a(),jobId:t,subjectType:i.subjectType,subjectId:i.id,snapshot:i})))}async replaceStepExecutions(t,e){await this.db.delete(Nt).where(Ko(Nt.jobId,t));let n=mr(t,e);n.length!==0&&await this.db.insert(Nt).values(n)}toDomain(t,e,n){let i=La(e.map(s=>s.snapshot)),r=Ba(n);return{id:t.id,workflowId:t.workflowId,status:t.status,...i?{subjectContext:i}:{},...t.selection!=null?{selection:t.selection}:{},...t.batchId!=null?{batchId:t.batchId}:{},...t.parentJobId!=null?{parentJobId:t.parentJobId}:{},...t.parentStepExecutionId!=null?{parentStepExecutionId:t.parentStepExecutionId}:{},...t.fanOutIndex!=null?{fanOutIndex:t.fanOutIndex}:{},...t.retryOf!=null?{retryOf:t.retryOf}:{},context:t.context,...t.worktreePath!=null?{worktreePath:t.worktreePath}:{},...t.branch!=null?{branch:t.branch}:{},...t.currentStepId!=null?{currentStepId:t.currentStepId}:{},...t.currentStepExecutionId!=null?{currentStepExecutionId:t.currentStepExecutionId}:{},stepHistory:r,createdAt:t.createdAt,updatedAt:t.updatedAt,...t.completedAt!=null?{completedAt:t.completedAt}:{}}}};x=Na([Da(),Ca("design:paramtypes",[Object])],x)});import{Injectable as Ka}from"@nestjs/common";import{eq as Xa}from"drizzle-orm";var Ma,Va,J,Fe=p(()=>{"use strict";qe();Ma=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},Va=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},J=class{db;constructor(t){this.db=t}async create(t){return await this.db.insert(wt).values({id:t.id,workflowId:t.workflowId,selection:t.selection,resolvedSubjects:t.resolvedSubjects,status:t.status,triggeredBy:t.triggeredBy,scheduleId:t.scheduleId??null,notificationOverride:t.notificationOverride??null,notificationSent:t.notificationSent,createdAt:t.createdAt,completedAt:t.completedAt??null}),await this.get(t.id)}async get(t){let e=await this.db.query.jobBatches.findFirst({where:{id:t},with:{jobs:!0}});return e?this.toDomain(e,e.jobs.map(n=>n.id)):null}async update(t,e){let n=await this.get(t);return n?(await this.db.update(wt).set({workflowId:e.workflowId??n.workflowId,selection:e.selection??n.selection,resolvedSubjects:e.resolvedSubjects??n.resolvedSubjects,status:e.status??n.status,triggeredBy:e.triggeredBy??n.triggeredBy,scheduleId:e.scheduleId!==void 0?e.scheduleId??null:n.scheduleId??null,notificationOverride:e.notificationOverride!==void 0?e.notificationOverride??null:n.notificationOverride??null,notificationSent:e.notificationSent??n.notificationSent,createdAt:e.createdAt??n.createdAt,completedAt:e.completedAt!==void 0?e.completedAt??null:n.completedAt??null}).where(Xa(wt.id,t)),this.get(t)):null}async list(t={}){return(t.workflowId?await this.db.query.jobBatches.findMany({where:{workflowId:t.workflowId},with:{jobs:!0}}):await this.db.query.jobBatches.findMany({with:{jobs:!0}})).map(n=>this.toDomain(n,n.jobs.map(i=>i.id)))}toDomain(t,e){return{id:t.id,workflowId:t.workflowId,selection:t.selection,resolvedSubjects:t.resolvedSubjects,jobIds:e,status:t.status,triggeredBy:t.triggeredBy,...t.scheduleId!=null?{scheduleId:t.scheduleId}:{},...t.notificationOverride!=null?{notificationOverride:t.notificationOverride}:{},notificationSent:t.notificationSent,createdAt:t.createdAt,...t.completedAt!=null?{completedAt:t.completedAt}:{}}}};J=Ma([Ka(),Va("design:paramtypes",[Object])],J)});import{Injectable as Ga}from"@nestjs/common";import{eq as hr}from"drizzle-orm";var Ha,Wa,dt,Xo=p(()=>{"use strict";Fo();Ha=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},Wa=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},dt=class{db;constructor(t){this.db=t}async create(t){return await this.db.insert(St).values({id:t.id,workflowId:t.workflowId,viewId:t.viewId,triggerType:t.trigger.type,cadence:t.trigger.cadence,notificationOverride:t.notificationOverride??null,missedFirePolicy:t.missedFirePolicy,enabled:t.enabled,lastFiredAt:t.lastFiredAt??null,createdAt:t.createdAt}),await this.get(t.id)}async get(t){let e=await this.db.query.schedules.findFirst({where:{id:t}});return e?this.toDomain(e):null}async update(t,e){let n=await this.get(t);if(!n)return null;let i=e.trigger??n.trigger;return await this.db.update(St).set({workflowId:e.workflowId??n.workflowId,viewId:e.viewId??n.viewId,triggerType:i.type,cadence:i.cadence,notificationOverride:e.notificationOverride!==void 0?e.notificationOverride??null:n.notificationOverride??null,missedFirePolicy:e.missedFirePolicy??n.missedFirePolicy,enabled:e.enabled??n.enabled,lastFiredAt:e.lastFiredAt!==void 0?e.lastFiredAt??null:n.lastFiredAt??null,createdAt:e.createdAt??n.createdAt}).where(hr(St.id,t)),this.get(t)}async list(t={}){return(t.enabled!==void 0?await this.db.query.schedules.findMany({where:{enabled:t.enabled}}):await this.db.query.schedules.findMany()).map(n=>this.toDomain(n))}async delete(t){return await this.get(t)?(await this.db.delete(St).where(hr(St.id,t)),!0):!1}async findDue(t){return(await this.list({enabled:!0})).filter(n=>n.lastFiredAt==null||n.lastFiredAt<t)}toDomain(t){return{id:t.id,workflowId:t.workflowId,viewId:t.viewId,trigger:{type:"cron",cadence:t.cadence},...t.notificationOverride!=null?{notificationOverride:t.notificationOverride}:{},missedFirePolicy:t.missedFirePolicy,enabled:t.enabled,...t.lastFiredAt!=null?{lastFiredAt:t.lastFiredAt}:{},createdAt:t.createdAt}}};dt=Ha([Ga(),Wa("design:paramtypes",[Object])],dt)});import{Injectable as Qa}from"@nestjs/common";import{eq as Za}from"drizzle-orm";function tc(o,t){let e={...o.activeProviders,...t.activeProviders},n=t.jira!==void 0?{...o.jira,...t.jira}:o.jira,i=t.bitbucket!==void 0?{...o.bitbucket,...t.bitbucket}:o.bitbucket;return Ho({activeProviders:e,...n&&Object.keys(n).length>0?{jira:n}:{},...i&&Object.keys(i).length>0?{bitbucket:i}:{}})}function Ho(o){return{...o,activeProviders:{ticket:o.activeProviders?.ticket??"manual",repo:o.activeProviders?.repo??"manual",agent:o.activeProviders?.agent??"claude"},...o.jira?{jira:o.jira}:{},...o.bitbucket?{bitbucket:o.bitbucket}:{}}}function br(o){return Object.prototype.hasOwnProperty.call(o,"activeProviders")}var za,Ya,D,Ue=p(()=>{"use strict";Uo();za=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},Ya=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},D=class{db;constructor(t){this.db=t}async get(){let t=await this.db.query.settings.findFirst({where:{id:ue}});return Ho(t?t.data:{})}async update(t){let e=tc(await this.get(),t);return await this.db.query.settings.findFirst({where:{id:ue}})?await this.db.update(Ft).set({data:e}).where(Za(Ft.id,ue)):await this.db.insert(Ft).values({id:ue,data:e}),e}};D=za([Qa(),Ya("design:paramtypes",[Object])],D)});import{Module as oc}from"@nestjs/common";var ec,nc,it,de=p(()=>{"use strict";dr();Be();Je();Ut();Fe();Xo();Ue();ec=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},nc=[L,B,x,J,dt,D],it=class{};it=ec([oc({providers:[G,{provide:L,useFactory:o=>new L(o.getDb(),o.getSqlite()),inject:[G]},{provide:B,useFactory:o=>new B(o.getDb()),inject:[G]},{provide:x,useFactory:o=>new x(o.getDb()),inject:[G]},{provide:J,useFactory:o=>new J(o.getDb()),inject:[G]},{provide:dt,useFactory:o=>new dt(o.getDb()),inject:[G]},{provide:D,useFactory:o=>new D(o.getDb()),inject:[G]}],exports:[G,...nc]})],it)});function Wo(o){return o==null?"":typeof o=="string"?o:yr(o).replace(/\n+$/,"")}function gr(o){return{version:1,type:"doc",content:o.split(`
131
- `).map(e=>({type:"paragraph",content:e.length===0?[]:[{type:"text",text:e}]}))}}function yr(o){if(o==null||typeof o!="object")return"";let t=o;if(t.type==="text")return t.text??"";if(t.type==="hardBreak")return`
132
- `;let e=(t.content??[]).map(yr).join("");return t.type==="paragraph"||t.type==="heading"||t.type==="blockquote"||t.type==="listItem"?`${e}
133
- `:e}var wr=p(()=>{"use strict"});function sc(o){if(typeof o.jql=="string"&&o.jql.trim().length>0)return o.jql;let t=[];if(Ve(o.project)&&t.push(`project = ${Ke(o.project)}`),Ve(o.status)&&t.push(`status = ${Ke(o.status)}`),Ve(o.assignee)&&t.push(`assignee = ${Ke(o.assignee)}`),Ve(o.sprintId)){let e=o.sprintId;t.push(typeof e=="number"||/^\d+$/.test(String(e))?`sprint = ${Number(e)}`:`sprint = ${Ke(e)}`)}if(t.length===0)throw new Error("Jira query requires jql or at least one of project, status, assignee, sprintId");return t.join(" AND ")}function Ve(o){return o!=null&&o!==""}function Ke(o){return`"${String(o).replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Sr(o,t){let e=String(o.key??o.id??""),n=o.fields??{},i=Wo(n.description);return{id:e,source:"jira",title:String(n.summary??""),...i?{description:i}:{},status:String(n.status?.name??""),...n.assignee?.displayName?{assignee:String(n.assignee.displayName)}:{},url:`${t.replace(/\/$/,"")}/browse/${e}`,raw:o}}var Mt,rc,ic,Me,Xe,Go=p(()=>{"use strict";wr();Mt="kno.jira.apiToken",rc=50,ic=10,Me=500,Xe=class{secrets;settings;fetchFn;constructor(t,e,n=fetch){this.secrets=t,this.settings=e,this.fetchFn=n}async get(t){let{baseUrl:e}=await this.requireConfig(),n=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(t)}`);return Sr(n,e)}async query(t){let{baseUrl:e}=await this.requireConfig(),n=sc(t),i=[],r,s=new Set;for(let a=0;a<ic&&i.length<Me;a++){let u={jql:n,maxResults:Math.min(rc,Me-i.length),fields:["summary","description","status","assignee"]};r&&(u.nextPageToken=r);let c=await this.request("POST","/rest/api/3/search/jql",{body:u}),f=Array.isArray(c.issues)?c.issues:[];for(let y of f){if(i.length>=Me)break;i.push(Sr(y,e))}let m=typeof c.nextPageToken=="string"?c.nextPageToken:void 0;if(c.isLast===!0||!m||f.length===0||m===r||s.has(m))break;s.add(m),r=m}return i}async getComments(t){let e=[],n=0,i=100,r=Me;for(;e.length<r;){let s=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(t)}/comment?startAt=${n}&maxResults=${i}`),a=Array.isArray(s.comments)?s.comments:[];for(let u of a)e.push({id:String(u.id??""),subjectId:t,body:Wo(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<i)break}return e}async postComment(t,e){await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(t)}/comment`,{body:{body:gr(e)}})}async updateStatus(t,e){let n=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(t)}/transitions`),i=Array.isArray(n.transitions)?n.transitions:[],r=e.trim().toLowerCase(),s=i.find(a=>(a.to?.name??"").trim().toLowerCase()===r);if(!s?.id){let a=i.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 '${e}' from the current state. Available: ${u}`)}await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(t)}/transitions`,{body:{transition:{id:s.id}}})}async requireConfig(){let t=(await this.settings.get()).jira,e=t?.baseUrl?.trim(),n=t?.email?.trim(),i=await this.secrets.get(Mt),r=[];if(e||r.push("settings.jira.baseUrl"),n||r.push("settings.jira.email"),i||r.push(`SecretStore '${Mt}'`),r.length>0)throw new Error(`Jira is not configured \u2014 missing ${r.join(", ")}. Set jira.baseUrl and jira.email via PATCH /api/settings, and store the API token with: POST /api/secrets/${Mt} or npm --workspace apps/engine run set-secret -- ${Mt} <value>`);return{baseUrl:e,email:n,token:i}}async request(t,e,n={}){let{baseUrl:i,email:r,token:s}=await this.requireConfig(),a=`${i.replace(/\/$/,"")}${e}`,u={Authorization:`Basic ${Buffer.from(`${r}:${s}`).toString("base64")}`,Accept:"application/json"};n.body!==void 0&&(u["Content-Type"]="application/json");let c=await this.fetchFn(a,{method:t,headers:u,...n.body!==void 0?{body:JSON.stringify(n.body)}:{}});if(!c.ok){let m=await c.text().catch(()=>"");throw new Error(`Jira ${t} ${e} failed (${c.status}): ${m||c.statusText}`)}if(c.status===204)return;let f=await c.text();if(f)return JSON.parse(f)}}});function He(o){let t=o.trim(),e=t.lastIndexOf("#");if(e<=0||e===t.length-1)throw new Error(`Bitbucket pull request id must be '{repoSlug}#{prNumber}' (e.g. 'kno-engine#42'), got '${o}'`);let n=t.slice(0,e),i=t.slice(e+1);if(!/^\d+$/.test(i))throw new Error(`Bitbucket pull request id must be '{repoSlug}#{prNumber}' with a numeric PR number, got '${o}'`);return{repoSlug:n,prNumber:i}}function cc(o,t){return`${o}#${t}`}function uc(o){let t=o.repoSlug;if(typeof t!="string"||t.trim().length===0)throw new Error("Bitbucket query requires filter.repoSlug \u2014 PR listing is scoped per repository");return t.trim()}function dc(o){if(typeof o.q=="string"&&o.q.trim().length>0)return o.q;if(lc(o.state)){let t=String(o.state).trim().toUpperCase();if(t!=="OPEN"&&t!=="MERGED"&&t!=="DECLINED")throw new Error(`Bitbucket query filter.state must be OPEN, MERGED, or DECLINED, got '${String(o.state)}'`);return`state="${t}"`}}function pc(o){let t=o.trim().toLowerCase();if(t==="approved")return"approve";if(t==="declined"||t==="rejected")return"decline";if(t==="merged")return"merge";throw new Error(`No Bitbucket action for status '${o}'. Accepted: approved, declined/rejected, merged`)}function lc(o){return o!=null&&o!==""}function _r(o,t){let e=String(o.id??""),n=typeof o.description=="string"?o.description:"";return{id:cc(t,e),source:"bitbucket",title:String(o.title??""),...n?{description:n}:{},sourceBranch:String(o.source?.branch?.name??""),targetBranch:String(o.destination?.branch?.name??""),...o.author?.display_name?{author:o.author.display_name}:{},...o.links?.html?.href?{url:o.links.html.href}:{},raw:o}}function fc(o,t){let e=o.user?.display_name??o.author?.display_name;return{id:String(o.id??""),subjectId:t,body:o.content?.raw??"",...e?{author:e}:{},createdAt:o.created_on??"",raw:o}}var Vt,ac,We,zo=p(()=>{"use strict";Vt="kno.bitbucket.apiToken",ac="https://api.bitbucket.org/2.0",We=class{secrets;settings;fetchFn;constructor(t,e,n=fetch){this.secrets=t,this.settings=e,this.fetchFn=n}async get(t){let{repoSlug:e,prNumber:n}=He(t),{workspace:i}=await this.requireConfig(),r=await this.request("GET",this.prPath(i,e,n));return _r(r,e)}async query(t){let e=uc(t),{baseUrl:n,workspace:i}=await this.requireConfig(),r=dc(t),s=[],a=new Set,u=new URLSearchParams({pagelen:String(50)});r&&u.set("q",r);let c=`${n.replace(/\/$/,"")}/repositories/${encodeURIComponent(i)}/${encodeURIComponent(e)}/pullrequests?${u.toString()}`;for(let f=0;f<10&&s.length<500&&!(!c||a.has(c));f++){a.add(c);let m=await this.request("GET",c),y=Array.isArray(m.values)?m.values:[];for(let I of y){if(s.length>=500)break;s.push(_r(I,e))}let h=typeof m.next=="string"&&m.next.length>0?m.next:void 0;if(!h||y.length===0)break;c=h}return s}async getComments(t){let{repoSlug:e,prNumber:n}=He(t),{workspace:i}=await this.requireConfig(),r=[],s=new Set,a=`${this.prPath(i,e,n)}/comments?pagelen=50`;for(let u=0;u<10&&r.length<500&&!(!a||s.has(a));u++){s.add(a);let c=await this.request("GET",a),f=Array.isArray(c.values)?c.values:[];for(let y of f)r.push(fc(y,t));let m=typeof c.next=="string"&&c.next.length>0?c.next:void 0;if(!m||f.length===0)break;a=m}return r}async postComment(t,e){let{repoSlug:n,prNumber:i}=He(t),{workspace:r}=await this.requireConfig();await this.request("POST",`${this.prPath(r,n,i)}/comments`,{body:{content:{raw:e}}})}async updateStatus(t,e){let{repoSlug:n,prNumber:i}=He(t),{workspace:r}=await this.requireConfig(),s=pc(e);await this.request("POST",`${this.prPath(r,n,i)}/${s}`)}prPath(t,e,n){return`/repositories/${encodeURIComponent(t)}/${encodeURIComponent(e)}/pullrequests/${encodeURIComponent(n)}`}async requireConfig(){let t=(await this.settings.get()).bitbucket,e=(t?.baseUrl?.trim()||ac).replace(/\/$/,""),n=t?.email?.trim(),i=t?.workspace?.trim(),r=await this.secrets.get(Vt),s=[];if(n||s.push("settings.bitbucket.email"),i||s.push("settings.bitbucket.workspace"),r||s.push(`SecretStore '${Vt}'`),s.length>0)throw new Error(`Bitbucket is not configured \u2014 missing ${s.join(", ")}. Set bitbucket.email and bitbucket.workspace via PATCH /api/settings, and store the API token with: POST /api/secrets/${Vt} or npm --workspace apps/engine run set-secret -- ${Vt} <value>`);return{baseUrl:e,email:n,workspace:i,token:r}}async request(t,e,n={}){let{baseUrl:i,email:r,token:s}=await this.requireConfig(),a=e.startsWith("http://")||e.startsWith("https://")?e:`${i}${e.startsWith("/")?e:`/${e}`}`,u={Authorization:`Basic ${Buffer.from(`${r}:${s}`).toString("base64")}`,Accept:"application/json"};n.body!==void 0&&(u["Content-Type"]="application/json");let c=await this.fetchFn(a,{method:t,headers:u,...n.body!==void 0?{body:JSON.stringify(n.body)}:{}});if(!c.ok){let m=await c.text().catch(()=>"");throw new Error(`Bitbucket ${t} ${e} failed (${c.status}): ${m||c.statusText}`)}if(c.status===204)return;let f=await c.text();if(f)return JSON.parse(f)}}});import{Injectable as gc,Logger as yc,Inject as wc}from"@nestjs/common";async function jr(o){let t=[];for(let e of Sc){let n=await o.get(e.secretKey);t.push({providerId:e.providerId,secretKey:e.secretKey,configured:typeof n=="string"&&n.length>0})}return t}async function _c(o,t){let e=await jr(o);for(let n of e)n.configured||t(`${n.providerId} API key not configured (looked up as '${n.secretKey}'). GET /api/providers/status lists what's missing; store a key with: POST /api/secrets/${n.secretKey} or npm --workspace apps/engine run set-secret -- ${n.secretKey} <value>`)}function Ir(o={}){let t=o.activeProviders?.agent;if(t==null)return"claude";if(t==="claude"||t==="cursor")return t;throw new Error(`Invalid activeProviders.agent '${String(t)}'. Expected 'claude' or 'cursor'.`)}function xr(o={}){let t=o.activeProviders?.ticket;if(t==null||t==="manual")return"manual";if(t==="jira")return"jira";throw new Error(`Invalid activeProviders.ticket '${String(t)}'. Expected 'jira' or 'manual'.`)}function Er(o={}){let t=o.activeProviders?.repo;if(t==null||t==="manual")return"manual";if(t==="bitbucket")return"bitbucket";throw new Error(`Invalid activeProviders.repo '${String(t)}'. Expected 'bitbucket' or 'manual'.`)}var mc,hc,bc,Yo,Sc,_t,Qo=p(()=>{"use strict";yt();Go();zo();mc=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},hc=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},bc=function(o,t){return function(e,n){t(e,n,o)}},Sc=[{providerId:"anthropic",secretKey:ct("anthropic")},{providerId:"cursor",secretKey:ct("cursor")},{providerId:"jira",secretKey:Mt},{providerId:"bitbucket",secretKey:Vt}];_t=Yo=class{secrets;logger=new yc(Yo.name);constructor(t){this.secrets=t}async onModuleInit(){await _c(this.secrets,t=>this.logger.warn(t))}list(){return jr(this.secrets)}};_t=Yo=mc([gc(),bc(0,wc(H)),hc("design:paramtypes",[Function])],_t)});import{Module as Ic}from"@nestjs/common";import{fileURLToPath as xc}from"node:url";import{dirname as Ec,join as vc}from"node:path";var jc,Tc,jt,Ge=p(()=>{"use strict";Ie();$n();Ee();qn();Te();Ln();Po();Hn();Wn();Do();Gn();$o();Yn();qo();yt();de();Ue();Qo();Go();zo();jc=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},Tc=vc(Ec(xc(import.meta.url)),"../../../knowledge"),jt=class{};jt=jc([Ic({imports:[Bt,it],providers:[{provide:Pt,useFactory:async(o,t)=>xr(await t.get())==="jira"?new Xe(o,t):new xe([]),inject:[H,D]},{provide:At,useFactory:async(o,t)=>Er(await t.get())==="bitbucket"?new We(o,t):new ve([]),inject:[H,D]},{provide:kt,useFactory:()=>new Oe([])},{provide:ee,useFactory:async(o,t)=>Ir(await t.get())==="cursor"?new Ne(o):new ke(o),inject:[H,D]},{provide:re,useClass:Ce},{provide:ie,useFactory:()=>new De(Tc)},_t],exports:[Pt,At,kt,ee,re,ie,_t]})],jt)});import{Module as Rc}from"@nestjs/common";var Oc,ze,vr=p(()=>{"use strict";Oc=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},ze=class{};ze=Oc([Rc({})],ze)});import{Injectable as Ac}from"@nestjs/common";var Pc,z,Ye=p(()=>{"use strict";Pc=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},z=class{listeners=new Set;emit(t){for(let e of this.listeners)e(t)}subscribe(t){return this.listeners.add(t),()=>this.listeners.delete(t)}};z=Pc([Ac()],z)});import{Global as Nc,Module as Cc}from"@nestjs/common";var kc,It,Qe=p(()=>{"use strict";Ye();kc=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},It=class{};It=kc([Nc(),Cc({providers:[z],exports:[z]})],It)});import{Injectable as qc}from"@nestjs/common";import{execFile as Lc}from"node:child_process";import{mkdirSync as Tr}from"node:fs";import{join as Zo}from"node:path";import{promisify as Bc}from"node:util";function Or(o){return o==null?"":typeof o=="string"?o:o.toString("utf8")}function Rr(o){return Zo(o,"worktrees")}var Dc,$c,Jc,pt,tn=p(()=>{"use strict";Dc=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},$c=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},Jc=Bc(Lc),pt=class{worktreesRoot;constructor(t){this.worktreesRoot=t,Tr(this.worktreesRoot,{recursive:!0})}async createWorktree(t,e){let n=e.worktreePath??Zo(this.worktreesRoot,t);return Tr(Zo(n,".."),{recursive:!0}),await this.git(e.repoPath,["worktree","add","-b",e.branchName,n,e.baseBranch]),{worktreePath:n,branch:e.branchName}}async checkout(t,e){await this.git(t,["checkout",e.branch])}async createBranch(t,e){e.baseBranch?await this.git(t,["checkout","-b",e.branchName,e.baseBranch]):await this.git(t,["checkout","-b",e.branchName])}async commit(t,e){return e.addAll!==!1&&await this.git(t,["add","-A"]),await this.git(t,["commit","-m",e.message]),{sha:(await this.git(t,["rev-parse","HEAD"])).stdout.trim()}}async push(t,e={}){let n=e.remote??"origin";e.branch?await this.git(t,["push",n,e.branch]):await this.git(t,["push",n,"HEAD"])}async git(t,e){try{let n=await Jc("git",e,{cwd:t,encoding:"utf8",windowsHide:!0});return{stdout:n.stdout??"",stderr:n.stderr??""}}catch(n){let i=n,r=Or(i.stderr),s=Or(i.stdout),a=r||s||i.message||"unknown git error";throw new Error(`git ${e.join(" ")} failed (cwd=${t}, code=${String(i.code??"?")}): ${a}`)}}};pt=Dc([qc(),$c("design:paramtypes",[String])],pt)});import{Module as Uc}from"@nestjs/common";import{mkdirSync as Mc}from"node:fs";import{dirname as Vc,join as Kc}from"node:path";import{fileURLToPath as Xc}from"node:url";var Fc,Pr,Ze,Ar=p(()=>{"use strict";tn();Fc=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},Pr=Kc(Vc(Xc(import.meta.url)),"../../data");Mc(Pr,{recursive:!0});Ze=class{};Ze=Fc([Uc({providers:[{provide:pt,useFactory:()=>new pt(Rr(Pr))}],exports:[pt]})],Ze)});var Ct,g,b,Dt,Y=p(()=>{"use strict";Ct=class extends Error{constructor(t){super(t),this.name=this.constructor.name}},g=class extends Ct{httpStatus=404},b=class extends Ct{httpStatus=400},Dt=class extends Ct{httpStatus=409}});function to(o,t){return o.replace(/\{\{\s*([^}]+?)\s*\}\}/g,(e,n)=>{let i=Hc(t,n.trim());return i==null?"":typeof i=="string"?i:JSON.stringify(i)})}function Hc(o,t){let e=t.split(".").filter(Boolean),n=o;for(let i of e){if(n==null||typeof n!="object")return;n=n[i]}return n}function pe(o,t){return typeof o=="string"?to(o,t):Array.isArray(o)?o.map(e=>pe(e,t)):o&&typeof o=="object"?Object.fromEntries(Object.entries(o).map(([e,n])=>[e,pe(n,t)])):o}var kr=p(()=>{"use strict"});function Nr(o,t){switch(o){case"questionnaire":return en(t);case"confirmation":return Wc(t);case"conversation":return Gc(t);default:return o}}function en(o){if(typeof o=="string"&&o.trim())return[o.trim()];if(!o||typeof o!="object")return[];let t=o.questions;return Array.isArray(t)?t.map(e=>typeof e=="string"?e.trim():e&&typeof e=="object"&&"prompt"in e?String(e.prompt).trim():"").filter(Boolean):[]}function Wc(o){if(typeof o=="string"&&o.trim())return[o.trim()];if(!o||typeof o!="object")return[];let t=o;for(let e of["prompt","message","summary","question"]){let n=t[e];if(typeof n=="string"&&n.trim())return[n.trim()]}return"approved"in t&&!("questions"in t)?[]:en(o)}function Gc(o){if(typeof o=="string"&&o.trim())return[o.trim()];if(!o||typeof o!="object")return[];let t=o;for(let e of["prompt","message","text"]){let n=t[e];if(typeof n=="string"&&n.trim())return[n.trim()]}return"suggestions"in t?[]:"questions"in t?en(o):[]}var Cr=p(()=>{"use strict"});function Kt(o,t){for(let e of o){if(e.id===t)return e;if(e.iterations)for(let n of e.iterations){let i=Kt(n.stepExecutions,t);if(i)return i}}}function le(o,t,e,n){for(let i=0;i<o.length;i++){let r=o[i];if(r.id===t)return{execution:r,siblings:o,index:i,parentLoopExecutionId:e,iterationIndex:n};if(r.iterations)for(let s of r.iterations){let a=le(s.stepExecutions,t,r.id,s.index);if(a)return a}}}function $(o,t,e){return o.map(n=>n.id===t?e(n):n.iterations?{...n,iterations:n.iterations.map(i=>({...i,stepExecutions:$(i.stepExecutions,t,e)}))}:n)}function on(o,t,e,n){return e==null?[...o,t]:o.map(i=>{if(i.id===e){let r=[...i.iterations??[]],s=r.find(a=>a.index===n);if(s){let a={...s,stepExecutions:[...s.stepExecutions,t]},u=r.findIndex(c=>c.index===n);r[u]=a}else{let a={index:n,stepExecutions:[t],startedAt:t.startedAt??new Date().toISOString()};r.push(a),r.sort((u,c)=>u.index-c.index)}return{...i,iterations:r}}return i.iterations?{...i,iterations:i.iterations.map(r=>({...r,stepExecutions:on(r.stepExecutions,t,e,n)}))}:i})}function fe(o,t){for(let e of o){if(e.id===t)return e;if(e.type==="loop"){let n=fe(e.steps,t);if(n)return n}}}function Dr(o,t,e){return $(o,t,n=>{let i=(n.iterations??[]).map(r=>{if(r.index!==e)return r;let s=r.stepExecutions.every(a=>a.completedAt)?r.stepExecutions.map(a=>a.completedAt).reduce((a,u)=>a>u?a:u):void 0;return{...r,...s?{completedAt:s}:{}}});return{...n,iterations:i}})}var $r=p(()=>{"use strict"});import{z as F}from"zod";function qr(o,t){let e=tu[o].safeParse(t);if(!e.success){let n=e.error.issues.map(i=>`${i.path.length?i.path.join("."):"(root)"}: ${i.message}`).join("; ");throw new Error(`Agent output failed validation for format '${o}': ${n}`)}return e.data}var zc,Yc,Qc,Zc,tu,Lr=p(()=>{"use strict";zc=F.object({questions:F.array(F.object({id:F.string(),prompt:F.string()}))}),Yc=F.object({approved:F.boolean()}),Qc=F.object({suggestions:F.array(F.object({body:F.string()}))}),Zc=F.string(),tu={questionnaire:zc,confirmation:Yc,comment_suggestions:Qc,free_text:Zc}});function Br(o){return o==="completed"||o==="failed"||o==="cancelled"}function nn(o,t){let e=new Map;for(let i of o){let r=t(i);if(r==null)continue;let s=e.get(r)??[];s.push(i),e.set(r,s)}if(e.size===0)return null;let n=[];for(let i of e.values()){let r=new Set(i.map(a=>a.retryOf).filter(a=>a!=null)),s=i.find(a=>!r.has(a.id));if(!s)return null;n.push(s)}return{activeJobs:n,allTerminal:n.every(i=>Br(i.status)),groupCount:e.size}}function Jr(o){let t=o.every(n=>n.status==="completed"),e=o.every(n=>n.status==="failed"||n.status==="cancelled");return t?"completed":e?"failed":"completed_with_issues"}var Fr=p(()=>{"use strict"});async function eo(o,t,e){let n=await t.get(o);if(!n)throw new g(`SubjectView not found: ${o}`);if(n.subjectType==="ticket")return(await e.tickets.query(n.query)).map(r=>({subjectType:"ticket",...r}));if(n.subjectType==="pull_request")return(await e.repo.query(n.query)).map(r=>({subjectType:"pull_request",...r}));if(n.subjectType==="documentation")return(await e.documentation.query(n.query)).map(r=>({subjectType:"documentation",...r}));throw new b(`Unsupported subjectType on view: ${n.subjectType}`)}var rn=p(()=>{"use strict";Y()});import{Inject as M,Injectable as nu}from"@nestjs/common";import{randomUUID as sn}from"node:crypto";import{exec as ru}from"node:child_process";import{promisify as iu}from"node:util";function Ur(o,t){let e=t[o.stepId];if(e==null||typeof e!="object")return o.type==="field_empty";let n=e[o.field];return o.type==="field_empty"?n==null?!0:typeof n=="string"||Array.isArray(n)?n.length===0:!1:n===o.value}function cu(o,t){let e=i=>{let r=[];for(let s of i)r.push(s),s.type==="loop"&&r.push(...e(s.steps));return r},n=i=>{let r=i.findIndex(s=>s.id===t);if(r>=0){for(let s=r-1;s>=0;s--)if(i[s].type==="agent")return i[s].id;return}for(let s of i)if(s.type==="loop"){let a=n(s.steps);if(a!==void 0||s.steps.some(u=>u.id===t))return a}};return n(o.steps)}function oo(o){let t={...o.context};return o.subjectContext?.mode==="single"&&(t.subject=o.subjectContext.subject),o.worktreePath&&(t.worktreePath=o.worktreePath),o.branch&&(t.branch=o.branch),t}function no(o){if(!o.worktreePath)throw new Error(`Job ${o.id} has no worktreePath; run create_worktree first`);return o.worktreePath}function st(o,t){let e=o[t];if(typeof e!="string"||e.length===0)throw new Error(`Missing required string param '${t}'`);return e}function uu(o){if(o==="none")throw new Error("normalizeAppliesTo called with none");if(Array.isArray(o)){if(o.length!==1)throw new Error(`Workflow Runner requires appliesTo to be a single SubjectType (got ${JSON.stringify(o)})`);return o[0]}return o}function Mr(o,t){for(let e of o)if(e.required&&(t[e.name]===void 0||t[e.name]===null))throw new b(`Missing required input: ${e.name}`)}var eu,ou,U,su,au,Q,ro=p(()=>{"use strict";Be();Ut();Fe();Je();Ye();Po();Ie();Ee();Te();Do();$o();tn();Y();kr();Cr();$r();Lr();Fr();rn();eu=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},ou=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},U=function(o,t){return function(e,n){t(e,n,o)}},su=iu(ru),au=["user","organization","project"],Q=class{workflows;jobs;batches;views;events;tickets;repo;documentation;agent;notifications;knowledge;git;childTerminalLocks=new Set;batchTerminalLocks=new Set;constructor(t,e,n,i,r,s,a,u,c,f,m,y){this.workflows=t,this.jobs=e,this.batches=n,this.views=i,this.events=r,this.tickets=s,this.repo=a,this.documentation=u,this.agent=c,this.notifications=f,this.knowledge=m,this.git=y,this.events.subscribe(h=>{let I=h;(I.type==="job_completed"||I.type==="job_failed")&&this.onChildTerminal(I.jobId)})}async start(t){let e=await this.createJob(t);return this.emit({type:"job_started",jobId:e.id,timestamp:new Date().toISOString()}),this.runJob(e.id)}async launch(t){let e=await this.requireWorkflow(t.workflowId);if(e.cardinality==="single")throw new b("launch() does not support cardinality 'single'; use start() with a subjectId");if(e.cardinality!=="batch"&&e.cardinality!=="aggregate")throw new b(`Unsupported cardinality: ${e.cardinality}`);Mr(e.inputSchema,t.inputValues);let n=await this.resolveSelection(t.selection);if(e.cardinality==="aggregate"){let a=await this.createJob({workflowId:e.id,subjectContext:{mode:"collection",subjects:n},selection:t.selection,inputValues:t.inputValues});return this.emit({type:"job_started",jobId:a.id,timestamp:new Date().toISOString()}),this.runJob(a.id)}let i=new Date().toISOString(),r=await this.batches.create({id:sn(),workflowId:e.id,selection:t.selection,resolvedSubjects:n,status:"running",triggeredBy:t.triggeredBy,...t.notificationOverride?{notificationOverride:t.notificationOverride}:{},notificationSent:!1,createdAt:i}),s=[];for(let a=0;a<n.length;a++){let u=n[a],c=await this.createJob({workflowId:e.id,subjectContext:{mode:"single",subject:u},selection:t.selection,batchId:r.id,fanOutIndex:a,inputValues:t.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(r.id)}async createJob(t){let e=await this.workflows.get(t.workflowId);if(!e)throw new g(`Workflow not found: ${t.workflowId}`);if(!t.subjectContext&&e.cardinality!=="single")throw new b(`Workflow Runner only supports cardinality 'single' at start() without an explicit subjectContext (got '${e.cardinality}')`);Mr(e.inputSchema,t.inputValues);let n=t.subjectContext??await this.resolveSubjectContext(e,t.subjectId),i=new Date().toISOString();return this.jobs.create({id:sn(),workflowId:e.id,status:"pending",...n?{subjectContext:n}:{},...t.selection?{selection:t.selection}:{},...t.batchId?{batchId:t.batchId}:{},...t.parentJobId?{parentJobId:t.parentJobId}:{},...t.parentStepExecutionId?{parentStepExecutionId:t.parentStepExecutionId}:{},...t.fanOutIndex!=null?{fanOutIndex:t.fanOutIndex}:{},...t.retryOf?{retryOf:t.retryOf}:{},context:{...t.inputValues},stepHistory:[],createdAt:i,updatedAt:i})}async runJob(t){let e=await this.jobs.get(t);if(!e)throw new g(`Job not found: ${t}`);let n=await this.requireWorkflow(e.workflowId);e.status==="pending"&&(e=await this.persistJob({...e,status:"planning",updatedAt:new Date().toISOString()}));let i=await this.executeStepSequence(e,n,n.steps,void 0,void 0,0);return i.outcome==="paused"||i.outcome==="failed"?i.job:this.completeJob(i.job,n)}async resume(t,e){let n=await this.jobs.get(t);if(!n)throw new g(`Job not found: ${t}`);if(n.status!=="waiting_for_human")throw new Dt(`Job ${t} is not waiting for human input (status: ${n.status})`);let i=await this.requireWorkflow(n.workflowId),r=n.currentStepExecutionId;if(!r)throw new Error(`Job ${t} is waiting_for_human but has no currentStepExecutionId`);let s=Kt(n.stepHistory,r);if(!s)throw new Error(`Paused execution ${r} not found on job ${t}`);if(s.type==="loop")return this.resumeAskHuman(n,i,s,e);if(s.type!=="interaction")throw new Error(`Paused execution ${r} has type '${s.type}'; expected interaction or loop`);let a=new Date().toISOString(),u=$(n.stepHistory,r,I=>({...I,status:"completed",completedAt:a,output:e})),c=e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{response:e};n=await this.persistJob({...n,status:"planning",context:{...n.context,[s.stepDefinitionId]:e},stepHistory:u,currentStepId:void 0,currentStepExecutionId:void 0,updatedAt:a}),this.emit({type:"human_answered",jobId:n.id,answers:c,timestamp:a});let f=le(n.stepHistory,r);if(!f)throw new Error(`Could not locate frame for execution ${r}`);let m=this.sequenceForFrameOnJob(n,i,f),y=f.index+1,h=await this.executeStepSequence(n,i,m,f.parentLoopExecutionId,f.iterationIndex,y);return h.outcome==="paused"||h.outcome==="failed"?h.job:f.parentLoopExecutionId!=null&&f.iterationIndex!=null?this.continueLoopAfterBody(h.job,i,f.parentLoopExecutionId,f.iterationIndex):this.completeJob(h.job,i)}async retryFailedJob(t){let e=await this.jobs.get(t);if(!e)throw new g(`Job not found: ${t}`);if(e.status!=="failed")throw new Dt(`Job ${t} is not failed (status: ${e.status})`);let n=e.parentJobId!=null&&e.parentStepExecutionId!=null&&e.fanOutIndex!=null,i=e.batchId!=null&&e.fanOutIndex!=null;if(!n&&!i)throw new b(`Job ${t} is not a retryable sub_workflow child or batch member`);if(n){let a=await this.jobs.get(e.parentJobId);if(!a)throw new g(`Parent job not found: ${e.parentJobId}`);let u=await this.createJob({workflowId:e.workflowId,subjectContext:e.subjectContext,inputValues:{},parentJobId:e.parentJobId,parentStepExecutionId:e.parentStepExecutionId,fanOutIndex:e.fanOutIndex,retryOf:e.id}),c=$(a.stepHistory,e.parentStepExecutionId,f=>({...f,status:"waiting_for_children",error:void 0,completedAt:void 0,childJobIds:[...f.childJobIds??[],u.id]}));return a=await this.persistJob({...a,status:"waiting_for_children",stepHistory:c,completedAt:void 0,updatedAt:new Date().toISOString()}),this.emit({type:"job_started",jobId:u.id,timestamp:new Date().toISOString()}),this.emit({type:"job_retried",jobId:u.id,retryOf:e.id,timestamp:new Date().toISOString()}),this.runJob(u.id),u}let r=await this.batches.get(e.batchId);if(!r)throw new g(`JobBatch not found: ${e.batchId}`);r.status!=="running"&&await this.batches.update(r.id,{status:"running",completedAt:null,notificationSent:!1});let s=await this.createJob({workflowId:e.workflowId,subjectContext:e.subjectContext,selection:e.selection,batchId:e.batchId,fanOutIndex:e.fanOutIndex,inputValues:{},retryOf:e.id});return this.emit({type:"job_started",jobId:s.id,timestamp:new Date().toISOString()}),this.emit({type:"job_retried",jobId:s.id,retryOf:e.id,timestamp:new Date().toISOString()}),this.runJob(s.id),s}async executeStepSequence(t,e,n,i,r,s){let a=t;for(let u=s;u<n.length;u++){let c=n[u],f=new Date().toISOString(),m={id:sn(),stepDefinitionId:c.id,type:c.type,status:"running",startedAt:f},y=on(a.stepHistory,m,i,r);a=await this.persistJob({...a,status:a.status==="pending"?"planning":a.status,currentStepId:c.id,currentStepExecutionId:m.id,stepHistory:y,updatedAt:f}),this.emit({type:"step_started",jobId:a.id,stepDefinitionId:c.id,timestamp:f});try{let h=await this.dispatchStep(a,e,c,m.id,i,r);if(a=h.job,h.outcome==="paused"||h.outcome==="failed")return h}catch(h){return{outcome:"failed",job:await this.failJob(a,e,m.id,c.id,h)}}}return i!=null&&r!=null&&(a=await this.persistJob({...a,stepHistory:Dr(a.stepHistory,i,r),updatedAt:new Date().toISOString()})),{outcome:"completed",job:a}}async dispatchStep(t,e,n,i,r,s){switch(n.type){case"agent":return{outcome:"completed",job:await this.executeAgentStep(t,n,i)};case"interaction":return{outcome:"paused",job:await this.pauseForInteraction(t,e,n,i)};case"git":return{outcome:"completed",job:await this.executeGitStep(t,n,i)};case"provider_action":return{outcome:"completed",job:await this.executeProviderActionStep(t,n,i)};case"shell":return{outcome:"completed",job:await this.executeShellStep(t,n,i)};case"loop":return this.runLoopStep(t,e,n,i,r,s);case"sub_workflow":return this.runSubWorkflowStep(t,n,i);default:{let a=n;throw new b(`Step type '${a.type}' not yet supported by the Workflow Runner`)}}}async runLoopStep(t,e,n,i,r,s,a=0,u=n.maxIterations){let c=t,f=a;for(;;){if(f>=u)switch(n.onMaxIterations.action){case"fail":return c=await this.failExecution(c,e,i,n.id,`Loop '${n.id}' exceeded maxIterations (${u})`),{outcome:"failed",job:c};case"continue":return c=await this.finishExecution(c,i,n.id,{iterations:f,exitedOnMaxIterations:!0}),{outcome:"completed",job:c};case"ask_human":{let y={maxIterationsCheckpoint:!0,nextIteration:f,effectiveMaxIterations:u},h=new Date().toISOString(),I=$(c.stepHistory,i,E=>({...E,status:"pending",output:y}));return c=await this.persistJob({...c,status:"waiting_for_human",currentStepId:n.id,currentStepExecutionId:i,stepHistory:I,updatedAt:h}),this.emit({type:"waiting_for_human",jobId:c.id,stepDefinitionId:n.id,interaction:"confirmation",data:y,questions:[`Loop '${n.id}' reached maxIterations (${u}). Extend, continue, or cancel?`],timestamp:h}),e.notificationPolicy.triggers.includes("on_needs_input")&&await this.notifications.send({title:`Input needed: ${e.name}`,body:`Job ${c.id} hit max iterations on loop '${n.id}'`,jobId:c.id}),{outcome:"paused",job:c}}default:{let y=n.onMaxIterations;throw new Error(`Unknown onMaxIterations action: ${JSON.stringify(y)}`)}}let m=await this.executeStepSequence(c,e,n.steps,i,f,0);if(c=m.job,m.outcome==="paused")return m;if(m.outcome==="failed")return c=await this.failExecution(c,e,i,n.id,"Loop body failed"),{outcome:"failed",job:c};if(Ur(n.until,c.context))return c=await this.finishExecution(c,i,n.id,{iterations:f+1}),{outcome:"completed",job:c};f+=1}}async resumeAskHuman(t,e,n,i){let r=i,s=n.output;if(!s?.maxIterationsCheckpoint)throw new Error(`Loop execution ${n.id} is not at an ask_human checkpoint`);let a=fe(e.steps,n.stepDefinitionId);if(!a||a.type!=="loop")throw new Error(`Loop step definition '${n.stepDefinitionId}' not found`);let u=le(t.stepHistory,n.id),c=new Date().toISOString();if(r.action==="cancel")return await this.failExecution({...t,status:"planning",currentStepId:void 0,currentStepExecutionId:void 0,updatedAt:c},e,n.id,a.id,"Loop cancelled by human at maxIterations checkpoint");if(r.action==="continue"){let I=await this.persistJob({...t,status:"planning",currentStepId:void 0,currentStepExecutionId:void 0,stepHistory:$(t.stepHistory,n.id,E=>({...E,status:"completed",completedAt:c,output:{iterations:s.nextIteration,exitedOnMaxIterations:!0,humanAction:"continue"}})),updatedAt:c});return this.emit({type:"human_answered",jobId:I.id,answers:r,timestamp:c}),this.emit({type:"step_completed",jobId:I.id,stepDefinitionId:a.id,timestamp:c}),u?.parentLoopExecutionId!=null&&u.iterationIndex!=null?this.continueLoopAfterBody(I,e,u.parentLoopExecutionId,u.iterationIndex):this.continueTopLevelAfter(I,e,a.id)}let f=typeof r.additionalIterations=="number"?r.additionalIterations:0,m=s.effectiveMaxIterations+f,y=await this.persistJob({...t,status:"planning",currentStepId:void 0,currentStepExecutionId:void 0,stepHistory:$(t.stepHistory,n.id,I=>({...I,status:"running",output:void 0})),updatedAt:c});this.emit({type:"human_answered",jobId:y.id,answers:r,timestamp:c});let h=await this.runLoopStep(y,e,a,n.id,u?.parentLoopExecutionId,u?.iterationIndex,s.nextIteration,m);return h.outcome==="paused"||h.outcome==="failed"?h.job:u?.parentLoopExecutionId!=null&&u.iterationIndex!=null?this.continueLoopAfterBody(h.job,e,u.parentLoopExecutionId,u.iterationIndex):this.continueTopLevelAfter(h.job,e,a.id)}async continueLoopAfterBody(t,e,n,i){let r=Kt(t.stepHistory,n);if(!r)throw new Error(`Loop execution ${n} not found`);let s=fe(e.steps,r.stepDefinitionId);if(!s||s.type!=="loop")throw new Error(`Loop step '${r.stepDefinitionId}' not found`);let a=le(t.stepHistory,n),u=r.output?.effectiveMaxIterations??s.maxIterations,c=t;if(Ur(s.until,c.context))c=await this.finishExecution(c,n,s.id,{iterations:i+1});else{let f=i+1,m=await this.runLoopStep(c,e,s,n,a?.parentLoopExecutionId,a?.iterationIndex,f,u);if(m.outcome==="paused"||m.outcome==="failed")return m.job;c=m.job}return a?.parentLoopExecutionId!=null&&a.iterationIndex!=null?this.continueLoopAfterBody(c,e,a.parentLoopExecutionId,a.iterationIndex):this.continueTopLevelAfter(c,e,s.id)}async continueTopLevelAfter(t,e,n){let i=e.steps.findIndex(s=>s.id===n),r=await this.executeStepSequence(t,e,e.steps,void 0,void 0,i+1);return r.outcome==="paused"||r.outcome==="failed"?r.job:this.completeJob(r.job,e)}sequenceForFrameOnJob(t,e,n){if(n.parentLoopExecutionId==null)return e.steps;let i=Kt(t.stepHistory,n.parentLoopExecutionId);if(!i)throw new Error(`Parent loop execution ${n.parentLoopExecutionId} not found`);let r=fe(e.steps,i.stepDefinitionId);if(!r||r.type!=="loop")throw new Error(`Parent loop step '${i.stepDefinitionId}' not found`);return r.steps}async runSubWorkflowStep(t,e,n){if(!t.subjectContext||t.subjectContext.mode!=="collection")throw new b(`sub_workflow steps require subjectContext.mode === 'collection' (job ${t.id})`);let i=t.subjectContext.subjects,r=[];for(let f=0;f<i.length;f++){let m=i[f],y=await this.createJob({workflowId:e.workflowId,subjectContext:{mode:"single",subject:m},inputValues:{},parentJobId:t.id,parentStepExecutionId:n,fanOutIndex:f});r.push(y)}let s=r.map(f=>f.id),a=new Date().toISOString(),u=$(t.stepHistory,n,f=>({...f,status:"waiting_for_children",childJobIds:s})),c=await this.persistJob({...t,status:"waiting_for_children",currentStepId:e.id,currentStepExecutionId:n,stepHistory:u,updatedAt:a});for(let f of r)this.emit({type:"job_started",jobId:f.id,timestamp:a}),this.runJob(f.id);return{outcome:"paused",job:c}}async onChildTerminal(t){let e=await this.jobs.get(t);if(!e?.parentJobId||!e.parentStepExecutionId)return;let n=`${e.parentJobId}:${e.parentStepExecutionId}`;if(!this.childTerminalLocks.has(n)){this.childTerminalLocks.add(n);try{let i=(await this.jobs.list({parentJobId:e.parentJobId,parentStepExecutionId:e.parentStepExecutionId})).filter(E=>E.parentStepExecutionId===e.parentStepExecutionId),r=nn(i,E=>E.fanOutIndex);if(!r?.allTerminal)return;let{activeJobs:s}=r,a=await this.jobs.get(e.parentJobId);if(!a||a.status!=="waiting_for_children"&&a.status!=="failed")return;let u=await this.requireWorkflow(a.workflowId),c=e.parentStepExecutionId,f=Kt(a.stepHistory,c);if(!f||f.type!=="sub_workflow")return;if(s.some(E=>E.status==="failed")){await this.failExecution(a,u,c,f.stepDefinitionId,"One or more child jobs failed");return}let y=s.slice().sort((E,ys)=>(E.fanOutIndex??0)-(ys.fanOutIndex??0)).map(E=>({fanOutIndex:E.fanOutIndex,jobId:E.id,output:E.context})),h=new Date().toISOString();a=await this.persistJob({...a,status:"planning",context:{...a.context,[f.stepDefinitionId]:y},currentStepId:void 0,currentStepExecutionId:void 0,stepHistory:$(a.stepHistory,c,E=>({...E,status:"completed",completedAt:h,output:y})),completedAt:void 0,updatedAt:h}),this.emit({type:"step_completed",jobId:a.id,stepDefinitionId:f.stepDefinitionId,timestamp:h});let I=await this.continueTopLevelAfter(a,u,f.stepDefinitionId)}finally{this.childTerminalLocks.delete(n)}}}async onBatchMemberTerminal(t){let e=await this.jobs.get(t);if(!e?.batchId)return;let n=e.batchId;if(!this.batchTerminalLocks.has(n)){this.batchTerminalLocks.add(n);try{let i=await this.batches.get(e.batchId);if(!i||i.status!=="running")return;let r=await this.jobs.list({batchId:i.id}),s=nn(r,m=>m.fanOutIndex);if(!s||s.groupCount!==i.resolvedSubjects.length||!s.allTerminal)return;let{activeJobs:a}=s,u=Jr(a),c=new Date().toISOString(),f=await this.batches.update(i.id,{status:u,completedAt:c});if(!f)return;if(this.emit({type:"batch_completed",batchId:f.id,summary:a.map(m=>({jobId:m.id,status:m.status})),timestamp:c}),!f.notificationSent){let m=await this.requireWorkflow(f.workflowId),y=f.notificationOverride??m.notificationPolicy,h=u==="completed"?"on_complete":"on_fail";y.triggers.includes(h)&&await this.notifications.send({title:`Batch ${u}: ${m.name}`,body:`JobBatch ${f.id} finished with status '${u}' (${a.length} members)`,batchId:f.id}),await this.batches.update(f.id,{notificationSent:!0})}}finally{this.batchTerminalLocks.delete(n)}}}async resolveSelection(t){if(t.mode==="view")return eo(t.viewId,this.views,{tickets:this.tickets,repo:this.repo,documentation:this.documentation});let e=[];for(let n of t.subjectIds)if(t.subjectType==="ticket"){let i=await this.tickets.get(n);e.push({subjectType:"ticket",...i})}else if(t.subjectType==="pull_request"){let i=await this.repo.get(n);e.push({subjectType:"pull_request",...i})}else if(t.subjectType==="documentation"){let i=await this.documentation.get(n);e.push({subjectType:"documentation",...i})}else throw new b(`Unsupported subjectType: ${t.subjectType}`);return e}async executeAgentStep(t,e,n){let i=e.knowledgeScope?.length?e.knowledgeScope:au,r=await this.resolveKnowledge(i),s=oo(t),a=to(e.objective,s),u=await this.agent.run({objective:a,outputFormat:e.outputFormat,knowledge:r,context:{...s,stepId:e.id},...t.worktreePath?{cwd:t.worktreePath}:{}}),c=qr(e.outputFormat,u.parsed);return this.finishExecution(t,n,e.id,c)}async executeGitStep(t,e,n){let i=pe(e.params,oo(t));switch(e.operation){case"create_worktree":{let r=await this.git.createWorktree(t.id,{repoPath:st(i,"repoPath"),baseBranch:st(i,"baseBranch"),branchName:st(i,"branchName"),...typeof i.worktreePath=="string"?{worktreePath:i.worktreePath}:{}});return this.finishExecution(t,n,e.id,r,{worktreePath:r.worktreePath,branch:r.branch})}case"create_branch":{let r=no(t),s=st(i,"branchName");return await this.git.createBranch(r,{branchName:s,...typeof i.baseBranch=="string"?{baseBranch:i.baseBranch}:{}}),this.finishExecution(t,n,e.id,{branch:s},{branch:s})}case"checkout":{let r=no(t),s=st(i,"branch");return await this.git.checkout(r,{branch:s}),this.finishExecution(t,n,e.id,{branch:s},{branch:s})}case"commit":{let r=no(t),s=await this.git.commit(r,{message:st(i,"message"),addAll:i.addAll!==!1});return this.finishExecution(t,n,e.id,s)}case"push":{let r=no(t);return await this.git.push(r,{...typeof i.remote=="string"?{remote:i.remote}:{},...typeof i.branch=="string"?{branch:i.branch}:{}}),this.finishExecution(t,n,e.id,{remote:typeof i.remote=="string"?i.remote:"origin",branch:typeof i.branch=="string"?i.branch:t.branch})}default:{let r=e.operation;throw new Error(`Unknown git operation: ${r}`)}}}async executeProviderActionStep(t,e,n){if(!t.subjectContext||t.subjectContext.mode!=="single")throw new b(`provider_action steps require subjectContext.mode === 'single' (job ${t.id})`);let i=t.subjectContext.subject,r=i.id,s=pe(e.params??{},oo(t))??{},a;if(i.subjectType==="documentation")switch(e.action){case"get_subject":a=await this.documentation.get(r);break;case"get_content":a=await this.documentation.getContent(r);break;case"get_comments":a=await this.documentation.getComments(r);break;case"post_comment":await this.documentation.postComment(r,st(s,"body")),a={posted:!0};break;case"update_status":throw new Error(`Provider action '${e.action}' is not valid for subject type 'documentation'`);default:{let u=e.action;throw new Error(`Unknown provider action: ${u}`)}}else{let u=i.subjectType==="ticket"?this.tickets:i.subjectType==="pull_request"?this.repo:null;if(!u)throw new Error(`Unsupported subjectType for provider_action: ${i.subjectType}`);switch(e.action){case"get_subject":a=await u.get(r);break;case"get_comments":a=await u.getComments(r);break;case"post_comment":await u.postComment(r,st(s,"body")),a={posted:!0};break;case"update_status":await u.updateStatus(r,st(s,"status")),a={status:st(s,"status")};break;case"get_content":throw new Error(`Provider action 'get_content' is not valid for subject type '${i.subjectType}'`);default:{let c=e.action;throw new Error(`Unknown provider action: ${c}`)}}}return this.finishExecution(t,n,e.id,a)}async executeShellStep(t,e,n){let i=to(e.command,oo(t)),r=t.worktreePath??process.cwd();try{let s=await su(i,{cwd:r,windowsHide:!0});return this.finishExecution(t,n,e.id,{exitCode:0,stdout:String(s.stdout??""),stderr:String(s.stderr??"")})}catch(s){let a=s,u=a.stderr??"",c=a.stdout??"",f=typeof a.code=="number"?a.code:Number.parseInt(String(a.code??"1"),10)||1;throw new Error(`shell command failed (exit ${f}, cwd=${r}): ${u||c||a.message||i}`)}}async pauseForInteraction(t,e,n,i){let r=new Date().toISOString(),s=cu(e,n.id),a=s!=null?t.context[s]:void 0,u=$(t.stepHistory,i,y=>({...y,status:"pending"})),c=await this.persistJob({...t,status:"waiting_for_human",currentStepId:n.id,currentStepExecutionId:i,stepHistory:u,updatedAt:r}),f=Nr(n.interaction,a);return this.emit({type:"waiting_for_human",jobId:c.id,stepDefinitionId:n.id,interaction:n.interaction,data:a,questions:f,timestamp:r}),e.notificationPolicy.triggers.includes("on_needs_input")&&n.notify!==!1&&await this.notifications.send({title:`Input needed: ${e.name}`,body:`Job ${c.id} is waiting for human input on step '${n.id}'`,jobId:c.id}),c}async finishExecution(t,e,n,i,r={}){let s=new Date().toISOString(),a=$(t.stepHistory,e,c=>({...c,status:"completed",completedAt:s,output:i})),u=await this.persistJob({...t,...r,context:{...t.context,[n]:i},stepHistory:a,updatedAt:s});return this.emit({type:"step_completed",jobId:u.id,stepDefinitionId:n,timestamp:s}),u}async failExecution(t,e,n,i,r){return this.failJob(t,e,n,i,new Error(r))}async completeJob(t,e){let n=new Date().toISOString(),i=await this.persistJob({...t,status:"completed",currentStepId:void 0,currentStepExecutionId:void 0,completedAt:n,updatedAt:n});return this.emit({type:"job_completed",jobId:i.id,timestamp:n}),await this.onBatchMemberTerminal(i.id),!i.batchId&&e.notificationPolicy.triggers.includes("on_complete")&&await this.notifications.send({title:`Job completed: ${e.name}`,body:`Job ${i.id} completed successfully`,jobId:i.id}),i}async failJob(t,e,n,i,r){let s=r instanceof Error?r.message:String(r),a=new Date().toISOString(),u=$(t.stepHistory,n,f=>({...f,status:"failed",completedAt:a,error:s})),c=await this.persistJob({...t,status:"failed",stepHistory:u,completedAt:a,updatedAt:a});return this.emit({type:"step_failed",jobId:c.id,stepDefinitionId:i,error:s,timestamp:a}),this.emit({type:"job_failed",jobId:c.id,error:s,timestamp:a}),await this.onBatchMemberTerminal(c.id),!c.batchId&&e.notificationPolicy.triggers.includes("on_fail")&&await this.notifications.send({title:`Job failed: ${e.name}`,body:`Job ${c.id} failed on step '${i}': ${s}`,jobId:c.id}),c}async resolveSubjectContext(t,e){if(t.appliesTo==="none")return;let n=uu(t.appliesTo);if(!e)throw new Error(`Workflow '${t.id}' applies to '${n}' but no subjectId was provided`);if(n==="ticket")return{mode:"single",subject:{subjectType:"ticket",...await this.tickets.get(e)}};if(n==="pull_request")return{mode:"single",subject:{subjectType:"pull_request",...await this.repo.get(e)}};if(n==="documentation")return{mode:"single",subject:{subjectType:"documentation",...await this.documentation.get(e)}};throw new Error(`Unsupported subjectType for workflow subject resolution: ${n}`)}async resolveKnowledge(t){let e=[];for(let n of t)e.push(...await this.knowledge.resolve(n));return e}async requireWorkflow(t){let e=await this.workflows.get(t);if(!e)throw new g(`Workflow not found: ${t}`);return e}async persistJob(t){let e=await this.jobs.update(t.id,{status:t.status,context:t.context,currentStepId:t.currentStepId,currentStepExecutionId:t.currentStepExecutionId,stepHistory:t.stepHistory,worktreePath:t.worktreePath,branch:t.branch,updatedAt:t.updatedAt,completedAt:t.completedAt});if(!e)throw new Error(`Failed to persist job ${t.id}`);return e}emit(t){this.events.emit(t)}};Q=eu([nu(),U(0,M(L)),U(1,M(x)),U(2,M(J)),U(3,M(B)),U(4,M(z)),U(5,M(Pt)),U(6,M(At)),U(7,M(kt)),U(8,M(ee)),U(9,M(re)),U(10,M(ie)),U(11,M(pt)),ou("design:paramtypes",[L,x,J,B,z,Object,Object,Object,Object,Object,Object,pt])],Q)});import{Module as pu}from"@nestjs/common";var du,Xt,an=p(()=>{"use strict";de();Ge();Qe();Ar();ro();du=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},Xt=class{};Xt=du([pu({imports:[it,jt,It,Ze],providers:[Q],exports:[Q]})],Xt)});import{Catch as fu}from"@nestjs/common";var lu,io,Vr=p(()=>{"use strict";Y();lu=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},io=class{catch(t,e){e.switchToHttp().getResponse().status(t.httpStatus).json({error:t.message})}};io=lu([fu(Ct)],io)});import{z as V}from"zod";var at,Ht,so,ao,cn=p(()=>{"use strict";at=V.enum(["ticket","pull_request","documentation"]),Ht=V.object({id:V.string().min(1),name:V.string().min(1),subjectType:at,query:V.record(V.string(),V.unknown()),description:V.string().optional(),order:V.number().int().nonnegative()}),so=Ht.omit({order:!0}),ao=V.object({viewIds:V.array(V.string().min(1)).min(1)})});var Kr=p(()=>{"use strict";cn()});function mu(o){let t=o.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"");return t.length>0?t:"step"}function Xr(o,t){let e=mu(o);if(!t.has(e))return e;let n=2;for(;t.has(`${e}-${n}`);)n+=1;return`${e}-${n}`}function Hr(o,t){for(let e of o)e.id&&t.push(e.id),e.type==="loop"&&Array.isArray(e.steps)&&Hr(e.steps,t)}function Wr(o){let t=[];Hr(o,t);let e=new Map;for(let n of t)e.set(n,(e.get(n)??0)+1);return[...e.entries()].filter(([,n])=>n>1).map(([n])=>n)}function Gr(o){let t=new Set,e=n=>{for(let i of n)i.id&&t.add(i.id),i.type==="loop"&&Array.isArray(i.steps)&&e(i.steps)};return e(o),t}var un=p(()=>{"use strict"});import{z as l}from"zod";var hu,me,bu,xt,zr,Yr,Qr,Zr,ti,ei,oi,ni,gu,ri,ii,he,yu,wu,Su,_u,ju,Iu,xu,si,Wt,ai=p(()=>{"use strict";cn();un();hu=l.enum(["on_fail","on_complete","on_needs_input"]),me=l.object({triggers:l.array(hu),messageTemplate:l.string().optional()}),bu=l.object({name:l.string().min(1),label:l.string().min(1),type:l.enum(["string","number","boolean","select"]),options:l.array(l.string()).optional(),required:l.boolean(),defaultValue:l.unknown().optional()}),xt=l.string().min(1),zr=l.object({type:l.literal("agent"),id:l.string().min(1),name:xt,objective:l.string().min(1),knowledgeScope:l.array(l.enum(["user","organization","project"])).optional(),outputFormat:l.enum(["questionnaire","confirmation","comment_suggestions","free_text"])}),Yr=l.object({type:l.literal("interaction"),id:l.string().min(1),name:xt,interaction:l.union([l.literal("questionnaire"),l.literal("confirmation"),l.literal("conversation")]),notify:l.boolean().optional()}),Qr=l.object({type:l.literal("shell"),id:l.string().min(1),name:xt,command:l.string().min(1)}),Zr=l.object({type:l.literal("git"),id:l.string().min(1),name:xt,operation:l.enum(["create_worktree","checkout","create_branch","commit","push"]),params:l.record(l.string(),l.unknown())}),ti=l.object({type:l.literal("provider_action"),id:l.string().min(1),name:xt,action:l.enum(["get_subject","get_comments","post_comment","update_status","get_content"]),params:l.record(l.string(),l.unknown()).optional()}),ei=l.object({type:l.literal("sub_workflow"),id:l.string().min(1),name:xt,workflowId:l.string().min(1),forEach:l.literal("selection")}),oi=l.discriminatedUnion("type",[l.object({type:l.literal("field_empty"),stepId:l.string().min(1),field:l.string().min(1)}),l.object({type:l.literal("field_equals"),stepId:l.string().min(1),field:l.string().min(1),value:l.unknown()})]),ni=l.discriminatedUnion("action",[l.object({action:l.literal("fail")}),l.object({action:l.literal("continue")}),l.object({action:l.literal("ask_human")})]),gu=l.object({type:l.literal("loop"),id:l.string().min(1),name:xt,steps:l.array(l.lazy(()=>ri)),until:oi,maxIterations:l.number().int().nonnegative(),onMaxIterations:ni}),ri=l.lazy(()=>l.discriminatedUnion("type",[Zr,ti,Qr,zr,Yr,ei,gu])),ii=l.object({id:l.string().min(1),name:l.string().min(1),description:l.string().optional(),appliesTo:l.union([at,l.array(at),l.literal("none")]),cardinality:l.enum(["single","batch","aggregate"]),inputSchema:l.array(bu),steps:l.array(ri),notificationPolicy:me}),he=ii.superRefine((o,t)=>{let e=Wr(o.steps);e.length!==0&&t.addIssue({code:"custom",path:["steps"],message:`Duplicate step id(s): ${e.join(", ")}`})}),yu=zr.extend({id:l.string().min(1).optional()}),wu=Yr.extend({id:l.string().min(1).optional()}),Su=Qr.extend({id:l.string().min(1).optional()}),_u=Zr.extend({id:l.string().min(1).optional()}),ju=ti.extend({id:l.string().min(1).optional()}),Iu=ei.extend({id:l.string().min(1).optional()}),xu=l.object({type:l.literal("loop"),id:l.string().min(1).optional(),name:xt,steps:l.array(l.lazy(()=>si)),until:oi,maxIterations:l.number().int().nonnegative(),onMaxIterations:ni}),si=l.lazy(()=>l.discriminatedUnion("type",[_u,ju,Su,yu,wu,Iu,xu])),Wt=ii.omit({id:!0,steps:!0}).extend({id:l.string().min(1).optional(),steps:l.array(si)})});var ci=p(()=>{"use strict";ai();un()});var ui=p(()=>{"use strict"});var di=p(()=>{"use strict";ui()});var pi=p(()=>{"use strict"});var li=p(()=>{"use strict";pi()});var fi=p(()=>{"use strict"});var mi=p(()=>{"use strict";fi()});import{z as k}from"zod";var Gt,hi=p(()=>{"use strict";Gt=k.object({id:k.string().min(1),workflowId:k.string().min(1),viewId:k.string().min(1),trigger:k.object({type:k.literal("cron"),cadence:k.string().min(1)}),notificationOverride:k.object({triggers:k.array(k.enum(["on_fail","on_complete","on_needs_input"])),messageTemplate:k.string().optional()}).optional(),missedFirePolicy:k.enum(["skip","catch_up"]),enabled:k.boolean(),lastFiredAt:k.string().optional(),createdAt:k.string()})});var bi=p(()=>{"use strict";hi()});import{z as K}from"zod";var gi,yi,wi,Si,dn,co,_i=p(()=>{"use strict";gi=K.string().min(1).refine(o=>{try{let t=new URL(o);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}},{message:"Must be an http(s) URL"}).optional(),yi=K.object({ticket:K.enum(["jira","manual"]).optional(),repo:K.enum(["bitbucket","manual"]).optional(),agent:K.enum(["claude","cursor"]).optional()}),wi=K.object({baseUrl:gi,email:K.string().min(1).optional()}),Si=K.object({baseUrl:gi,email:K.string().min(1).optional(),workspace:K.string().min(1).optional()}),dn=K.object({activeProviders:yi.optional(),jira:wi.optional(),bitbucket:Si.optional()}),co=K.object({activeProviders:yi.optional(),jira:wi.partial().optional(),bitbucket:Si.partial().optional()})});var ji=p(()=>{"use strict";_i()});var Ii=p(()=>{"use strict"});var xi=p(()=>{"use strict";Ii()});var lt=p(()=>{"use strict";Kr();ci();di();li();mi();bi();ji();xi()});var j,Et=p(()=>{"use strict";Y();j=class{schema;constructor(t){this.schema=t}transform(t){let e=this.schema.safeParse(t);if(!e.success){let n=e.error.issues.map(i=>`${i.path.join(".")||"(root)"}: ${i.message}`).join("; ");throw new b(`Validation failed: ${n}`)}return e.data}}});import{randomUUID as Eu}from"node:crypto";function vu(){return Eu()}function pn(o){let t=o.id??vu(),e=Gr(o.steps),n=Ei(o.steps,e);return{...o,id:t,steps:n}}function Ei(o,t){return o.map(e=>{let n=e.id;return n||(n=Xr(e.name,t),t.add(n)),e.type==="loop"?{...e,id:n,steps:Ei(e.steps,t)}:{...e,id:n}})}var vi=p(()=>{"use strict";lt()});import{Body as Oi,Controller as Tu,Delete as Ou,Get as Ri,HttpCode as Ru,Inject as Ti,Param as ln,Patch as Pu,Post as Au,Query as ku}from"@nestjs/common";var zt,T,vt,Nu,ft,Pi=p(()=>{"use strict";lt();Be();Ut();Y();Et();vi();zt=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},T=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},vt=function(o,t){return function(e,n){t(e,n,o)}},Nu=new Set(["completed","failed","cancelled"]),ft=class{workflows;jobs;constructor(t,e){this.workflows=t,this.jobs=e}async list(t){if(t!=null&&t!==""&&t!=="single"&&t!=="batch"&&t!=="aggregate")throw new b(`Invalid cardinality filter: ${t}`);return this.workflows.list(t?{cardinality:t}:{})}async get(t){let e=await this.workflows.get(t);if(!e)throw new g(`Workflow not found: ${t}`);return e}async create(t){let e=pn(t),n=he.safeParse(e);if(!n.success){let i=n.error.issues.map(r=>`${r.path.join(".")||"(root)"}: ${r.message}`).join("; ");throw new b(`Validation failed: ${i}`)}return this.workflows.create(n.data)}async update(t,e){let n=pn({...e,id:t}),i=he.safeParse(n);if(!i.success){let u=i.error.issues.map(c=>`${c.path.join(".")||"(root)"}: ${c.message}`).join("; ");throw new b(`Validation failed: ${u}`)}let{id:r,...s}=i.data,a=await this.workflows.update(t,s);if(!a)throw new g(`Workflow not found: ${t}`);return a}async remove(t){if(!await this.workflows.get(t))throw new g(`Workflow not found: ${t}`);let i=(await this.jobs.list({workflowId:t})).filter(s=>!Nu.has(s.status));if(i.length>0){let s=i.length===1?"Job":"Jobs";throw new Dt(`Cannot delete workflow ${t}: ${i.length} non-terminal ${s} still reference it`)}if(!await this.workflows.delete(t))throw new g(`Workflow not found: ${t}`)}};zt([Ri(),vt(0,ku("cardinality")),T("design:type",Function),T("design:paramtypes",[String]),T("design:returntype",Promise)],ft.prototype,"list",null);zt([Ri(":id"),vt(0,ln("id")),T("design:type",Function),T("design:paramtypes",[String]),T("design:returntype",Promise)],ft.prototype,"get",null);zt([Au(),vt(0,Oi(new j(Wt))),T("design:type",Function),T("design:paramtypes",[Object]),T("design:returntype",Promise)],ft.prototype,"create",null);zt([Pu(":id"),vt(0,ln("id")),vt(1,Oi(new j(Wt))),T("design:type",Function),T("design:paramtypes",[String,Object]),T("design:returntype",Promise)],ft.prototype,"update",null);zt([Ou(":id"),Ru(204),vt(0,ln("id")),T("design:type",Function),T("design:paramtypes",[String]),T("design:returntype",Promise)],ft.prototype,"remove",null);ft=zt([Tu("workflows"),vt(0,Ti(L)),vt(1,Ti(x)),T("design:paramtypes",[L,x])],ft)});import{Body as fn,Controller as Cu,Delete as Du,Get as mn,HttpCode as $u,Inject as uo,Param as po,Patch as Ai,Post as qu,Query as Lu}from"@nestjs/common";var Tt,_,X,Z,ki=p(()=>{"use strict";lt();Je();Y();Et();Ie();Ee();Te();rn();Tt=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},_=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},X=function(o,t){return function(e,n){t(e,n,o)}},Z=class{views;tickets;repo;documentation;constructor(t,e,n,i){this.views=t,this.tickets=e,this.repo=n,this.documentation=i}async list(t){if(t!=null&&t!==""){let e=at.safeParse(t);if(!e.success)throw new b(`Invalid subjectType filter: ${t}`);return this.views.list({subjectType:e.data})}return this.views.list({})}async reorder(t){let e=[];for(let r of t.viewIds){let s=await this.views.get(r);if(!s)throw new b(`Unknown view id in reorder: ${r}`);e.push(s)}if(new Set(e.map(r=>r.subjectType)).size!==1)throw new b("All viewIds in a reorder request must share the same subjectType");return await this.views.reorder(t.viewIds)}async listSubjects(t){return eo(t,this.views,{tickets:this.tickets,repo:this.repo,documentation:this.documentation})}async get(t){let e=await this.views.get(t);if(!e)throw new g(`SubjectView not found: ${t}`);return e}async create(t){return this.views.create(t)}async update(t,e){let n=await this.views.update(t,e);if(!n)throw new g(`SubjectView not found: ${t}`);return n}async remove(t){if(!await this.views.delete(t))throw new g(`SubjectView not found: ${t}`)}};Tt([mn(),X(0,Lu("subjectType")),_("design:type",Function),_("design:paramtypes",[String]),_("design:returntype",Promise)],Z.prototype,"list",null);Tt([Ai("reorder"),X(0,fn(new j(ao))),_("design:type",Function),_("design:paramtypes",[Object]),_("design:returntype",Promise)],Z.prototype,"reorder",null);Tt([mn(":id/subjects"),X(0,po("id")),_("design:type",Function),_("design:paramtypes",[String]),_("design:returntype",Promise)],Z.prototype,"listSubjects",null);Tt([mn(":id"),X(0,po("id")),_("design:type",Function),_("design:paramtypes",[String]),_("design:returntype",Promise)],Z.prototype,"get",null);Tt([qu(),X(0,fn(new j(so))),_("design:type",Function),_("design:paramtypes",[Object]),_("design:returntype",Promise)],Z.prototype,"create",null);Tt([Ai(":id"),X(0,po("id")),X(1,fn(new j(Ht.partial().omit({id:!0,order:!0})))),_("design:type",Function),_("design:paramtypes",[String,Object]),_("design:returntype",Promise)],Z.prototype,"update",null);Tt([Du(":id"),$u(204),X(0,po("id")),_("design:type",Function),_("design:paramtypes",[String]),_("design:returntype",Promise)],Z.prototype,"remove",null);Z=Tt([Cu("views"),X(0,uo(B)),X(1,uo(Pt)),X(2,uo(At)),X(3,uo(kt)),_("design:paramtypes",[B,Object,Object,Object])],Z)});function lo(o,t,e=50){let n=o!=null&&o!==""?Number(o):e,i=t!=null&&t!==""?Number(t):0;return!Number.isFinite(n)||n<1?{limit:e,offset:Math.max(0,i||0)}:!Number.isFinite(i)||i<0?{limit:n,offset:0}:{limit:Math.floor(n),offset:Math.floor(i)}}function fo(o,t,e){return o.slice(e,e+t)}var hn=p(()=>{"use strict"});import{z as Ot}from"zod";var mo,ho,bn=p(()=>{"use strict";mo=Ot.object({workflowId:Ot.string().min(1),subjectId:Ot.string().min(1).optional(),inputValues:Ot.record(Ot.string(),Ot.unknown())}),ho=Ot.object({response:Ot.unknown()})});import{Body as Ci,Controller as Bu,Get as Di,Inject as Ni,Param as gn,Post as yn,Query as $t}from"@nestjs/common";import"zod";var Yt,O,N,Ju,mt,$i=p(()=>{"use strict";ro();Ut();Y();Et();hn();bn();Yt=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},O=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},N=function(o,t){return function(e,n){t(e,n,o)}},Ju=["pending","planning","waiting_for_human","waiting_for_children","implementing","testing","completed","failed","cancelled"],mt=class{jobs;runner;constructor(t,e){this.jobs=t,this.runner=e}async list(t,e,n,i,r,s,a){if(e!=null&&e!==""&&!Ju.includes(e))throw new b(`Invalid status filter: ${e}`);if(r!=null&&r!==""&&r!=="true"&&r!=="false")throw new b(`Invalid topLevelOnly filter: ${r}`);let{limit:u,offset:c}=lo(s,a),f=await this.jobs.list({...t?{workflowId:t}:{},...e?{status:e}:{},...n?{batchId:n}:{},...i?{parentJobId:i}:{},...r==="true"?{topLevelOnly:!0}:{}});return fo(f,u,c)}async get(t){let e=await this.jobs.get(t);if(!e)throw new g(`Job not found: ${t}`);return e}async create(t){return this.runner.start({workflowId:t.workflowId,...t.subjectId?{subjectId:t.subjectId}:{},inputValues:t.inputValues})}async resume(t,e){return this.runner.resume(t,e.response)}async retry(t){return this.runner.retryFailedJob(t)}};Yt([Di(),N(0,$t("workflowId")),N(1,$t("status")),N(2,$t("batchId")),N(3,$t("parentJobId")),N(4,$t("topLevelOnly")),N(5,$t("limit")),N(6,$t("offset")),O("design:type",Function),O("design:paramtypes",[String,String,String,String,String,String,String]),O("design:returntype",Promise)],mt.prototype,"list",null);Yt([Di(":id"),N(0,gn("id")),O("design:type",Function),O("design:paramtypes",[String]),O("design:returntype",Promise)],mt.prototype,"get",null);Yt([yn(),N(0,Ci(new j(mo))),O("design:type",Function),O("design:paramtypes",[Object]),O("design:returntype",Promise)],mt.prototype,"create",null);Yt([yn(":id/resume"),N(0,gn("id")),N(1,Ci(new j(ho))),O("design:type",Function),O("design:paramtypes",[String,Object]),O("design:returntype",Promise)],mt.prototype,"resume",null);Yt([yn(":id/retry"),N(0,gn("id")),O("design:type",Function),O("design:paramtypes",[String]),O("design:returntype",Promise)],mt.prototype,"retry",null);mt=Yt([Bu("jobs"),N(0,Ni(x)),N(1,Ni(Q)),O("design:paramtypes",[x,Q])],mt)});import{z as C}from"zod";var bo,go,wn=p(()=>{"use strict";lt();bo=C.discriminatedUnion("mode",[C.object({mode:C.literal("view"),viewId:C.string().min(1)}),C.object({mode:C.literal("manual"),subjectType:at,subjectIds:C.array(C.string().min(1))})]),go=C.object({workflowId:C.string().min(1),selection:bo,triggeredBy:C.enum(["schedule","view_bulk","multiselect"]),notificationOverride:me.optional(),inputValues:C.record(C.string(),C.unknown())})});import{Body as Fu,Controller as Uu,Get as jn,Inject as Sn,Param as qi,Post as Mu,Query as _n}from"@nestjs/common";import"zod";var be,q,ht,Rt,Li=p(()=>{"use strict";ro();Fe();Ut();Y();Et();hn();wn();be=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},q=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},ht=function(o,t){return function(e,n){t(e,n,o)}},Rt=class{batches;jobs;runner;constructor(t,e,n){this.batches=t,this.jobs=e,this.runner=n}async list(t,e,n){let{limit:i,offset:r}=lo(e,n),s=await this.batches.list(t?{workflowId:t}:{});return fo(s,i,r)}async get(t){let e=await this.batches.get(t);if(!e)throw new g(`JobBatch not found: ${t}`);return e}async listJobs(t){if(!await this.batches.get(t))throw new g(`JobBatch not found: ${t}`);return this.jobs.list({batchId:t})}async launch(t){let e=await this.runner.launch({workflowId:t.workflowId,selection:t.selection,triggeredBy:t.triggeredBy,...t.notificationOverride?{notificationOverride:t.notificationOverride}:{},inputValues:t.inputValues});return"resolvedSubjects"in e&&"jobIds"in e?{kind:"batch",batch:e}:{kind:"job",job:e}}};be([jn(),ht(0,_n("workflowId")),ht(1,_n("limit")),ht(2,_n("offset")),q("design:type",Function),q("design:paramtypes",[String,String,String]),q("design:returntype",Promise)],Rt.prototype,"list",null);be([jn(":id"),ht(0,qi("id")),q("design:type",Function),q("design:paramtypes",[String]),q("design:returntype",Promise)],Rt.prototype,"get",null);be([jn(":id/jobs"),ht(0,qi("id")),q("design:type",Function),q("design:paramtypes",[String]),q("design:returntype",Promise)],Rt.prototype,"listJobs",null);be([Mu(),ht(0,Fu(new j(go))),q("design:type",Function),q("design:paramtypes",[Object]),q("design:returntype",Promise)],Rt.prototype,"launch",null);Rt=be([Uu("batches"),ht(0,Sn(J)),ht(1,Sn(x)),ht(2,Sn(Q)),q("design:paramtypes",[J,x,Q])],Rt)});import{Body as Bi,Controller as Vu,Delete as Ku,Get as Ji,HttpCode as Xu,Inject as Hu,Param as In,Patch as Wu,Post as Gu,Query as zu}from"@nestjs/common";var Qt,R,qt,bt,Fi=p(()=>{"use strict";lt();Xo();Y();Et();Qt=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},R=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},qt=function(o,t){return function(e,n){t(e,n,o)}},bt=class{schedules;constructor(t){this.schedules=t}async list(t){if(t==null||t==="")return this.schedules.list();if(t!=="true"&&t!=="false")throw new b(`Invalid enabled filter: ${t}`);return this.schedules.list({enabled:t==="true"})}async get(t){let e=await this.schedules.get(t);if(!e)throw new g(`Schedule not found: ${t}`);return e}async create(t){return this.schedules.create(t)}async update(t,e){let n=await this.schedules.update(t,e);if(!n)throw new g(`Schedule not found: ${t}`);return n}async remove(t){if(!await this.schedules.delete(t))throw new g(`Schedule not found: ${t}`)}};Qt([Ji(),qt(0,zu("enabled")),R("design:type",Function),R("design:paramtypes",[String]),R("design:returntype",Promise)],bt.prototype,"list",null);Qt([Ji(":id"),qt(0,In("id")),R("design:type",Function),R("design:paramtypes",[String]),R("design:returntype",Promise)],bt.prototype,"get",null);Qt([Gu(),qt(0,Bi(new j(Gt))),R("design:type",Function),R("design:paramtypes",[Object]),R("design:returntype",Promise)],bt.prototype,"create",null);Qt([Wu(":id"),qt(0,In("id")),qt(1,Bi(new j(Gt.partial().omit({id:!0})))),R("design:type",Function),R("design:paramtypes",[String,Object]),R("design:returntype",Promise)],bt.prototype,"update",null);Qt([Ku(":id"),Xu(204),qt(0,In("id")),R("design:type",Function),R("design:paramtypes",[String]),R("design:returntype",Promise)],bt.prototype,"remove",null);bt=Qt([Vu("schedules"),qt(0,Hu(dt)),R("design:paramtypes",[dt])],bt)});import{Controller as Yu,Inject as Qu,Query as Ui,Sse as Zu}from"@nestjs/common";import{Observable as Vi}from"rxjs";var Mi,yo,xn,ge,Ki=p(()=>{"use strict";Ye();Mi=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},yo=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},xn=function(o,t){return function(e,n){t(e,n,o)}},ge=class{events;constructor(t){this.events=t}stream(t,e){return new Vi(n=>{let i=this.events.subscribe(r=>{let s=r;t!=null&&t!==""&&(!("jobId"in s)||s.jobId!==t)||e!=null&&e!==""&&(!("batchId"in s)||s.batchId!==e)||n.next({data:s})});return()=>{i()}})}};Mi([Zu(),xn(0,Ui("jobId")),xn(1,Ui("batchId")),yo("design:type",Function),yo("design:paramtypes",[String,String]),yo("design:returntype",Vi)],ge.prototype,"stream",null);ge=Mi([Yu("events"),xn(0,Qu(z)),yo("design:paramtypes",[z])],ge)});import{extendZodWithOpenApi as td}from"@asteasolutions/zod-to-openapi";import{z as ed}from"zod";var Xi=p(()=>{"use strict";td(ed)});import{z as Hi}from"zod";var wo,En=p(()=>{"use strict";wo=Hi.object({value:Hi.string().min(1)})});import{z as d}from"zod";function yd(o){let t=d.toJSONSchema(o),{$schema:e,...n}=t;return n}function zi(o){let t=(e,n)=>o.registerComponent("schemas",e,yd(n)).ref;return{WorkflowDefinition:t("WorkflowDefinition",he),WorkflowDefinitionInput:t("WorkflowDefinitionInput",Wt),UpdateWorkflowBody:t("UpdateWorkflowBody",fd),SubjectView:t("SubjectView",Ht),CreateSubjectViewBody:t("CreateSubjectViewBody",so),ReorderViewsBody:t("ReorderViewsBody",ao),UpdateViewBody:t("UpdateViewBody",md),Schedule:t("Schedule",Gt),UpdateScheduleBody:t("UpdateScheduleBody",hd),EngineSettings:t("EngineSettings",dn),UpdateSettingsBody:t("UpdateSettingsBody",bd),SettingsPatchResponse:t("SettingsPatchResponse",gd),SetSecretBody:t("SetSecretBody",wo),CreateJobBody:t("CreateJobBody",mo),ResumeJobBody:t("ResumeJobBody",ho),LaunchBody:t("LaunchBody",go),Job:t("Job",Wi),JobBatch:t("JobBatch",Gi),LaunchResponse:t("LaunchResponse",cd),HealthResponse:t("HealthResponse",ud),ProviderStatus:t("ProviderStatus",dd),ErrorResponse:t("ErrorResponse",pd),EngineEvent:t("EngineEvent",ld),Subject:t("Subject",So)}}var od,nd,rd,id,So,sd,ad,Wi,Gi,cd,ud,dd,pd,ld,fd,md,hd,bd,gd,P,vn,Tn=p(()=>{"use strict";Xi();lt();bn();wn();En();od=d.enum(["pending","planning","waiting_for_human","waiting_for_children","implementing","testing","completed","failed","cancelled"]),nd=d.object({subjectType:d.literal("ticket"),id:d.string(),source:d.enum(["jira","azure-devops","manual"]),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()}),rd=d.object({subjectType:d.literal("pull_request"),id:d.string(),source:d.enum(["bitbucket","github","manual"]),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()}),id=d.object({subjectType:d.literal("documentation"),id:d.string(),source:d.enum(["confluence","notion","github_wiki","gitlab_wiki","azure_wiki","web","manual"]),title:d.string(),url:d.string().optional(),raw:d.record(d.string(),d.unknown()).optional()}),So=d.discriminatedUnion("subjectType",[nd,rd,id]),sd=d.discriminatedUnion("mode",[d.object({mode:d.literal("single"),subject:So}),d.object({mode:d.literal("collection"),subjects:d.array(So)})]),ad=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()}),Wi=d.object({id:d.string(),workflowId:d.string(),status:od,subjectContext:sd.optional(),selection:bo.optional(),batchId:d.string().optional(),parentJobId:d.string().optional(),parentStepExecutionId:d.string().optional(),fanOutIndex:d.number().int().optional(),retryOf:d.string().optional(),context:d.record(d.string(),d.unknown()),worktreePath:d.string().optional(),branch:d.string().optional(),currentStepId:d.string().optional(),currentStepExecutionId:d.string().optional(),stepHistory:d.array(ad),createdAt:d.string(),updatedAt:d.string(),completedAt:d.string().optional()}),Gi=d.object({id:d.string(),workflowId:d.string(),selection:bo,resolvedSubjects:d.array(So),jobIds:d.array(d.string()),status:d.enum(["running","completed","completed_with_issues","failed"]),triggeredBy:d.enum(["schedule","view_bulk","multiselect"]),scheduleId:d.string().optional(),notificationOverride:me.optional(),notificationSent:d.boolean(),createdAt:d.string(),completedAt:d.string().optional()}),cd=d.discriminatedUnion("kind",[d.object({kind:d.literal("job"),job:Wi}),d.object({kind:d.literal("batch"),batch:Gi})]),ud=d.object({ok:d.boolean(),service:d.string(),timestamp:d.string()}),dd=d.object({providerId:d.string(),secretKey:d.string(),configured:d.boolean()}),pd=d.object({error:d.string()}),ld=d.object({type:d.string(),timestamp:d.string()}).passthrough(),fd=Wt,md=Ht.partial().omit({id:!0,order:!0}),hd=Gt.partial().omit({id:!0}),bd=co,gd=d.object({settings:dn,restartRequired:d.boolean()}),P=d.object({id:d.string().min(1)}),vn=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 A}from"zod";function w(o,t){return{description:t,content:{"application/json":{schema:o}}}}function gt(o){return{type:"array",items:o}}function S(o,...t){let e={400:"Validation error",404:"Resource not found",409:"Conflict"};return Object.fromEntries(t.map(n=>[String(n),w(o.ErrorResponse,e[n]??"Error")]))}function Yi(o,t){o.registerPath({method:"get",path:"/health",tags:["Health"],summary:"Health check",responses:{200:w(t.HealthResponse,"Service is healthy")}}),o.registerPath({method:"get",path:"/workflows",tags:["Workflows"],summary:"List workflow definitions",request:{query:A.object({cardinality:A.enum(["single","batch","aggregate"]).optional()})},responses:{200:w(gt(t.WorkflowDefinition),"Workflow definitions"),...S(t,400)}}),o.registerPath({method:"get",path:"/workflows/{id}",tags:["Workflows"],summary:"Get a workflow definition",request:{params:P},responses:{200:w(t.WorkflowDefinition,"Workflow definition"),...S(t,404)}}),o.registerPath({method:"post",path:"/workflows",tags:["Workflows"],summary:"Create a workflow definition",request:{body:{required:!0,content:{"application/json":{schema:t.WorkflowDefinitionInput}}}},responses:{201:w(t.WorkflowDefinition,"Created workflow definition"),...S(t,400)}}),o.registerPath({method:"patch",path:"/workflows/{id}",tags:["Workflows"],summary:"Update a workflow definition",request:{params:P,body:{required:!0,content:{"application/json":{schema:t.UpdateWorkflowBody}}}},responses:{200:w(t.WorkflowDefinition,"Updated workflow definition"),...S(t,400,404)}}),o.registerPath({method:"delete",path:"/workflows/{id}",tags:["Workflows"],summary:"Delete a workflow definition",description:"Rejected with 409 if any non-terminal Job still references the workflow. Terminal Jobs (completed, failed, cancelled) do not block deletion.",request:{params:P},responses:{204:{description:"Workflow deleted"},...S(t,404,409)}}),o.registerPath({method:"get",path:"/views",tags:["Views"],summary:"List subject views",request:{query:A.object({subjectType:at.optional()})},responses:{200:w(gt(t.SubjectView),"Subject views"),...S(t,400)}}),o.registerPath({method:"get",path:"/views/{id}",tags:["Views"],summary:"Get a subject view",request:{params:P},responses:{200:w(t.SubjectView,"Subject view"),...S(t,404)}}),o.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:w(gt(t.Subject),"Matching subjects"),...S(t,404,400)}}),o.registerPath({method:"patch",path:"/views/reorder",tags:["Views"],summary:"Reorder views within a subject type group",request:{body:{required:!0,content:{"application/json":{schema:t.ReorderViewsBody}}}},responses:{200:w(gt(t.SubjectView),"Reordered views for the subject type"),...S(t,400)}}),o.registerPath({method:"post",path:"/views",tags:["Views"],summary:"Create a subject view",request:{body:{required:!0,content:{"application/json":{schema:t.CreateSubjectViewBody}}}},responses:{201:w(t.SubjectView,"Created subject view"),...S(t,400)}}),o.registerPath({method:"patch",path:"/views/{id}",tags:["Views"],summary:"Update a subject view",request:{params:P,body:{required:!0,content:{"application/json":{schema:t.UpdateViewBody}}}},responses:{200:w(t.SubjectView,"Updated subject view"),...S(t,400,404)}}),o.registerPath({method:"delete",path:"/views/{id}",tags:["Views"],summary:"Delete a subject view",request:{params:P},responses:{204:{description:"Subject view deleted"},...S(t,404)}}),o.registerPath({method:"get",path:"/jobs",tags:["Jobs"],summary:"List jobs",request:{query:vn.extend({workflowId:A.string().optional(),status:A.enum(["pending","planning","waiting_for_human","waiting_for_children","implementing","testing","completed","failed","cancelled"]).optional(),batchId:A.string().optional(),parentJobId:A.string().optional(),topLevelOnly:A.enum(["true","false"]).optional().openapi({description:"When true, exclude jobs that belong to a batch or a parent (sub_workflow) job"})})},responses:{200:w(gt(t.Job),"Jobs"),...S(t,400)}}),o.registerPath({method:"get",path:"/jobs/{id}",tags:["Jobs"],summary:"Get a job",request:{params:P},responses:{200:w(t.Job,"Job"),...S(t,404)}}),o.registerPath({method:"post",path:"/jobs",tags:["Jobs"],summary:"Start a single job",request:{body:{required:!0,content:{"application/json":{schema:t.CreateJobBody}}}},responses:{201:w(t.Job,"Started job"),...S(t,400,404)}}),o.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:t.ResumeJobBody}}}},responses:{200:w(t.Job,"Resumed job"),...S(t,400,404,409)}}),o.registerPath({method:"post",path:"/jobs/{id}/retry",tags:["Jobs"],summary:"Retry a failed job",request:{params:P},responses:{200:w(t.Job,"Retry job"),...S(t,404,409)}}),o.registerPath({method:"get",path:"/batches",tags:["Batches"],summary:"List job batches",request:{query:vn.extend({workflowId:A.string().optional()})},responses:{200:w(gt(t.JobBatch),"Job batches")}}),o.registerPath({method:"get",path:"/batches/{id}",tags:["Batches"],summary:"Get a job batch",request:{params:P},responses:{200:w(t.JobBatch,"Job batch"),...S(t,404)}}),o.registerPath({method:"get",path:"/batches/{id}/jobs",tags:["Batches"],summary:"List jobs in a batch",request:{params:P},responses:{200:w(gt(t.Job),"Jobs in the batch"),...S(t,404)}}),o.registerPath({method:"post",path:"/batches",tags:["Batches"],summary:"Launch a batch or aggregate run",description:"Resolves subject selection and starts either a JobBatch (batch cardinality) or a single Job (aggregate cardinality).",request:{body:{required:!0,content:{"application/json":{schema:t.LaunchBody}}}},responses:{201:w(t.LaunchResponse,"Launch result"),...S(t,400,404)}}),o.registerPath({method:"get",path:"/schedules",tags:["Schedules"],summary:"List schedules",request:{query:A.object({enabled:A.enum(["true","false"]).optional()})},responses:{200:w(gt(t.Schedule),"Schedules"),...S(t,400)}}),o.registerPath({method:"get",path:"/schedules/{id}",tags:["Schedules"],summary:"Get a schedule",request:{params:P},responses:{200:w(t.Schedule,"Schedule"),...S(t,404)}}),o.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:t.Schedule}}}},responses:{201:w(t.Schedule,"Created schedule"),...S(t,400)}}),o.registerPath({method:"patch",path:"/schedules/{id}",tags:["Schedules"],summary:"Update a schedule",request:{params:P,body:{required:!0,content:{"application/json":{schema:t.UpdateScheduleBody}}}},responses:{200:w(t.Schedule,"Updated schedule"),...S(t,400,404)}}),o.registerPath({method:"delete",path:"/schedules/{id}",tags:["Schedules"],summary:"Delete a schedule",request:{params:P},responses:{204:{description:"Schedule deleted"},...S(t,404)}}),o.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:w(gt(t.ProviderStatus),"Provider configuration status")}}),o.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:w(t.EngineSettings,"Current engine settings")}}),o.registerPath({method:"patch",path:"/settings",tags:["Settings"],summary:"Update engine settings",description:"Partial merge. restartRequired is true only when activeProviders was in the patch (implementation binding is a boot-time decision). Jira/Bitbucket config fields take effect on the next provider call with no restart.",request:{body:{required:!0,content:{"application/json":{schema:t.UpdateSettingsBody}}}},responses:{200:w(t.SettingsPatchResponse,"Updated settings"),...S(t,400)}}),o.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:A.object({key:A.string().min(1)}),body:{required:!0,content:{"application/json":{schema:t.SetSecretBody}}}},responses:{204:{description:"Secret stored"},...S(t,400)}}),o.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:A.object({jobId:A.string().optional(),batchId:A.string().optional()})},responses:{200:{description:"SSE stream of engine events",content:{"text/event-stream":{schema:t.EngineEvent}}}}})}var Qi=p(()=>{"use strict";lt();Tn()});import{OpenAPIRegistry as wd,OpenApiGeneratorV31 as Sd}from"@asteasolutions/zod-to-openapi";function Zi(){if(_o)return _o;let o=new wd,t=zi(o);return Yi(o,t),_o=new Sd(o.definitions).generateDocument({openapi:"3.1.0",info:{title:"Kno Engine API",version:"0.1.0",description:"REST API for workflow definitions, jobs, batches, schedules, views, and live events."},servers:[{url:"/api"}]}),_o}var _o,ts=p(()=>{"use strict";Tn();Qi()});import{Controller as _d,Get as jd,Header as Id}from"@nestjs/common";var es,On,ye,os=p(()=>{"use strict";ts();es=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},On=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},ye=class{getOpenApiDocument(){return Zi()}};es([jd("openapi.json"),Id("Content-Type","application/json"),On("design:type",Function),On("design:paramtypes",[]),On("design:returntype",void 0)],ye.prototype,"getOpenApiDocument",null);ye=es([_d()],ye)});import{Controller as Ed,Get as vd,Inject as Td}from"@nestjs/common";var ns,jo,xd,we,rs=p(()=>{"use strict";Qo();ns=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},jo=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},xd=function(o,t){return function(e,n){t(e,n,o)}},we=class{providerStatus;constructor(t){this.providerStatus=t}async status(){return this.providerStatus.list()}};ns([vd("status"),jo("design:type",Function),jo("design:paramtypes",[]),jo("design:returntype",Promise)],we.prototype,"status",null);we=ns([Ed("providers"),xd(0,Td(_t)),jo("design:paramtypes",[_t])],we)});import{Body as Od,Controller as Rd,Get as Pd,Inject as Ad,Patch as kd}from"@nestjs/common";var Rn,Lt,is,Zt,ss=p(()=>{"use strict";lt();Ue();Et();Rn=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},Lt=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},is=function(o,t){return function(e,n){t(e,n,o)}},Zt=class{settings;constructor(t){this.settings=t}get(){return this.settings.get()}async update(t){return{settings:await this.settings.update(t),restartRequired:br(t)}}};Rn([Pd(),Lt("design:type",Function),Lt("design:paramtypes",[]),Lt("design:returntype",Promise)],Zt.prototype,"get",null);Rn([kd(),is(0,Od(new j(co))),Lt("design:type",Function),Lt("design:paramtypes",[Object]),Lt("design:returntype",Promise)],Zt.prototype,"update",null);Zt=Rn([Rd("settings"),is(0,Ad(D)),Lt("design:paramtypes",[D])],Zt)});import{Body as Nd,Controller as Cd,HttpCode as Dd,Inject as $d,Param as qd,Post as Ld}from"@nestjs/common";var as,Io,Pn,Se,cs=p(()=>{"use strict";yt();Y();Et();En();as=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},Io=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},Pn=function(o,t){return function(e,n){t(e,n,o)}},Se=class{secrets;constructor(t){this.secrets=t}async set(t,e){let n=t.trim();if(!n)throw new b("Secret key must not be empty");await this.secrets.set(n,e.value)}};as([Ld(":key"),Dd(204),Pn(0,qd("key")),Pn(1,Nd(new j(wo))),Io("design:type",Function),Io("design:paramtypes",[String,Object]),Io("design:returntype",Promise)],Se.prototype,"set",null);Se=as([Cd("secrets"),Pn(0,$d(H)),Io("design:paramtypes",[Function])],Se)});import{Module as Jd}from"@nestjs/common";import{APP_FILTER as Fd}from"@nestjs/core";var Bd,xo,us=p(()=>{"use strict";de();an();Qe();Vr();Pi();ki();$i();Li();Fi();Ki();os();rs();ss();cs();Ge();qo();Bd=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},xo=class{};xo=Bd([Jd({imports:[it,Xt,It,jt,Bt],controllers:[ft,Z,mt,Rt,bt,ge,ye,we,Zt,Se],providers:[{provide:Fd,useClass:io}]})],xo)});import{Module as Md}from"@nestjs/common";var Ud,Eo,ds=p(()=>{"use strict";Nn();Cn();Dn();Ge();vr();Qe();de();an();us();Ud=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},Eo=class{};Eo=Ud([Md({imports:[_e,je,jt,ze,It,it,Xt,xo],controllers:[te]})],Eo)});import{apiReference as Vd}from"@scalar/nestjs-api-reference";function ps(o){o.use("/api/docs",Vd({url:"/api/openapi.json",pageTitle:"Kno Engine API"}))}var ls=p(()=>{"use strict"});import{createServer as Kd}from"node:net";function fs(o){return typeof o=="object"&&o!==null&&"code"in o&&o.code==="EADDRINUSE"}async function An(o,t=20){for(let e=0;e<t;e+=1){let n=o+e;if(await Xd(n))return n}throw new Error(`No free port found in ${o}\u2013${o+t-1}`)}function Xd(o){return new Promise(t=>{let e=Kd();e.once("error",()=>{t(!1)}),e.once("listening",()=>{e.close(()=>t(!0))}),e.listen(o)})}var ms=p(()=>{"use strict"});import{existsSync as Hd}from"node:fs";import{dirname as Wd,join as vo}from"node:path";import{fileURLToPath as Gd}from"node:url";function hs(){let o=Wd(Gd(import.meta.url)),t=[vo(o,"../static"),vo(o,"../../static"),vo(o,"static")];for(let e of t)if(Hd(vo(e,"index.html")))return e;return null}var bs=p(()=>{"use strict"});var ep={};import"reflect-metadata";import{existsSync as zd}from"node:fs";import{join as Yd}from"node:path";import{Logger as Qd}from"@nestjs/common";import{NestFactory as Zd}from"@nestjs/core";async function tp(){let o=await Zd.create(Eo);o.enableCors(),o.setGlobalPrefix("api"),ps(o);let t=hs(),e=t?Yd(t,"index.html"):null;t&&e&&zd(e)?(To.log(`Serving UI from ${t}`),o.useStaticAssets(t),o.use((r,s,a)=>{if(r.method!=="GET"&&r.method!=="HEAD"||r.path.startsWith("/api"))return a();s.sendFile(e,u=>{u&&a(u)})})):To.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 i=await An(n);for(let r=0;r<5;r+=1)try{await o.listen(i),i!==n?To.warn(`Port ${n} is in use; listening on ${i} instead`):To.log(`Listening on http://localhost:${i}`);return}catch(s){if(!fs(s))throw s;i=await An(i+1)}throw new Error(`Could not bind a free port starting at ${n}`)}var To,gs=p(()=>{"use strict";ds();ls();ms();bs();To=new Qd("Bootstrap");tp()});import{readFileSync as op}from"node:fs";function np(){let o=op(new URL("../package.json",import.meta.url),"utf8");return JSON.parse(o).version}var Oo=process.argv.slice(2);Oo.includes("--version")||Oo.includes("-v")?console.log(np()):Oo.includes("--help")||Oo.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(`
134
- `)):await Promise.resolve().then(()=>(gs(),ep));
140
+ `),Tc(o)}var Mn=p(()=>{"use strict"});import{Injectable as Pc}from"@nestjs/common";import{mkdirSync as kc}from"node:fs";import{dirname as Ac}from"node:path";import{fileURLToPath as Nc}from"node:url";import{DatabaseSync as Vn}from"node:sqlite";var Rc,Oc,W,Wn=p(()=>{"use strict";Jn();Mn();Rc=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},Oc=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},W=class{sqlite;db;constructor(){let e=process.env.KNO_SQLITE_PATH??Nc(new URL("../../data/kno.db",import.meta.url));e===":memory:"?this.sqlite=new Vn(":memory:"):(kc(Ac(e),{recursive:!0}),this.sqlite=new Vn(e)),this.db=Fn(this.sqlite),mr(this.sqlite)}async onModuleInit(){mr(this.sqlite)}getDb(){return this.db}getSqlite(){return this.sqlite}};W=Rc([Pc(),Oc("design:paramtypes",[])],W)});import{Injectable as Dc}from"@nestjs/common";import{eq as Xn}from"drizzle-orm";var qc,Cc,O,ee=p(()=>{"use strict";ze();qc=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},Cc=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},O=class{db;sqlite;constructor(t,e){this.db=t,this.sqlite=e}async create(t){let e=new Date().toISOString();return await this.db.insert(ct).values({id:t.id,name:t.name,description:t.description??null,appliesTo:t.appliesTo,cardinality:t.cardinality,inputSchema:t.inputSchema,steps:t.steps,notificationPolicy:t.notificationPolicy,createdAt:e,updatedAt:e}),await this.get(t.id)}async get(t){let e=await this.db.query.workflowDefinitions.findFirst({where:{id:t}});return e?this.toDomain(e):null}async update(t,e){let r=await this.get(t);return r?(await this.db.update(ct).set({name:e.name??r.name,description:e.description!==void 0?e.description??null:r.description??null,appliesTo:e.appliesTo??r.appliesTo,cardinality:e.cardinality??r.cardinality,inputSchema:e.inputSchema??r.inputSchema,steps:e.steps??r.steps,notificationPolicy:e.notificationPolicy??r.notificationPolicy,updatedAt:new Date().toISOString()}).where(Xn(ct.id,t)),this.get(t)):null}async list(t={}){return(t.cardinality?await this.db.query.workflowDefinitions.findMany({where:{cardinality:t.cardinality}}):await this.db.query.workflowDefinitions.findMany()).map(r=>this.toDomain(r))}async delete(t){if(!await this.get(t))return!1;try{this.sqlite?.exec("PRAGMA foreign_keys = OFF"),await this.db.delete(ct).where(Xn(ct.id,t))}finally{this.sqlite?.exec("PRAGMA foreign_keys = ON")}return!0}toDomain(t){return{id:t.id,name:t.name,...t.description!=null?{description:t.description}:{},appliesTo:t.appliesTo,cardinality:t.cardinality,inputSchema:t.inputSchema,steps:t.steps,notificationPolicy:t.notificationPolicy}}};O=qc([Dc(),Cc("design:paramtypes",[Object,Function])],O)});import{Injectable as Lc}from"@nestjs/common";import{eq as hr}from"drizzle-orm";var Bc,$c,Kn,X,to=p(()=>{"use strict";cr();Bc=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},$c=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},Kn=["ticket","pull_request","documentation"],X=class{db;constructor(t){this.db=t}async create(t){let e=await this.nextOrder(t.subjectType);return await this.db.insert(ut).values({id:t.id,name:t.name,subjectType:t.subjectType,workflowId:t.workflowId,query:t.query,description:t.description??null,queryTemplate:t.queryTemplate??null,order:e}),await this.get(t.id)}async get(t){let e=await this.db.query.subjectViews.findFirst({where:{id:t}});return e?this.toDomain(e):null}async update(t,e){let r=await this.get(t);if(!r)return null;let i=e.queryTemplate!==void 0?e.queryTemplate:e.query!==void 0?void 0:r.queryTemplate;return await this.db.update(ut).set({name:e.name??r.name,subjectType:e.subjectType??r.subjectType,workflowId:e.workflowId??r.workflowId,query:e.query??r.query,description:e.description!==void 0?e.description??null:r.description??null,queryTemplate:i??null}).where(hr(ut.id,t)),this.get(t)}async list(t={}){let e=t.subjectType?await this.db.query.subjectViews.findMany({where:{subjectType:t.subjectType}}):await this.db.query.subjectViews.findMany();return this.sortViews(e.map(r=>this.toDomain(r)))}async reorder(t){let e=[];for(let i of t){let n=await this.get(i);if(!n)return[];e.push(n)}let r=e[0].subjectType;if(!e.every(i=>i.subjectType===r))return[];for(let i=0;i<t.length;i+=1)await this.db.update(ut).set({order:i}).where(hr(ut.id,t[i]));return this.list({subjectType:r})}async delete(t){return await this.get(t)?(await this.db.delete(ut).where(hr(ut.id,t)),!0):!1}async nextOrder(t){let e=await this.db.query.subjectViews.findMany({where:{subjectType:t}});return e.length===0?0:Math.max(...e.map(r=>r.order))+1}sortViews(t){return[...t].sort((e,r)=>{let i=Kn.indexOf(e.subjectType)-Kn.indexOf(r.subjectType);return i!==0?i:e.order-r.order})}toDomain(t){return{id:t.id,name:t.name,subjectType:t.subjectType,workflowId:t.workflowId,query:t.query,order:t.order,...t.description!=null?{description:t.description}:{},...t.queryTemplate!=null?{queryTemplate:t.queryTemplate}:{}}}};X=Bc([Lc(),$c("design:paramtypes",[Object])],X)});import{Injectable as Jc}from"@nestjs/common";import{and as Mc,desc as Vc,eq as Ie,inArray as Wc}from"drizzle-orm";import{randomUUID as Xc}from"node:crypto";function Kc(o){return o?o.mode==="single"?[o.subject]:o.subjects:[]}function Hc(o){if(o.length!==0)return o.length===1?{mode:"single",subject:o[0]}:{mode:"collection",subjects:o}}function Gn(o,t,e=null,r=null){let i=[];for(let n of t)if(i.push({id:n.id,jobId:o,stepDefinitionId:n.stepDefinitionId,type:n.type,status:n.status,startedAt:n.startedAt??null,completedAt:n.completedAt??null,output:n.output??null,error:n.error??null,childJobIds:n.childJobIds??null,parentStepExecutionId:e,iterationIndex:r}),n.iterations)for(let s of n.iterations)i.push(...Gn(o,s.stepExecutions,n.id,s.index));return i}function Gc(o){let t=new Map;for(let i of o){let n=i.parentStepExecutionId,s=t.get(n)??[];s.push(i),t.set(n,s)}let e=i=>{let n=t.get(i)??[];if(n.length===0)return;let s=new Map;for(let a of n){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(f=>Hn(f,e(f.id)));return{index:a,stepExecutions:c,startedAt:zc(c),...Yc(c)?{completedAt:Qc(c)}:{}}})};return(t.get(null)??[]).filter(i=>i.iterationIndex==null).map(i=>Hn(i,e(i.id)))}function Hn(o,t){return{id:o.id,stepDefinitionId:o.stepDefinitionId,type:o.type,status:o.status,...o.startedAt!=null?{startedAt:o.startedAt}:{},...o.completedAt!=null?{completedAt:o.completedAt}:{},...o.output!==null&&o.output!==void 0?{output:o.output}:{},...o.error!=null?{error:o.error}:{},...o.childJobIds!=null?{childJobIds:o.childJobIds}:{},...t&&t.length>0?{iterations:t}:{}}}function zc(o){let t=o.map(e=>e.startedAt).filter(e=>e!=null);return t.length===0?"":t.reduce((e,r)=>e<r?e:r)}function Qc(o){return o.map(e=>e.completedAt).filter(e=>e!=null).reduce((e,r)=>e>r?e:r)}function Yc(o){return o.length>0&&o.every(t=>t.completedAt!=null)}var Uc,Fc,P,oe=p(()=>{"use strict";ge();ur();lr();Uc=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},Fc=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},P=class{db;constructor(t){this.db=t}async create(t){return await this.db.insert(N).values(this.jobToRow(t)),await this.replaceSubjects(t.id,t.subjectContext),await this.replaceStepExecutions(t.id,t.stepHistory),await this.get(t.id)}async get(t){let e=await this.db.query.jobs.findFirst({where:{id:t},with:{subjects:!0,stepExecutions:!0}});return e?this.toDomain(e,e.subjects,e.stepExecutions):null}async update(t,e){let r=await this.get(t);if(!r)return null;let i={...r,...e,id:t,context:e.context??r.context,stepHistory:e.stepHistory??r.stepHistory,updatedAt:e.updatedAt??new Date().toISOString()};return await this.db.update(N).set({workflowId:i.workflowId,status:i.status,selection:i.selection??null,batchId:i.batchId??null,parentJobId:i.parentJobId??null,parentStepExecutionId:i.parentStepExecutionId??null,fanOutIndex:i.fanOutIndex??null,retryOf:i.retryOf??null,context:i.context,worktreePath:i.worktreePath??null,branch:i.branch??null,currentStepId:i.currentStepId??null,currentStepExecutionId:i.currentStepExecutionId??null,createdAt:i.createdAt,updatedAt:i.updatedAt,completedAt:i.completedAt??null}).where(Ie(N.id,t)),e.subjectContext!==void 0&&await this.replaceSubjects(t,e.subjectContext),e.stepHistory!==void 0&&await this.replaceStepExecutions(t,e.stepHistory),this.get(t)}async list(t={}){let e={};t.workflowId!==void 0&&(e.workflowId=t.workflowId),t.status!==void 0&&(e.status=t.status),t.batchId!==void 0&&(e.batchId=t.batchId),t.parentJobId!==void 0&&(e.parentJobId=t.parentJobId),t.parentStepExecutionId!==void 0&&(e.parentStepExecutionId=t.parentStepExecutionId);let i=(Object.keys(e).length>0?await this.db.query.jobs.findMany({where:e,with:{subjects:!0,stepExecutions:!0}}):await this.db.query.jobs.findMany({with:{subjects:!0,stepExecutions:!0}})).map(n=>this.toDomain(n,n.subjects,n.stepExecutions));return t.topLevelOnly?i.filter(n=>n.batchId==null&&n.parentJobId==null):i}async latestBySubject(t,e){let r={};for(let c of e)r[c]=null;if(e.length===0)return r;let i=await this.db.select({subjectId:pt.subjectId,jobId:N.id,createdAt:N.createdAt}).from(pt).innerJoin(N,Ie(pt.jobId,N.id)).where(Mc(Ie(N.workflowId,t),Wc(pt.subjectId,e))).orderBy(Vc(N.createdAt)),n=new Map;for(let c of i)n.has(c.subjectId)||n.set(c.subjectId,c.jobId);let s=[...new Set(n.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,f]of n)r[c]=u.get(f)??null;return r}jobToRow(t){return{id:t.id,workflowId:t.workflowId,status:t.status,selection:t.selection??null,batchId:t.batchId??null,parentJobId:t.parentJobId??null,parentStepExecutionId:t.parentStepExecutionId??null,fanOutIndex:t.fanOutIndex??null,retryOf:t.retryOf??null,context:t.context,worktreePath:t.worktreePath??null,branch:t.branch??null,currentStepId:t.currentStepId??null,currentStepExecutionId:t.currentStepExecutionId??null,createdAt:t.createdAt,updatedAt:t.updatedAt,completedAt:t.completedAt??null}}async replaceSubjects(t,e){await this.db.delete(pt).where(Ie(pt.jobId,t));let r=Kc(e);r.length!==0&&await this.db.insert(pt).values(r.map(i=>({id:Xc(),jobId:t,subjectType:i.subjectType,subjectId:i.id,snapshot:i})))}async replaceStepExecutions(t,e){await this.db.delete(Vt).where(Ie(Vt.jobId,t));let r=Gn(t,e);r.length!==0&&await this.db.insert(Vt).values(r)}toDomain(t,e,r){let i=Hc(e.map(s=>s.snapshot)),n=Gc(r);return{id:t.id,workflowId:t.workflowId,status:t.status,...i?{subjectContext:i}:{},...t.selection!=null?{selection:t.selection}:{},...t.batchId!=null?{batchId:t.batchId}:{},...t.parentJobId!=null?{parentJobId:t.parentJobId}:{},...t.parentStepExecutionId!=null?{parentStepExecutionId:t.parentStepExecutionId}:{},...t.fanOutIndex!=null?{fanOutIndex:t.fanOutIndex}:{},...t.retryOf!=null?{retryOf:t.retryOf}:{},context:t.context,...t.worktreePath!=null?{worktreePath:t.worktreePath}:{},...t.branch!=null?{branch:t.branch}:{},...t.currentStepId!=null?{currentStepId:t.currentStepId}:{},...t.currentStepExecutionId!=null?{currentStepExecutionId:t.currentStepExecutionId}:{},stepHistory:n,createdAt:t.createdAt,updatedAt:t.updatedAt,...t.completedAt!=null?{completedAt:t.completedAt}:{}}}};P=Uc([Jc(),Fc("design:paramtypes",[Object])],P)});import{Injectable as eu}from"@nestjs/common";import{eq as ou}from"drizzle-orm";var Zc,tu,K,eo=p(()=>{"use strict";Qe();Zc=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},tu=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},K=class{db;constructor(t){this.db=t}async create(t){return await this.db.insert(Rt).values({id:t.id,workflowId:t.workflowId,selection:t.selection,resolvedSubjects:t.resolvedSubjects,status:t.status,triggeredBy:t.triggeredBy,scheduleId:t.scheduleId??null,notificationOverride:t.notificationOverride??null,notificationSent:t.notificationSent,createdAt:t.createdAt,completedAt:t.completedAt??null}),await this.get(t.id)}async get(t){let e=await this.db.query.jobBatches.findFirst({where:{id:t},with:{jobs:!0}});return e?this.toDomain(e,e.jobs.map(r=>r.id)):null}async update(t,e){let r=await this.get(t);return r?(await this.db.update(Rt).set({workflowId:e.workflowId??r.workflowId,selection:e.selection??r.selection,resolvedSubjects:e.resolvedSubjects??r.resolvedSubjects,status:e.status??r.status,triggeredBy:e.triggeredBy??r.triggeredBy,scheduleId:e.scheduleId!==void 0?e.scheduleId??null:r.scheduleId??null,notificationOverride:e.notificationOverride!==void 0?e.notificationOverride??null:r.notificationOverride??null,notificationSent:e.notificationSent??r.notificationSent,createdAt:e.createdAt??r.createdAt,completedAt:e.completedAt!==void 0?e.completedAt??null:r.completedAt??null}).where(ou(Rt.id,t)),this.get(t)):null}async list(t={}){return(t.workflowId?await this.db.query.jobBatches.findMany({where:{workflowId:t.workflowId},with:{jobs:!0}}):await this.db.query.jobBatches.findMany({with:{jobs:!0}})).map(r=>this.toDomain(r,r.jobs.map(i=>i.id)))}toDomain(t,e){return{id:t.id,workflowId:t.workflowId,selection:t.selection,resolvedSubjects:t.resolvedSubjects,jobIds:e,status:t.status,triggeredBy:t.triggeredBy,...t.scheduleId!=null?{scheduleId:t.scheduleId}:{},...t.notificationOverride!=null?{notificationOverride:t.notificationOverride}:{},notificationSent:t.notificationSent,createdAt:t.createdAt,...t.completedAt!=null?{completedAt:t.completedAt}:{}}}};K=Zc([eu(),tu("design:paramtypes",[Object])],K)});import{Injectable as iu}from"@nestjs/common";import{eq as zn}from"drizzle-orm";var ru,nu,jt,br=p(()=>{"use strict";pr();ru=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},nu=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},jt=class{db;constructor(t){this.db=t}async create(t){return await this.db.insert(Pt).values({id:t.id,viewId:t.viewId,triggerType:t.trigger.type,cadence:t.trigger.cadence,notificationOverride:t.notificationOverride??null,missedFirePolicy:t.missedFirePolicy,enabled:t.enabled,lastFiredAt:t.lastFiredAt??null,createdAt:t.createdAt}),await this.get(t.id)}async get(t){let e=await this.db.query.schedules.findFirst({where:{id:t}});return e?this.toDomain(e):null}async update(t,e){let r=await this.get(t);if(!r)return null;let i=e.trigger??r.trigger;return await this.db.update(Pt).set({viewId:e.viewId??r.viewId,triggerType:i.type,cadence:i.cadence,notificationOverride:e.notificationOverride!==void 0?e.notificationOverride??null:r.notificationOverride??null,missedFirePolicy:e.missedFirePolicy??r.missedFirePolicy,enabled:e.enabled??r.enabled,lastFiredAt:e.lastFiredAt!==void 0?e.lastFiredAt??null:r.lastFiredAt??null,createdAt:e.createdAt??r.createdAt}).where(zn(Pt.id,t)),this.get(t)}async list(t={}){return(t.enabled!==void 0?await this.db.query.schedules.findMany({where:{enabled:t.enabled}}):await this.db.query.schedules.findMany()).map(r=>this.toDomain(r))}async delete(t){return await this.get(t)?(await this.db.delete(Pt).where(zn(Pt.id,t)),!0):!1}async findDue(t){return(await this.list({enabled:!0})).filter(r=>r.lastFiredAt==null||r.lastFiredAt<t)}toDomain(t){return{id:t.id,viewId:t.viewId,trigger:{type:"cron",cadence:t.cadence},...t.notificationOverride!=null?{notificationOverride:t.notificationOverride}:{},missedFirePolicy:t.missedFirePolicy,enabled:t.enabled,...t.lastFiredAt!=null?{lastFiredAt:t.lastFiredAt}:{},createdAt:t.createdAt}}};jt=ru([iu(),nu("design:paramtypes",[Object])],jt)});import{Injectable as cu}from"@nestjs/common";import{eq as wr}from"drizzle-orm";var su,au,_t,yr=p(()=>{"use strict";dr();su=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},au=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},_t=class{db;constructor(t){this.db=t}async create(t){let e=await this.nextOrder();return await this.db.insert(dt).values({id:t.id,name:t.name,workflowId:t.workflowId,inputValues:t.inputValues,lastJobId:t.lastJobId??null,order:e}),await this.get(t.id)}async get(t){let e=await this.db.query.workflowShortcuts.findFirst({where:{id:t}});return e?this.toDomain(e):null}async update(t,e){let r=await this.get(t);return r?(await this.db.update(dt).set({name:e.name??r.name,workflowId:e.workflowId??r.workflowId,inputValues:e.inputValues??r.inputValues,lastJobId:e.lastJobId!==void 0?e.lastJobId??null:r.lastJobId??null}).where(wr(dt.id,t)),this.get(t)):null}async list(){return(await this.db.query.workflowShortcuts.findMany()).map(e=>this.toDomain(e)).sort((e,r)=>e.order-r.order)}async reorder(t){let e=[];for(let r of t){let i=await this.get(r);if(!i)return[];e.push(i)}for(let r=0;r<t.length;r+=1)await this.db.update(dt).set({order:r}).where(wr(dt.id,t[r]));return this.list()}async delete(t){return await this.get(t)?(await this.db.delete(dt).where(wr(dt.id,t)),!0):!1}async nextOrder(){let t=await this.db.query.workflowShortcuts.findMany();return t.length===0?0:Math.max(...t.map(e=>e.order))+1}toDomain(t){return{id:t.id,name:t.name,workflowId:t.workflowId,inputValues:t.inputValues,order:t.order,...t.lastJobId!=null?{lastJobId:t.lastJobId}:{}}}};_t=su([cu(),au("design:paramtypes",[Object])],_t)});import{Injectable as pu}from"@nestjs/common";import{eq as du}from"drizzle-orm";function fu(o,t){let e={...o.activeProviders,...t.activeProviders},r=t.jira!==void 0?{...o.jira,...t.jira}:o.jira,i=t.bitbucket!==void 0?{...o.bitbucket,...t.bitbucket}:o.bitbucket;return gr({activeProviders:e,...r&&Object.keys(r).length>0?{jira:r}:{},...i&&Object.keys(i).length>0?{bitbucket:i}:{}})}function gr(o){return{...o,activeProviders:{ticket:o.activeProviders?.ticket??"manual",repo:o.activeProviders?.repo??"manual",agent:o.activeProviders?.agent??"claude"},...o.jira?{jira:o.jira}:{},...o.bitbucket?{bitbucket:o.bitbucket}:{}}}function Qn(o){return Object.prototype.hasOwnProperty.call(o,"activeProviders")}var uu,lu,U,oo=p(()=>{"use strict";fr();uu=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},lu=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},U=class{db;constructor(t){this.db=t}async get(){let t=await this.db.query.settings.findFirst({where:{id:_e}});return gr(t?t.data:{})}async update(t){let e=fu(await this.get(),t);return await this.db.query.settings.findFirst({where:{id:_e}})?await this.db.update(te).set({data:e}).where(du(te.id,_e)):await this.db.insert(te).values({id:_e,data:e}),e}};U=uu([pu(),lu("design:paramtypes",[Object])],U)});import{Module as hu}from"@nestjs/common";var mu,bu,ft,xe=p(()=>{"use strict";Wn();ee();to();oe();eo();br();yr();oo();mu=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},bu=[O,X,P,K,jt,_t,U],ft=class{};ft=mu([hu({providers:[W,{provide:O,useFactory:o=>new O(o.getDb(),o.getSqlite()),inject:[W]},{provide:X,useFactory:o=>new X(o.getDb()),inject:[W]},{provide:P,useFactory:o=>new P(o.getDb()),inject:[W]},{provide:K,useFactory:o=>new K(o.getDb()),inject:[W]},{provide:jt,useFactory:o=>new jt(o.getDb()),inject:[W]},{provide:_t,useFactory:o=>new _t(o.getDb()),inject:[W]},{provide:U,useFactory:o=>new U(o.getDb()),inject:[W]}],exports:[W,...bu]})],ft)});function Sr(o){return o==null?"":typeof o=="string"?o:Zn(o).replace(/\n+$/,"")}function Yn(o){return{version:1,type:"doc",content:o.split(`
141
+ `).map(e=>({type:"paragraph",content:e.length===0?[]:[{type:"text",text:e}]}))}}function Zn(o){if(o==null||typeof o!="object")return"";let t=o;if(t.type==="text")return t.text??"";if(t.type==="hardBreak")return`
142
+ `;let e=(t.content??[]).map(Zn).join("");return t.type==="paragraph"||t.type==="heading"||t.type==="blockquote"||t.type==="listItem"?`${e}
143
+ `:e}var ti=p(()=>{"use strict"});function gu(o){if(typeof o.jql=="string"&&o.jql.trim().length>0)return o.jql;let t=[];if(no(o.project)&&t.push(`project = ${io(o.project)}`),no(o.status)&&t.push(`status = ${io(o.status)}`),no(o.assignee)&&t.push(`assignee = ${io(o.assignee)}`),no(o.sprintId)){let e=o.sprintId;t.push(typeof e=="number"||/^\d+$/.test(String(e))?`sprint = ${Number(e)}`:`sprint = ${io(e)}`)}if(t.length===0)throw new Error("Jira query requires jql or at least one of project, status, assignee, sprintId");return t.join(" AND ")}function no(o){return o!=null&&o!==""}function io(o){return`"${String(o).replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function ei(o,t){let e=String(o.key??o.id??""),r=o.fields??{},i=Sr(r.description);return{id:e,source:"jira",title:String(r.summary??""),...i?{description:i}:{},status:String(r.status?.name??""),...r.assignee?.displayName?{assignee:String(r.assignee.displayName)}:{},url:`${t.replace(/\/$/,"")}/browse/${e}`,raw:o}}var re,wu,yu,ro,so,jr=p(()=>{"use strict";ti();re="kno.jira.apiToken",wu=50,yu=10,ro=500,so=class{secrets;settings;fetchFn;constructor(t,e,r=fetch){this.secrets=t,this.settings=e,this.fetchFn=r}async get(t){let{baseUrl:e}=await this.requireConfig(),r=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(t)}`);return ei(r,e)}async query(t){let{baseUrl:e}=await this.requireConfig(),r=gu(t),i=[],n,s=new Set;for(let a=0;a<yu&&i.length<ro;a++){let u={jql:r,maxResults:Math.min(wu,ro-i.length),fields:["summary","description","status","assignee"]};n&&(u.nextPageToken=n);let c=await this.request("POST","/rest/api/3/search/jql",{body:u}),f=Array.isArray(c.issues)?c.issues:[];for(let j of f){if(i.length>=ro)break;i.push(ei(j,e))}let m=typeof c.nextPageToken=="string"?c.nextPageToken:void 0;if(c.isLast===!0||!m||f.length===0||m===n||s.has(m))break;s.add(m),n=m}return i}async getComments(t){let e=[],r=0,i=100,n=ro;for(;e.length<n;){let s=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(t)}/comment?startAt=${r}&maxResults=${i}`),a=Array.isArray(s.comments)?s.comments:[];for(let u of a)e.push({id:String(u.id??""),subjectId:t,body:Sr(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<i)break}return e}async postComment(t,e){await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(t)}/comment`,{body:{body:Yn(e)}})}async updateStatus(t,e){let r=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(t)}/transitions`),i=Array.isArray(r.transitions)?r.transitions:[],n=e.trim().toLowerCase(),s=i.find(a=>(a.to?.name??"").trim().toLowerCase()===n);if(!s?.id){let a=i.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 '${e}' from the current state. Available: ${u}`)}await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(t)}/transitions`,{body:{transition:{id:s.id}}})}async requireConfig(){let t=(await this.settings.get()).jira,e=t?.baseUrl?.trim(),r=t?.email?.trim(),i=await this.secrets.get(re),n=[];if(e||n.push("settings.jira.baseUrl"),r||n.push("settings.jira.email"),i||n.push(`SecretStore '${re}'`),n.length>0)throw new Error(`Jira is not configured \u2014 missing ${n.join(", ")}. Set jira.baseUrl and jira.email via PATCH /api/settings, and store the API token with: POST /api/secrets/${re} or npm --workspace apps/engine run set-secret -- ${re} <value>`);return{baseUrl:e,email:r,token:i}}async request(t,e,r={}){let{baseUrl:i,email:n,token:s}=await this.requireConfig(),a=`${i.replace(/\/$/,"")}${e}`,u={Authorization:`Basic ${Buffer.from(`${n}:${s}`).toString("base64")}`,Accept:"application/json"};r.body!==void 0&&(u["Content-Type"]="application/json");let c=await this.fetchFn(a,{method:t,headers:u,...r.body!==void 0?{body:JSON.stringify(r.body)}:{}});if(!c.ok){let m=await c.text().catch(()=>"");throw new Error(`Jira ${t} ${e} failed (${c.status}): ${m||c.statusText}`)}if(c.status===204)return;let f=await c.text();if(f)return JSON.parse(f)}}});function ao(o){let t=o.trim(),e=t.lastIndexOf("#");if(e<=0||e===t.length-1)throw new Error(`Bitbucket pull request id must be '{repoSlug}#{prNumber}' (e.g. 'kno-engine#42'), got '${o}'`);let r=t.slice(0,e),i=t.slice(e+1);if(!/^\d+$/.test(i))throw new Error(`Bitbucket pull request id must be '{repoSlug}#{prNumber}' with a numeric PR number, got '${o}'`);return{repoSlug:r,prNumber:i}}function ju(o,t){return`${o}#${t}`}function _u(o){let t=o.repoSlug;if(typeof t!="string"||t.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 t.trim()}function Iu(o){if(typeof o.repoSlug=="string"&&o.repoSlug.trim().length>0||!ni(o.role))return;let t=String(o.role).trim().toLowerCase();if(t!=="author"&&t!=="reviewer")throw new Error(`Bitbucket query filter.role must be 'author' or 'reviewer', got '${String(o.role)}'`);return t}function ri(o){if(!ni(o))return;let t=String(o).trim().toUpperCase();if(t!=="OPEN"&&t!=="MERGED"&&t!=="DECLINED")throw new Error(`Bitbucket query filter.state must be OPEN, MERGED, or DECLINED, got '${String(o)}'`);return t}function xu(o){if(typeof o.q=="string"&&o.q.trim().length>0)return o.q;let t=ri(o.state);if(t)return`state="${t}"`}function Eu(o){let t=o.destination?.repository?.name;if(typeof t=="string"&&t.trim().length>0)return t.trim();let e=o.destination?.repository?.full_name;if(typeof e=="string"&&e.includes("/"))return e.slice(e.lastIndexOf("/")+1);throw new Error("Bitbucket workspace pull request is missing destination.repository slug")}function vu(o){let t=o.trim().toLowerCase();if(t==="approved")return"approve";if(t==="declined"||t==="rejected")return"decline";if(t==="merged")return"merge";throw new Error(`No Bitbucket action for status '${o}'. Accepted: approved, declined/rejected, merged`)}function ni(o){return o!=null&&o!==""}function oi(o,t){let e=String(o.id??""),r=typeof o.description=="string"?o.description:"";return{id:ju(t,e),source:"bitbucket",title:String(o.title??""),...r?{description:r}:{},sourceBranch:String(o.source?.branch?.name??""),targetBranch:String(o.destination?.branch?.name??""),...o.author?.display_name?{author:o.author.display_name}:{},...o.links?.html?.href?{url:o.links.html.href}:{},raw:o}}function Tu(o,t){let e=o.user?.display_name??o.author?.display_name;return{id:String(o.id??""),subjectId:t,body:o.content?.raw??"",...e?{author:e}:{},createdAt:o.created_on??"",raw:o}}var ne,Su,co,_r=p(()=>{"use strict";ne="kno.bitbucket.apiToken",Su="https://api.bitbucket.org/2.0",co=class{secrets;settings;fetchFn;constructor(t,e,r=fetch){this.secrets=t,this.settings=e,this.fetchFn=r}async get(t){let{repoSlug:e,prNumber:r}=ao(t),{workspace:i}=await this.requireConfig(),n=await this.request("GET",this.prPath(i,e,r));return oi(n,e)}async query(t){let e=Iu(t);if(e)return this.queryWorkspacePullRequests(e,t);let r=_u(t),{baseUrl:i,workspace:n}=await this.requireConfig(),s=xu(t),a=new URLSearchParams({pagelen:String(50)});s&&a.set("q",s);let u=`${i.replace(/\/$/,"")}/repositories/${encodeURIComponent(n)}/${encodeURIComponent(r)}/pullrequests?${a.toString()}`;return this.collectPullRequests(u,r)}async queryWorkspacePullRequests(t,e){let{baseUrl:r,workspace:i,email:n}=await this.requireConfig(),s=new URLSearchParams({pagelen:String(50)}),a=ri(e.state);a&&s.set("state",a),t==="reviewer"&&s.set("role","REVIEWER");let u=`${r.replace(/\/$/,"")}/workspaces/${encodeURIComponent(i)}/pullrequests/${encodeURIComponent(n)}?${s.toString()}`;return this.collectPullRequests(u)}async collectPullRequests(t,e){let r=[],i=new Set,n=t;for(let s=0;s<10&&r.length<500&&!(!n||i.has(n));s++){i.add(n);let a=await this.request("GET",n),u=Array.isArray(a.values)?a.values:[];for(let f of u){if(r.length>=500)break;r.push(oi(f,e??Eu(f)))}let c=typeof a.next=="string"&&a.next.length>0?a.next:void 0;if(!c||u.length===0)break;n=c}return r}async getComments(t){let{repoSlug:e,prNumber:r}=ao(t),{workspace:i}=await this.requireConfig(),n=[],s=new Set,a=`${this.prPath(i,e,r)}/comments?pagelen=50`;for(let u=0;u<10&&n.length<500&&!(!a||s.has(a));u++){s.add(a);let c=await this.request("GET",a),f=Array.isArray(c.values)?c.values:[];for(let j of f)n.push(Tu(j,t));let m=typeof c.next=="string"&&c.next.length>0?c.next:void 0;if(!m||f.length===0)break;a=m}return n}async postComment(t,e){let{repoSlug:r,prNumber:i}=ao(t),{workspace:n}=await this.requireConfig();await this.request("POST",`${this.prPath(n,r,i)}/comments`,{body:{content:{raw:e}}})}async updateStatus(t,e){let{repoSlug:r,prNumber:i}=ao(t),{workspace:n}=await this.requireConfig(),s=vu(e);await this.request("POST",`${this.prPath(n,r,i)}/${s}`)}prPath(t,e,r){return`/repositories/${encodeURIComponent(t)}/${encodeURIComponent(e)}/pullrequests/${encodeURIComponent(r)}`}async requireConfig(){let t=(await this.settings.get()).bitbucket,e=(t?.baseUrl?.trim()||Su).replace(/\/$/,""),r=t?.email?.trim(),i=t?.workspace?.trim(),n=await this.secrets.get(ne),s=[];if(r||s.push("settings.bitbucket.email"),i||s.push("settings.bitbucket.workspace"),n||s.push(`SecretStore '${ne}'`),s.length>0)throw new Error(`Bitbucket is not configured \u2014 missing ${s.join(", ")}. Set bitbucket.email and bitbucket.workspace via PATCH /api/settings, and store the API token with: POST /api/secrets/${ne} or npm --workspace apps/engine run set-secret -- ${ne} <value>`);return{baseUrl:e,email:r,workspace:i,token:n}}async request(t,e,r={}){let{baseUrl:i,email:n,token:s}=await this.requireConfig(),a=e.startsWith("http://")||e.startsWith("https://")?e:`${i}${e.startsWith("/")?e:`/${e}`}`,u={Authorization:`Basic ${Buffer.from(`${n}:${s}`).toString("base64")}`,Accept:"application/json"};r.body!==void 0&&(u["Content-Type"]="application/json");let c=await this.fetchFn(a,{method:t,headers:u,...r.body!==void 0?{body:JSON.stringify(r.body)}:{}});if(!c.ok){let m=await c.text().catch(()=>"");throw new Error(`Bitbucket ${t} ${e} failed (${c.status}): ${m||c.statusText}`)}if(c.status===204)return;let f=await c.text();if(f)return JSON.parse(f)}}});import{Injectable as ku,Logger as Au,Inject as Nu}from"@nestjs/common";async function ii(o){let t=[];for(let e of qu){let r=await o.get(e.secretKey);t.push({providerId:e.providerId,secretKey:e.secretKey,configured:typeof r=="string"&&r.length>0})}return t}async function Cu(o,t){let e=await ii(o);for(let r of e)r.configured||t(`${r.providerId} API key not configured (looked up as '${r.secretKey}'). GET /api/providers/status lists what's missing; store a key with: POST /api/secrets/${r.secretKey} or npm --workspace apps/engine run set-secret -- ${r.secretKey} <value>`)}function si(o={}){let t=o.activeProviders?.agent;if(t==null)return"claude";if(t==="claude"||t==="cursor")return t;throw new Error(`Invalid activeProviders.agent '${String(t)}'. Expected 'claude' or 'cursor'.`)}function ai(o={}){let t=o.activeProviders?.ticket;if(t==null||t==="manual")return"manual";if(t==="jira")return"jira";throw new Error(`Invalid activeProviders.ticket '${String(t)}'. Expected 'jira' or 'manual'.`)}function ci(o={}){let t=o.activeProviders?.repo;if(t==null||t==="manual")return"manual";if(t==="bitbucket")return"bitbucket";throw new Error(`Invalid activeProviders.repo '${String(t)}'. Expected 'bitbucket' or 'manual'.`)}var Ru,Ou,Pu,Ir,qu,kt,xr=p(()=>{"use strict";Tt();jr();_r();Ru=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},Ou=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},Pu=function(o,t){return function(e,r){t(e,r,o)}},qu=[{providerId:"anthropic",secretKey:St("anthropic")},{providerId:"cursor",secretKey:St("cursor")},{providerId:"jira",secretKey:re},{providerId:"bitbucket",secretKey:ne}];kt=Ir=class{secrets;logger=new Au(Ir.name);constructor(t){this.secrets=t}async onModuleInit(){await Cu(this.secrets,t=>this.logger.warn(t))}list(){return ii(this.secrets)}};kt=Ir=Ru([ku(),Pu(0,Nu(ot)),Ou("design:paramtypes",[Function])],kt)});var Wt,h,b,Xt,D=p(()=>{"use strict";Wt=class extends Error{constructor(t){super(t),this.name=this.constructor.name}},h=class extends Wt{httpStatus=404},b=class extends Wt{httpStatus=400},Xt=class extends Wt{httpStatus=409}});function li(o,t){switch(o){case"my-open-prs":return{role:"author",state:"OPEN"};case"reviewing":return{role:"reviewer",state:"OPEN"};case"repo-open-prs":{let e=typeof t.repoSlug=="string"?t.repoSlug.trim():"";if(!e)throw new b("Bitbucket template 'repo-open-prs' requires params.repoSlug");return{repoSlug:e,state:"OPEN"}}default:throw new h(`Unknown Bitbucket query template: ${o}`)}}var ui,pi=p(()=>{"use strict";D();ui=[{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}]}]});import{Injectable as Bu}from"@nestjs/common";var Du,di,At,Er=p(()=>{"use strict";D();pi();Du=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},di={bitbucket:{list:()=>ui,resolve:li}},At=class{list(t){return di[t]?.list()??[]}resolve(t,e,r){let i=di[t];if(!i)throw new h(`No query templates for provider '${t}'`);let n=i.list().find(s=>s.id===e);if(!n)throw new h(`Unknown query template '${e}' for provider '${t}'`);for(let s of n.params){if(!s.required)continue;let a=r[s.name];if(a==null||typeof a=="string"&&a.trim()==="")throw new b(`Template '${e}' requires params.${s.name}`)}return i.resolve(e,r)}};At=Du([Bu()],At)});import{Module as Lu}from"@nestjs/common";import{fileURLToPath as Uu}from"node:url";import{dirname as Fu,join as Ju}from"node:path";var $u,Mu,Nt,uo=p(()=>{"use strict";Be();wn();Le();yn();Fe();gn();tr();Rn();On();ir();Pn();sr();An();ar();Tt();xe();oo();xr();jr();_r();Er();$u=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},Mu=Ju(Fu(Uu(import.meta.url)),"../../../knowledge"),Nt=class{};Nt=$u([Lu({imports:[Zt,ft],providers:[{provide:Ut,useFactory:async(o,t)=>ai(await t.get())==="jira"?new so(o,t):new $e([]),inject:[ot,U]},{provide:Ft,useFactory:async(o,t)=>ci(await t.get())==="bitbucket"?new co(o,t):new Ue([]),inject:[ot,U]},{provide:Jt,useFactory:()=>new Je([])},{provide:me,useFactory:async(o,t)=>si(await t.get())==="cursor"?new Ke(o):new Xe(o),inject:[ot,U]},{provide:we,useClass:He},{provide:ye,useFactory:()=>new Ge(Mu)},kt,At],exports:[Ut,Ft,Jt,me,we,ye,kt,At]})],Nt)});import{Module as Wu}from"@nestjs/common";var Vu,lo,fi=p(()=>{"use strict";Vu=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},lo=class{};lo=Vu([Wu({})],lo)});import{Injectable as Ku}from"@nestjs/common";var Xu,nt,po=p(()=>{"use strict";Xu=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},nt=class{listeners=new Set;emit(t){for(let e of this.listeners)e(t)}subscribe(t){return this.listeners.add(t),()=>this.listeners.delete(t)}};nt=Xu([Ku()],nt)});import{Global as Gu,Module as zu}from"@nestjs/common";var Hu,qt,fo=p(()=>{"use strict";po();Hu=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},qt=class{};qt=Hu([Gu(),zu({providers:[nt],exports:[nt]})],qt)});import{Injectable as Zu}from"@nestjs/common";import{execFile as tl}from"node:child_process";import{mkdirSync as mi}from"node:fs";import{join as vr}from"node:path";import{promisify as el}from"node:util";function hi(o){return o==null?"":typeof o=="string"?o:o.toString("utf8")}function bi(o){return vr(o,"worktrees")}var Qu,Yu,ol,It,Tr=p(()=>{"use strict";Qu=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},Yu=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},ol=el(tl),It=class{worktreesRoot;constructor(t){this.worktreesRoot=t,mi(this.worktreesRoot,{recursive:!0})}async createWorktree(t,e){let r=e.worktreePath??vr(this.worktreesRoot,t);return mi(vr(r,".."),{recursive:!0}),await this.git(e.repoPath,["worktree","add","-b",e.branchName,r,e.baseBranch]),{worktreePath:r,branch:e.branchName}}async checkout(t,e){await this.git(t,["checkout",e.branch])}async createBranch(t,e){e.baseBranch?await this.git(t,["checkout","-b",e.branchName,e.baseBranch]):await this.git(t,["checkout","-b",e.branchName])}async commit(t,e){return e.addAll!==!1&&await this.git(t,["add","-A"]),await this.git(t,["commit","-m",e.message]),{sha:(await this.git(t,["rev-parse","HEAD"])).stdout.trim()}}async push(t,e={}){let r=e.remote??"origin";e.branch?await this.git(t,["push",r,e.branch]):await this.git(t,["push",r,"HEAD"])}async git(t,e){try{let r=await ol("git",e,{cwd:t,encoding:"utf8",windowsHide:!0});return{stdout:r.stdout??"",stderr:r.stderr??""}}catch(r){let i=r,n=hi(i.stderr),s=hi(i.stdout),a=n||s||i.message||"unknown git error";throw new Error(`git ${e.join(" ")} failed (cwd=${t}, code=${String(i.code??"?")}): ${a}`)}}};It=Qu([Zu(),Yu("design:paramtypes",[String])],It)});import{Module as nl}from"@nestjs/common";import{mkdirSync as il}from"node:fs";import{dirname as sl,join as al}from"node:path";import{fileURLToPath as cl}from"node:url";var rl,wi,mo,yi=p(()=>{"use strict";Tr();rl=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},wi=al(sl(cl(import.meta.url)),"../../data");il(wi,{recursive:!0});mo=class{};mo=rl([nl({providers:[{provide:It,useFactory:()=>new It(bi(wi))}],exports:[It]})],mo)});function ho(o,t){return o.replace(/\{\{\s*([^}]+?)\s*\}\}/g,(e,r)=>{let i=ul(t,r.trim());return i==null?"":typeof i=="string"?i:JSON.stringify(i)})}function ul(o,t){let e=t.split(".").filter(Boolean),r=o;for(let i of e){if(r==null||typeof r!="object")return;r=r[i]}return r}function Ee(o,t){return typeof o=="string"?ho(o,t):Array.isArray(o)?o.map(e=>Ee(e,t)):o&&typeof o=="object"?Object.fromEntries(Object.entries(o).map(([e,r])=>[e,Ee(r,t)])):o}var gi=p(()=>{"use strict"});function Si(o,t){switch(o){case"questionnaire":return Rr(t);case"confirmation":return ll(t);case"conversation":return pl(t);default:return o}}function Rr(o){if(typeof o=="string"&&o.trim())return[o.trim()];if(!o||typeof o!="object")return[];let t=o.questions;return Array.isArray(t)?t.map(e=>typeof e=="string"?e.trim():e&&typeof e=="object"&&"prompt"in e?String(e.prompt).trim():"").filter(Boolean):[]}function ll(o){if(typeof o=="string"&&o.trim())return[o.trim()];if(!o||typeof o!="object")return[];let t=o;for(let e of["prompt","message","summary","question"]){let r=t[e];if(typeof r=="string"&&r.trim())return[r.trim()]}return"approved"in t&&!("questions"in t)?[]:Rr(o)}function pl(o){if(typeof o=="string"&&o.trim())return[o.trim()];if(!o||typeof o!="object")return[];let t=o;for(let e of["prompt","message","text"]){let r=t[e];if(typeof r=="string"&&r.trim())return[r.trim()]}return"suggestions"in t?[]:"questions"in t?Rr(o):[]}var ji=p(()=>{"use strict"});function ie(o,t){for(let e of o){if(e.id===t)return e;if(e.iterations)for(let r of e.iterations){let i=ie(r.stepExecutions,t);if(i)return i}}}function ve(o,t,e,r){for(let i=0;i<o.length;i++){let n=o[i];if(n.id===t)return{execution:n,siblings:o,index:i,parentLoopExecutionId:e,iterationIndex:r};if(n.iterations)for(let s of n.iterations){let a=ve(s.stepExecutions,t,n.id,s.index);if(a)return a}}}function F(o,t,e){return o.map(r=>r.id===t?e(r):r.iterations?{...r,iterations:r.iterations.map(i=>({...i,stepExecutions:F(i.stepExecutions,t,e)}))}:r)}function Or(o,t,e,r){return e==null?[...o,t]:o.map(i=>{if(i.id===e){let n=[...i.iterations??[]],s=n.find(a=>a.index===r);if(s){let a={...s,stepExecutions:[...s.stepExecutions,t]},u=n.findIndex(c=>c.index===r);n[u]=a}else{let a={index:r,stepExecutions:[t],startedAt:t.startedAt??new Date().toISOString()};n.push(a),n.sort((u,c)=>u.index-c.index)}return{...i,iterations:n}}return i.iterations?{...i,iterations:i.iterations.map(n=>({...n,stepExecutions:Or(n.stepExecutions,t,e,r)}))}:i})}function Te(o,t){for(let e of o){if(e.id===t)return e;if(e.type==="loop"){let r=Te(e.steps,t);if(r)return r}}}function _i(o,t,e){return F(o,t,r=>{let i=(r.iterations??[]).map(n=>{if(n.index!==e)return n;let s=n.stepExecutions.every(a=>a.completedAt)?n.stepExecutions.map(a=>a.completedAt).reduce((a,u)=>a>u?a:u):void 0;return{...n,...s?{completedAt:s}:{}}});return{...r,iterations:i}})}var Ii=p(()=>{"use strict"});import{z as H}from"zod";function xi(o,t){let e=bl[o].safeParse(t);if(!e.success){let r=e.error.issues.map(i=>`${i.path.length?i.path.join("."):"(root)"}: ${i.message}`).join("; ");throw new Error(`Agent output failed validation for format '${o}': ${r}`)}return e.data}var dl,fl,ml,hl,bl,Ei=p(()=>{"use strict";dl=H.object({questions:H.array(H.object({id:H.string(),prompt:H.string()}))}),fl=H.object({approved:H.boolean()}),ml=H.object({suggestions:H.array(H.object({body:H.string()}))}),hl=H.string(),bl={questionnaire:dl,confirmation:fl,comment_suggestions:ml,free_text:hl}});function vi(o){return o==="completed"||o==="failed"||o==="cancelled"}function Pr(o,t){let e=new Map;for(let i of o){let n=t(i);if(n==null)continue;let s=e.get(n)??[];s.push(i),e.set(n,s)}if(e.size===0)return null;let r=[];for(let i of e.values()){let n=new Set(i.map(a=>a.retryOf).filter(a=>a!=null)),s=i.find(a=>!n.has(a.id));if(!s)return null;r.push(s)}return{activeJobs:r,allTerminal:r.every(i=>vi(i.status)),groupCount:e.size}}function Ti(o){let t=o.every(r=>r.status==="completed"),e=o.every(r=>r.status==="failed"||r.status==="cancelled");return t?"completed":e?"failed":"completed_with_issues"}var Ri=p(()=>{"use strict"});async function bo(o,t,e){let r=await t.get(o);if(!r)throw new h(`SubjectView not found: ${o}`);if(r.subjectType==="ticket")return(await e.tickets.query(r.query)).map(n=>({subjectType:"ticket",...n}));if(r.subjectType==="pull_request")return(await e.repo.query(r.query)).map(n=>({subjectType:"pull_request",...n}));if(r.subjectType==="documentation")return(await e.documentation.query(r.query)).map(n=>({subjectType:"documentation",...n}));throw new b(`Unsupported subjectType on view: ${r.subjectType}`)}var kr=p(()=>{"use strict";D()});import{Inject as z,Injectable as gl}from"@nestjs/common";import{randomUUID as Ar}from"node:crypto";import{exec as Sl}from"node:child_process";import{promisify as jl}from"node:util";function Oi(o,t){let e=t[o.stepId];if(e==null||typeof e!="object")return o.type==="field_empty";let r=e[o.field];return o.type==="field_empty"?r==null?!0:typeof r=="string"||Array.isArray(r)?r.length===0:!1:r===o.value}function xl(o,t){let e=i=>{let n=[];for(let s of i)n.push(s),s.type==="loop"&&n.push(...e(s.steps));return n},r=i=>{let n=i.findIndex(s=>s.id===t);if(n>=0){for(let s=n-1;s>=0;s--)if(i[s].type==="agent")return i[s].id;return}for(let s of i)if(s.type==="loop"){let a=r(s.steps);if(a!==void 0||s.steps.some(u=>u.id===t))return a}};return r(o.steps)}function wo(o){let t={...o.context};return o.subjectContext?.mode==="single"&&(t.subject=o.subjectContext.subject),o.worktreePath&&(t.worktreePath=o.worktreePath),o.branch&&(t.branch=o.branch),t}function yo(o){if(!o.worktreePath)throw new Error(`Job ${o.id} has no worktreePath; run create_worktree first`);return o.worktreePath}function mt(o,t){let e=o[t];if(typeof e!="string"||e.length===0)throw new Error(`Missing required string param '${t}'`);return e}function El(o){if(o==="none")throw new Error("normalizeAppliesTo called with none");if(Array.isArray(o)){if(o.length!==1)throw new Error(`Workflow Runner requires appliesTo to be a single SubjectType (got ${JSON.stringify(o)})`);return o[0]}return o}function Pi(o,t){for(let e of o)if(e.required&&(t[e.name]===void 0||t[e.name]===null))throw new b(`Missing required input: ${e.name}`)}var wl,yl,G,_l,Il,it,go=p(()=>{"use strict";ee();oe();eo();to();po();tr();Be();Le();Fe();ir();sr();Tr();D();gi();ji();Ii();Ei();Ri();kr();wl=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},yl=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},G=function(o,t){return function(e,r){t(e,r,o)}},_l=jl(Sl),Il=["user","organization","project"],it=class{workflows;jobs;batches;views;events;tickets;repo;documentation;agent;notifications;knowledge;git;childTerminalLocks=new Set;batchTerminalLocks=new Set;constructor(t,e,r,i,n,s,a,u,c,f,m,j){this.workflows=t,this.jobs=e,this.batches=r,this.views=i,this.events=n,this.tickets=s,this.repo=a,this.documentation=u,this.agent=c,this.notifications=f,this.knowledge=m,this.git=j,this.events.subscribe(g=>{let R=g;(R.type==="job_completed"||R.type==="job_failed")&&this.onChildTerminal(R.jobId)})}async start(t){let e=await this.createJob(t);return this.emit({type:"job_started",jobId:e.id,timestamp:new Date().toISOString()}),this.runJob(e.id)}async launch(t){let e=await this.requireWorkflow(t.workflowId);if(e.cardinality==="single")throw new b("launch() does not support cardinality 'single'; use start() with a subjectId");if(e.cardinality!=="batch"&&e.cardinality!=="aggregate")throw new b(`Unsupported cardinality: ${e.cardinality}`);Pi(e.inputSchema,t.inputValues);let r=await this.resolveSelection(t.selection);if(e.cardinality==="aggregate"){let a=await this.createJob({workflowId:e.id,subjectContext:{mode:"collection",subjects:r},selection:t.selection,inputValues:t.inputValues});return this.emit({type:"job_started",jobId:a.id,timestamp:new Date().toISOString()}),this.runJob(a.id)}let i=new Date().toISOString(),n=await this.batches.create({id:Ar(),workflowId:e.id,selection:t.selection,resolvedSubjects:r,status:"running",triggeredBy:t.triggeredBy,...t.notificationOverride?{notificationOverride:t.notificationOverride}:{},notificationSent:!1,createdAt:i}),s=[];for(let a=0;a<r.length;a++){let u=r[a],c=await this.createJob({workflowId:e.id,subjectContext:{mode:"single",subject:u},selection:t.selection,batchId:n.id,fanOutIndex:a,inputValues:t.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(n.id)}async createJob(t){let e=await this.workflows.get(t.workflowId);if(!e)throw new h(`Workflow not found: ${t.workflowId}`);if(!t.subjectContext&&e.cardinality!=="single")throw new b(`Workflow Runner only supports cardinality 'single' at start() without an explicit subjectContext (got '${e.cardinality}')`);Pi(e.inputSchema,t.inputValues);let r=t.subjectContext??await this.resolveSubjectContext(e,t.subjectId),i=new Date().toISOString();return this.jobs.create({id:Ar(),workflowId:e.id,status:"pending",...r?{subjectContext:r}:{},...t.selection?{selection:t.selection}:{},...t.batchId?{batchId:t.batchId}:{},...t.parentJobId?{parentJobId:t.parentJobId}:{},...t.parentStepExecutionId?{parentStepExecutionId:t.parentStepExecutionId}:{},...t.fanOutIndex!=null?{fanOutIndex:t.fanOutIndex}:{},...t.retryOf?{retryOf:t.retryOf}:{},context:{...t.inputValues},stepHistory:[],createdAt:i,updatedAt:i})}async runJob(t){let e=await this.jobs.get(t);if(!e)throw new h(`Job not found: ${t}`);let r=await this.requireWorkflow(e.workflowId);e.status==="pending"&&(e=await this.persistJob({...e,status:"planning",updatedAt:new Date().toISOString()}));let i=await this.executeStepSequence(e,r,r.steps,void 0,void 0,0);return i.outcome==="paused"||i.outcome==="failed"?i.job:this.completeJob(i.job,r)}async resume(t,e){let r=await this.jobs.get(t);if(!r)throw new h(`Job not found: ${t}`);if(r.status!=="waiting_for_human")throw new Xt(`Job ${t} is not waiting for human input (status: ${r.status})`);let i=await this.requireWorkflow(r.workflowId),n=r.currentStepExecutionId;if(!n)throw new Error(`Job ${t} is waiting_for_human but has no currentStepExecutionId`);let s=ie(r.stepHistory,n);if(!s)throw new Error(`Paused execution ${n} not found on job ${t}`);if(s.type==="loop")return this.resumeAskHuman(r,i,s,e);if(s.type!=="interaction")throw new Error(`Paused execution ${n} has type '${s.type}'; expected interaction or loop`);let a=new Date().toISOString(),u=F(r.stepHistory,n,R=>({...R,status:"completed",completedAt:a,output:e})),c=e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{response:e};r=await this.persistJob({...r,status:"planning",context:{...r.context,[s.stepDefinitionId]:e},stepHistory:u,currentStepId:void 0,currentStepExecutionId:void 0,updatedAt:a}),this.emit({type:"human_answered",jobId:r.id,answers:c,timestamp:a});let f=ve(r.stepHistory,n);if(!f)throw new Error(`Could not locate frame for execution ${n}`);let m=this.sequenceForFrameOnJob(r,i,f),j=f.index+1,g=await this.executeStepSequence(r,i,m,f.parentLoopExecutionId,f.iterationIndex,j);return g.outcome==="paused"||g.outcome==="failed"?g.job:f.parentLoopExecutionId!=null&&f.iterationIndex!=null?this.continueLoopAfterBody(g.job,i,f.parentLoopExecutionId,f.iterationIndex):this.completeJob(g.job,i)}async retryFailedJob(t){let e=await this.jobs.get(t);if(!e)throw new h(`Job not found: ${t}`);if(e.status!=="failed")throw new Xt(`Job ${t} is not failed (status: ${e.status})`);let r=e.parentJobId!=null&&e.parentStepExecutionId!=null&&e.fanOutIndex!=null,i=e.batchId!=null&&e.fanOutIndex!=null;if(!r&&!i)throw new b(`Job ${t} is not a retryable sub_workflow child or batch member`);if(r){let a=await this.jobs.get(e.parentJobId);if(!a)throw new h(`Parent job not found: ${e.parentJobId}`);let u=await this.createJob({workflowId:e.workflowId,subjectContext:e.subjectContext,inputValues:{},parentJobId:e.parentJobId,parentStepExecutionId:e.parentStepExecutionId,fanOutIndex:e.fanOutIndex,retryOf:e.id}),c=F(a.stepHistory,e.parentStepExecutionId,f=>({...f,status:"waiting_for_children",error:void 0,completedAt:void 0,childJobIds:[...f.childJobIds??[],u.id]}));return a=await this.persistJob({...a,status:"waiting_for_children",stepHistory:c,completedAt:void 0,updatedAt:new Date().toISOString()}),this.emit({type:"job_started",jobId:u.id,timestamp:new Date().toISOString()}),this.emit({type:"job_retried",jobId:u.id,retryOf:e.id,timestamp:new Date().toISOString()}),this.runJob(u.id),u}let n=await this.batches.get(e.batchId);if(!n)throw new h(`JobBatch not found: ${e.batchId}`);n.status!=="running"&&await this.batches.update(n.id,{status:"running",completedAt:null,notificationSent:!1});let s=await this.createJob({workflowId:e.workflowId,subjectContext:e.subjectContext,selection:e.selection,batchId:e.batchId,fanOutIndex:e.fanOutIndex,inputValues:{},retryOf:e.id});return this.emit({type:"job_started",jobId:s.id,timestamp:new Date().toISOString()}),this.emit({type:"job_retried",jobId:s.id,retryOf:e.id,timestamp:new Date().toISOString()}),this.runJob(s.id),s}async executeStepSequence(t,e,r,i,n,s){let a=t;for(let u=s;u<r.length;u++){let c=r[u],f=new Date().toISOString(),m={id:Ar(),stepDefinitionId:c.id,type:c.type,status:"running",startedAt:f},j=Or(a.stepHistory,m,i,n);a=await this.persistJob({...a,status:a.status==="pending"?"planning":a.status,currentStepId:c.id,currentStepExecutionId:m.id,stepHistory:j,updatedAt:f}),this.emit({type:"step_started",jobId:a.id,stepDefinitionId:c.id,timestamp:f});try{let g=await this.dispatchStep(a,e,c,m.id,i,n);if(a=g.job,g.outcome==="paused"||g.outcome==="failed")return g}catch(g){return{outcome:"failed",job:await this.failJob(a,e,m.id,c.id,g)}}}return i!=null&&n!=null&&(a=await this.persistJob({...a,stepHistory:_i(a.stepHistory,i,n),updatedAt:new Date().toISOString()})),{outcome:"completed",job:a}}async dispatchStep(t,e,r,i,n,s){switch(r.type){case"agent":return{outcome:"completed",job:await this.executeAgentStep(t,r,i)};case"interaction":return{outcome:"paused",job:await this.pauseForInteraction(t,e,r,i)};case"git":return{outcome:"completed",job:await this.executeGitStep(t,r,i)};case"provider_action":return{outcome:"completed",job:await this.executeProviderActionStep(t,r,i)};case"shell":return{outcome:"completed",job:await this.executeShellStep(t,r,i)};case"loop":return this.runLoopStep(t,e,r,i,n,s);case"sub_workflow":return this.runSubWorkflowStep(t,r,i);default:{let a=r;throw new b(`Step type '${a.type}' not yet supported by the Workflow Runner`)}}}async runLoopStep(t,e,r,i,n,s,a=0,u=r.maxIterations){let c=t,f=a;for(;;){if(f>=u)switch(r.onMaxIterations.action){case"fail":return c=await this.failExecution(c,e,i,r.id,`Loop '${r.id}' exceeded maxIterations (${u})`),{outcome:"failed",job:c};case"continue":return c=await this.finishExecution(c,i,r.id,{iterations:f,exitedOnMaxIterations:!0}),{outcome:"completed",job:c};case"ask_human":{let j={maxIterationsCheckpoint:!0,nextIteration:f,effectiveMaxIterations:u},g=new Date().toISOString(),R=F(c.stepHistory,i,k=>({...k,status:"pending",output:j}));return c=await this.persistJob({...c,status:"waiting_for_human",currentStepId:r.id,currentStepExecutionId:i,stepHistory:R,updatedAt:g}),this.emit({type:"waiting_for_human",jobId:c.id,stepDefinitionId:r.id,interaction:"confirmation",data:j,questions:[`Loop '${r.id}' reached maxIterations (${u}). Extend, continue, or cancel?`],timestamp:g}),e.notificationPolicy.triggers.includes("on_needs_input")&&await this.notifications.send({title:`Input needed: ${e.name}`,body:`Job ${c.id} hit max iterations on loop '${r.id}'`,jobId:c.id}),{outcome:"paused",job:c}}default:{let j=r.onMaxIterations;throw new Error(`Unknown onMaxIterations action: ${JSON.stringify(j)}`)}}let m=await this.executeStepSequence(c,e,r.steps,i,f,0);if(c=m.job,m.outcome==="paused")return m;if(m.outcome==="failed")return c=await this.failExecution(c,e,i,r.id,"Loop body failed"),{outcome:"failed",job:c};if(Oi(r.until,c.context))return c=await this.finishExecution(c,i,r.id,{iterations:f+1}),{outcome:"completed",job:c};f+=1}}async resumeAskHuman(t,e,r,i){let n=i,s=r.output;if(!s?.maxIterationsCheckpoint)throw new Error(`Loop execution ${r.id} is not at an ask_human checkpoint`);let a=Te(e.steps,r.stepDefinitionId);if(!a||a.type!=="loop")throw new Error(`Loop step definition '${r.stepDefinitionId}' not found`);let u=ve(t.stepHistory,r.id),c=new Date().toISOString();if(n.action==="cancel")return await this.failExecution({...t,status:"planning",currentStepId:void 0,currentStepExecutionId:void 0,updatedAt:c},e,r.id,a.id,"Loop cancelled by human at maxIterations checkpoint");if(n.action==="continue"){let R=await this.persistJob({...t,status:"planning",currentStepId:void 0,currentStepExecutionId:void 0,stepHistory:F(t.stepHistory,r.id,k=>({...k,status:"completed",completedAt:c,output:{iterations:s.nextIteration,exitedOnMaxIterations:!0,humanAction:"continue"}})),updatedAt:c});return this.emit({type:"human_answered",jobId:R.id,answers:n,timestamp:c}),this.emit({type:"step_completed",jobId:R.id,stepDefinitionId:a.id,timestamp:c}),u?.parentLoopExecutionId!=null&&u.iterationIndex!=null?this.continueLoopAfterBody(R,e,u.parentLoopExecutionId,u.iterationIndex):this.continueTopLevelAfter(R,e,a.id)}let f=typeof n.additionalIterations=="number"?n.additionalIterations:0,m=s.effectiveMaxIterations+f,j=await this.persistJob({...t,status:"planning",currentStepId:void 0,currentStepExecutionId:void 0,stepHistory:F(t.stepHistory,r.id,R=>({...R,status:"running",output:void 0})),updatedAt:c});this.emit({type:"human_answered",jobId:j.id,answers:n,timestamp:c});let g=await this.runLoopStep(j,e,a,r.id,u?.parentLoopExecutionId,u?.iterationIndex,s.nextIteration,m);return g.outcome==="paused"||g.outcome==="failed"?g.job:u?.parentLoopExecutionId!=null&&u.iterationIndex!=null?this.continueLoopAfterBody(g.job,e,u.parentLoopExecutionId,u.iterationIndex):this.continueTopLevelAfter(g.job,e,a.id)}async continueLoopAfterBody(t,e,r,i){let n=ie(t.stepHistory,r);if(!n)throw new Error(`Loop execution ${r} not found`);let s=Te(e.steps,n.stepDefinitionId);if(!s||s.type!=="loop")throw new Error(`Loop step '${n.stepDefinitionId}' not found`);let a=ve(t.stepHistory,r),u=n.output?.effectiveMaxIterations??s.maxIterations,c=t;if(Oi(s.until,c.context))c=await this.finishExecution(c,r,s.id,{iterations:i+1});else{let f=i+1,m=await this.runLoopStep(c,e,s,r,a?.parentLoopExecutionId,a?.iterationIndex,f,u);if(m.outcome==="paused"||m.outcome==="failed")return m.job;c=m.job}return a?.parentLoopExecutionId!=null&&a.iterationIndex!=null?this.continueLoopAfterBody(c,e,a.parentLoopExecutionId,a.iterationIndex):this.continueTopLevelAfter(c,e,s.id)}async continueTopLevelAfter(t,e,r){let i=e.steps.findIndex(s=>s.id===r),n=await this.executeStepSequence(t,e,e.steps,void 0,void 0,i+1);return n.outcome==="paused"||n.outcome==="failed"?n.job:this.completeJob(n.job,e)}sequenceForFrameOnJob(t,e,r){if(r.parentLoopExecutionId==null)return e.steps;let i=ie(t.stepHistory,r.parentLoopExecutionId);if(!i)throw new Error(`Parent loop execution ${r.parentLoopExecutionId} not found`);let n=Te(e.steps,i.stepDefinitionId);if(!n||n.type!=="loop")throw new Error(`Parent loop step '${i.stepDefinitionId}' not found`);return n.steps}async runSubWorkflowStep(t,e,r){if(!t.subjectContext||t.subjectContext.mode!=="collection")throw new b(`sub_workflow steps require subjectContext.mode === 'collection' (job ${t.id})`);let i=t.subjectContext.subjects,n=[];for(let f=0;f<i.length;f++){let m=i[f],j=await this.createJob({workflowId:e.workflowId,subjectContext:{mode:"single",subject:m},inputValues:{},parentJobId:t.id,parentStepExecutionId:r,fanOutIndex:f});n.push(j)}let s=n.map(f=>f.id),a=new Date().toISOString(),u=F(t.stepHistory,r,f=>({...f,status:"waiting_for_children",childJobIds:s})),c=await this.persistJob({...t,status:"waiting_for_children",currentStepId:e.id,currentStepExecutionId:r,stepHistory:u,updatedAt:a});for(let f of n)this.emit({type:"job_started",jobId:f.id,timestamp:a}),this.runJob(f.id);return{outcome:"paused",job:c}}async onChildTerminal(t){let e=await this.jobs.get(t);if(!e?.parentJobId||!e.parentStepExecutionId)return;let r=`${e.parentJobId}:${e.parentStepExecutionId}`;if(!this.childTerminalLocks.has(r)){this.childTerminalLocks.add(r);try{let i=(await this.jobs.list({parentJobId:e.parentJobId,parentStepExecutionId:e.parentStepExecutionId})).filter(k=>k.parentStepExecutionId===e.parentStepExecutionId),n=Pr(i,k=>k.fanOutIndex);if(!n?.allTerminal)return;let{activeJobs:s}=n,a=await this.jobs.get(e.parentJobId);if(!a||a.status!=="waiting_for_children"&&a.status!=="failed")return;let u=await this.requireWorkflow(a.workflowId),c=e.parentStepExecutionId,f=ie(a.stepHistory,c);if(!f||f.type!=="sub_workflow")return;if(s.some(k=>k.status==="failed")){await this.failExecution(a,u,c,f.stepDefinitionId,"One or more child jobs failed");return}let j=s.slice().sort((k,xa)=>(k.fanOutIndex??0)-(xa.fanOutIndex??0)).map(k=>({fanOutIndex:k.fanOutIndex,jobId:k.id,output:k.context})),g=new Date().toISOString();a=await this.persistJob({...a,status:"planning",context:{...a.context,[f.stepDefinitionId]:j},currentStepId:void 0,currentStepExecutionId:void 0,stepHistory:F(a.stepHistory,c,k=>({...k,status:"completed",completedAt:g,output:j})),completedAt:void 0,updatedAt:g}),this.emit({type:"step_completed",jobId:a.id,stepDefinitionId:f.stepDefinitionId,timestamp:g});let R=await this.continueTopLevelAfter(a,u,f.stepDefinitionId)}finally{this.childTerminalLocks.delete(r)}}}async onBatchMemberTerminal(t){let e=await this.jobs.get(t);if(!e?.batchId)return;let r=e.batchId;if(!this.batchTerminalLocks.has(r)){this.batchTerminalLocks.add(r);try{let i=await this.batches.get(e.batchId);if(!i||i.status!=="running")return;let n=await this.jobs.list({batchId:i.id}),s=Pr(n,m=>m.fanOutIndex);if(!s||s.groupCount!==i.resolvedSubjects.length||!s.allTerminal)return;let{activeJobs:a}=s,u=Ti(a),c=new Date().toISOString(),f=await this.batches.update(i.id,{status:u,completedAt:c});if(!f)return;if(this.emit({type:"batch_completed",batchId:f.id,summary:a.map(m=>({jobId:m.id,status:m.status})),timestamp:c}),!f.notificationSent){let m=await this.requireWorkflow(f.workflowId),j=f.notificationOverride??m.notificationPolicy,g=u==="completed"?"on_complete":"on_fail";j.triggers.includes(g)&&await this.notifications.send({title:`Batch ${u}: ${m.name}`,body:`JobBatch ${f.id} finished with status '${u}' (${a.length} members)`,batchId:f.id}),await this.batches.update(f.id,{notificationSent:!0})}}finally{this.batchTerminalLocks.delete(r)}}}async resolveSelection(t){if(t.mode==="view")return bo(t.viewId,this.views,{tickets:this.tickets,repo:this.repo,documentation:this.documentation});let e=[];for(let r of t.subjectIds)if(t.subjectType==="ticket"){let i=await this.tickets.get(r);e.push({subjectType:"ticket",...i})}else if(t.subjectType==="pull_request"){let i=await this.repo.get(r);e.push({subjectType:"pull_request",...i})}else if(t.subjectType==="documentation"){let i=await this.documentation.get(r);e.push({subjectType:"documentation",...i})}else throw new b(`Unsupported subjectType: ${t.subjectType}`);return e}async executeAgentStep(t,e,r){let i=e.knowledgeScope?.length?e.knowledgeScope:Il,n=await this.resolveKnowledge(i),s=wo(t),a=ho(e.objective,s),u=await this.agent.run({objective:a,outputFormat:e.outputFormat,knowledge:n,context:{...s,stepId:e.id},...t.worktreePath?{cwd:t.worktreePath}:{}}),c=xi(e.outputFormat,u.parsed);return this.finishExecution(t,r,e.id,c)}async executeGitStep(t,e,r){let i=Ee(e.params,wo(t));switch(e.operation){case"create_worktree":{let n=await this.git.createWorktree(t.id,{repoPath:mt(i,"repoPath"),baseBranch:mt(i,"baseBranch"),branchName:mt(i,"branchName"),...typeof i.worktreePath=="string"?{worktreePath:i.worktreePath}:{}});return this.finishExecution(t,r,e.id,n,{worktreePath:n.worktreePath,branch:n.branch})}case"create_branch":{let n=yo(t),s=mt(i,"branchName");return await this.git.createBranch(n,{branchName:s,...typeof i.baseBranch=="string"?{baseBranch:i.baseBranch}:{}}),this.finishExecution(t,r,e.id,{branch:s},{branch:s})}case"checkout":{let n=yo(t),s=mt(i,"branch");return await this.git.checkout(n,{branch:s}),this.finishExecution(t,r,e.id,{branch:s},{branch:s})}case"commit":{let n=yo(t),s=await this.git.commit(n,{message:mt(i,"message"),addAll:i.addAll!==!1});return this.finishExecution(t,r,e.id,s)}case"push":{let n=yo(t);return await this.git.push(n,{...typeof i.remote=="string"?{remote:i.remote}:{},...typeof i.branch=="string"?{branch:i.branch}:{}}),this.finishExecution(t,r,e.id,{remote:typeof i.remote=="string"?i.remote:"origin",branch:typeof i.branch=="string"?i.branch:t.branch})}default:{let n=e.operation;throw new Error(`Unknown git operation: ${n}`)}}}async executeProviderActionStep(t,e,r){if(!t.subjectContext||t.subjectContext.mode!=="single")throw new b(`provider_action steps require subjectContext.mode === 'single' (job ${t.id})`);let i=t.subjectContext.subject,n=i.id,s=Ee(e.params??{},wo(t))??{},a;if(i.subjectType==="documentation")switch(e.action){case"get_subject":a=await this.documentation.get(n);break;case"get_content":a=await this.documentation.getContent(n);break;case"get_comments":a=await this.documentation.getComments(n);break;case"post_comment":await this.documentation.postComment(n,mt(s,"body")),a={posted:!0};break;case"update_status":throw new Error(`Provider action '${e.action}' is not valid for subject type 'documentation'`);default:{let u=e.action;throw new Error(`Unknown provider action: ${u}`)}}else{let u=i.subjectType==="ticket"?this.tickets:i.subjectType==="pull_request"?this.repo:null;if(!u)throw new Error(`Unsupported subjectType for provider_action: ${i.subjectType}`);switch(e.action){case"get_subject":a=await u.get(n);break;case"get_comments":a=await u.getComments(n);break;case"post_comment":await u.postComment(n,mt(s,"body")),a={posted:!0};break;case"update_status":await u.updateStatus(n,mt(s,"status")),a={status:mt(s,"status")};break;case"get_content":throw new Error(`Provider action 'get_content' is not valid for subject type '${i.subjectType}'`);default:{let c=e.action;throw new Error(`Unknown provider action: ${c}`)}}}return this.finishExecution(t,r,e.id,a)}async executeShellStep(t,e,r){let i=ho(e.command,wo(t)),n=t.worktreePath??process.cwd();try{let s=await _l(i,{cwd:n,windowsHide:!0});return this.finishExecution(t,r,e.id,{exitCode:0,stdout:String(s.stdout??""),stderr:String(s.stderr??"")})}catch(s){let a=s,u=a.stderr??"",c=a.stdout??"",f=typeof a.code=="number"?a.code:Number.parseInt(String(a.code??"1"),10)||1;throw new Error(`shell command failed (exit ${f}, cwd=${n}): ${u||c||a.message||i}`)}}async pauseForInteraction(t,e,r,i){let n=new Date().toISOString(),s=xl(e,r.id),a=s!=null?t.context[s]:void 0,u=F(t.stepHistory,i,j=>({...j,status:"pending"})),c=await this.persistJob({...t,status:"waiting_for_human",currentStepId:r.id,currentStepExecutionId:i,stepHistory:u,updatedAt:n}),f=Si(r.interaction,a);return this.emit({type:"waiting_for_human",jobId:c.id,stepDefinitionId:r.id,interaction:r.interaction,data:a,questions:f,timestamp:n}),e.notificationPolicy.triggers.includes("on_needs_input")&&r.notify!==!1&&await this.notifications.send({title:`Input needed: ${e.name}`,body:`Job ${c.id} is waiting for human input on step '${r.id}'`,jobId:c.id}),c}async finishExecution(t,e,r,i,n={}){let s=new Date().toISOString(),a=F(t.stepHistory,e,c=>({...c,status:"completed",completedAt:s,output:i})),u=await this.persistJob({...t,...n,context:{...t.context,[r]:i},stepHistory:a,updatedAt:s});return this.emit({type:"step_completed",jobId:u.id,stepDefinitionId:r,timestamp:s}),u}async failExecution(t,e,r,i,n){return this.failJob(t,e,r,i,new Error(n))}async completeJob(t,e){let r=new Date().toISOString(),i=await this.persistJob({...t,status:"completed",currentStepId:void 0,currentStepExecutionId:void 0,completedAt:r,updatedAt:r});return this.emit({type:"job_completed",jobId:i.id,timestamp:r}),await this.onBatchMemberTerminal(i.id),!i.batchId&&e.notificationPolicy.triggers.includes("on_complete")&&await this.notifications.send({title:`Job completed: ${e.name}`,body:`Job ${i.id} completed successfully`,jobId:i.id}),i}async failJob(t,e,r,i,n){let s=n instanceof Error?n.message:String(n),a=new Date().toISOString(),u=F(t.stepHistory,r,f=>({...f,status:"failed",completedAt:a,error:s})),c=await this.persistJob({...t,status:"failed",stepHistory:u,completedAt:a,updatedAt:a});return this.emit({type:"step_failed",jobId:c.id,stepDefinitionId:i,error:s,timestamp:a}),this.emit({type:"job_failed",jobId:c.id,error:s,timestamp:a}),await this.onBatchMemberTerminal(c.id),!c.batchId&&e.notificationPolicy.triggers.includes("on_fail")&&await this.notifications.send({title:`Job failed: ${e.name}`,body:`Job ${c.id} failed on step '${i}': ${s}`,jobId:c.id}),c}async resolveSubjectContext(t,e){if(t.appliesTo==="none")return;let r=El(t.appliesTo);if(!e)throw new Error(`Workflow '${t.id}' applies to '${r}' but no subjectId was provided`);if(r==="ticket")return{mode:"single",subject:{subjectType:"ticket",...await this.tickets.get(e)}};if(r==="pull_request")return{mode:"single",subject:{subjectType:"pull_request",...await this.repo.get(e)}};if(r==="documentation")return{mode:"single",subject:{subjectType:"documentation",...await this.documentation.get(e)}};throw new Error(`Unsupported subjectType for workflow subject resolution: ${r}`)}async resolveKnowledge(t){let e=[];for(let r of t)e.push(...await this.knowledge.resolve(r));return e}async requireWorkflow(t){let e=await this.workflows.get(t);if(!e)throw new h(`Workflow not found: ${t}`);return e}async persistJob(t){let e=await this.jobs.update(t.id,{status:t.status,context:t.context,currentStepId:t.currentStepId,currentStepExecutionId:t.currentStepExecutionId,stepHistory:t.stepHistory,worktreePath:t.worktreePath,branch:t.branch,updatedAt:t.updatedAt,completedAt:t.completedAt});if(!e)throw new Error(`Failed to persist job ${t.id}`);return e}emit(t){this.events.emit(t)}};it=wl([gl(),G(0,z(O)),G(1,z(P)),G(2,z(K)),G(3,z(X)),G(4,z(nt)),G(5,z(Ut)),G(6,z(Ft)),G(7,z(Jt)),G(8,z(me)),G(9,z(we)),G(10,z(ye)),G(11,z(It)),yl("design:paramtypes",[O,P,K,X,nt,Object,Object,Object,Object,Object,Object,It])],it)});import{Module as Tl}from"@nestjs/common";var vl,se,Nr=p(()=>{"use strict";xe();uo();fo();yi();go();vl=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},se=class{};se=vl([Tl({imports:[ft,Nt,qt,mo],providers:[it],exports:[it]})],se)});import{Catch as Ol}from"@nestjs/common";var Rl,So,ki=p(()=>{"use strict";D();Rl=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},So=class{catch(t,e){e.switchToHttp().getResponse().status(t.httpStatus).json({error:t.message})}};So=Rl([Ol(Wt)],So)});import{z as _}from"zod";var Pl,Ai,qr,jo,Ni,Cr=p(()=>{"use strict";Pl=_.object({name:_.string().min(1),label:_.string().min(1),type:_.enum(["string","select"]),options:_.array(_.string()).optional(),required:_.boolean()}),Ai=_.object({id:_.string().min(1),label:_.string().min(1),params:_.array(Pl)}),qr=_.object({templateId:_.string().min(1),params:_.record(_.string(),_.unknown())}),jo=_.object({params:_.record(_.string(),_.unknown())}),Ni=_.object({query:_.record(_.string(),_.unknown())})});import{z as J}from"zod";var ht,_o,Io,xo,Eo,Dr=p(()=>{"use strict";Cr();ht=J.enum(["ticket","pull_request","documentation"]),_o=J.object({id:J.string().min(1),name:J.string().min(1),subjectType:ht,workflowId:J.string().min(1),query:J.record(J.string(),J.unknown()),description:J.string().optional(),queryTemplate:qr.optional(),order:J.number().int().nonnegative()}),Io=_o.omit({order:!0}),xo=_o.partial().omit({id:!0,order:!0}).extend({queryTemplate:qr.nullable().optional()}),Eo=J.object({viewIds:J.array(J.string().min(1)).min(1)})});var qi=p(()=>{"use strict";Dr()});var Ci=p(()=>{"use strict";Cr()});function kl(o){let t=o.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"");return t.length>0?t:"step"}function Di(o,t){let e=kl(o);if(!t.has(e))return e;let r=2;for(;t.has(`${e}-${r}`);)r+=1;return`${e}-${r}`}function Bi(o,t){for(let e of o)e.id&&t.push(e.id),e.type==="loop"&&Array.isArray(e.steps)&&Bi(e.steps,t)}function $i(o){let t=[];Bi(o,t);let e=new Map;for(let r of t)e.set(r,(e.get(r)??0)+1);return[...e.entries()].filter(([,r])=>r>1).map(([r])=>r)}function Li(o){let t=new Set,e=r=>{for(let i of r)i.id&&t.add(i.id),i.type==="loop"&&Array.isArray(i.steps)&&e(i.steps)};return e(o),t}var Br=p(()=>{"use strict"});import{z as d}from"zod";var Al,Re,Nl,Ct,Ui,Fi,Ji,Mi,Vi,Wi,Xi,Ki,ql,Hi,Gi,Oe,Cl,Dl,Bl,$l,Ll,Ul,Fl,zi,ae,Qi=p(()=>{"use strict";Dr();Br();Al=d.enum(["on_fail","on_complete","on_needs_input"]),Re=d.object({triggers:d.array(Al),messageTemplate:d.string().optional()}),Nl=d.object({name:d.string().min(1),label:d.string().min(1),type:d.enum(["string","number","boolean","select"]),options:d.array(d.string()).optional(),required:d.boolean(),defaultValue:d.unknown().optional()}),Ct=d.string().min(1),Ui=d.object({type:d.literal("agent"),id:d.string().min(1),name:Ct,objective:d.string().min(1),knowledgeScope:d.array(d.enum(["user","organization","project"])).optional(),outputFormat:d.enum(["questionnaire","confirmation","comment_suggestions","free_text"])}),Fi=d.object({type:d.literal("interaction"),id:d.string().min(1),name:Ct,interaction:d.union([d.literal("questionnaire"),d.literal("confirmation"),d.literal("conversation")]),notify:d.boolean().optional()}),Ji=d.object({type:d.literal("shell"),id:d.string().min(1),name:Ct,command:d.string().min(1)}),Mi=d.object({type:d.literal("git"),id:d.string().min(1),name:Ct,operation:d.enum(["create_worktree","checkout","create_branch","commit","push"]),params:d.record(d.string(),d.unknown())}),Vi=d.object({type:d.literal("provider_action"),id:d.string().min(1),name:Ct,action:d.enum(["get_subject","get_comments","post_comment","update_status","get_content"]),params:d.record(d.string(),d.unknown()).optional()}),Wi=d.object({type:d.literal("sub_workflow"),id:d.string().min(1),name:Ct,workflowId:d.string().min(1),forEach:d.literal("selection")}),Xi=d.discriminatedUnion("type",[d.object({type:d.literal("field_empty"),stepId:d.string().min(1),field:d.string().min(1)}),d.object({type:d.literal("field_equals"),stepId:d.string().min(1),field:d.string().min(1),value:d.unknown()})]),Ki=d.discriminatedUnion("action",[d.object({action:d.literal("fail")}),d.object({action:d.literal("continue")}),d.object({action:d.literal("ask_human")})]),ql=d.object({type:d.literal("loop"),id:d.string().min(1),name:Ct,steps:d.array(d.lazy(()=>Hi)),until:Xi,maxIterations:d.number().int().nonnegative(),onMaxIterations:Ki}),Hi=d.lazy(()=>d.discriminatedUnion("type",[Mi,Vi,Ji,Ui,Fi,Wi,ql])),Gi=d.object({id:d.string().min(1),name:d.string().min(1),description:d.string().optional(),appliesTo:d.union([ht,d.array(ht),d.literal("none")]),cardinality:d.enum(["single","batch","aggregate"]),inputSchema:d.array(Nl),steps:d.array(Hi),notificationPolicy:Re}),Oe=Gi.superRefine((o,t)=>{let e=$i(o.steps);e.length!==0&&t.addIssue({code:"custom",path:["steps"],message:`Duplicate step id(s): ${e.join(", ")}`})}),Cl=Ui.extend({id:d.string().min(1).optional()}),Dl=Fi.extend({id:d.string().min(1).optional()}),Bl=Ji.extend({id:d.string().min(1).optional()}),$l=Mi.extend({id:d.string().min(1).optional()}),Ll=Vi.extend({id:d.string().min(1).optional()}),Ul=Wi.extend({id:d.string().min(1).optional()}),Fl=d.object({type:d.literal("loop"),id:d.string().min(1).optional(),name:Ct,steps:d.array(d.lazy(()=>zi)),until:Xi,maxIterations:d.number().int().nonnegative(),onMaxIterations:Ki}),zi=d.lazy(()=>d.discriminatedUnion("type",[$l,Ll,Bl,Cl,Dl,Ul,Fl])),ae=Gi.omit({id:!0,steps:!0}).extend({id:d.string().min(1).optional(),steps:d.array(zi)})});function Jl(o){return o==="none"?[]:Array.isArray(o)?o:[o]}function Yi(o,t){return Jl(o).includes(t)}var Zi=p(()=>{"use strict"});var ts=p(()=>{"use strict";Qi();Br();Zi()});var es=p(()=>{"use strict"});var os=p(()=>{"use strict";es()});var rs=p(()=>{"use strict"});var ns=p(()=>{"use strict";rs()});var is=p(()=>{"use strict"});var ss=p(()=>{"use strict";is()});import{z as $}from"zod";var ce,as=p(()=>{"use strict";ce=$.object({id:$.string().min(1),viewId:$.string().min(1),trigger:$.object({type:$.literal("cron"),cadence:$.string().min(1)}),notificationOverride:$.object({triggers:$.array($.enum(["on_fail","on_complete","on_needs_input"])),messageTemplate:$.string().optional()}).optional(),missedFirePolicy:$.enum(["skip","catch_up"]),enabled:$.boolean(),lastFiredAt:$.string().optional(),createdAt:$.string()})});var cs=p(()=>{"use strict";as()});import{z as Q}from"zod";var vo,To,Ro,Oo,us=p(()=>{"use strict";vo=Q.object({id:Q.string().min(1),name:Q.string().min(1),workflowId:Q.string().min(1),inputValues:Q.record(Q.string(),Q.unknown()),lastJobId:Q.string().min(1).optional(),order:Q.number().int().nonnegative()}),To=vo.omit({order:!0}),Ro=vo.partial().omit({id:!0,order:!0}),Oo=Q.object({shortcutIds:Q.array(Q.string().min(1)).min(1)})});var ls=p(()=>{"use strict";us()});import{z as Y}from"zod";var ps,ds,fs,ms,$r,Po,hs=p(()=>{"use strict";ps=Y.string().min(1).refine(o=>{try{let t=new URL(o);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}},{message:"Must be an http(s) URL"}).optional(),ds=Y.object({ticket:Y.enum(["jira","manual"]).optional(),repo:Y.enum(["bitbucket","manual"]).optional(),agent:Y.enum(["claude","cursor"]).optional()}),fs=Y.object({baseUrl:ps,email:Y.string().min(1).optional()}),ms=Y.object({baseUrl:ps,email:Y.string().min(1).optional(),workspace:Y.string().min(1).optional()}),$r=Y.object({activeProviders:ds.optional(),jira:fs.optional(),bitbucket:ms.optional()}),Po=Y.object({activeProviders:ds.optional(),jira:fs.partial().optional(),bitbucket:ms.partial().optional()})});var bs=p(()=>{"use strict";hs()});var ws=p(()=>{"use strict"});var ys=p(()=>{"use strict";ws()});var Z=p(()=>{"use strict";qi();Ci();ts();os();ns();ss();cs();ls();bs();ys()});var S,bt=p(()=>{"use strict";D();S=class{schema;constructor(t){this.schema=t}transform(t){let e=this.schema.safeParse(t);if(!e.success){let r=e.error.issues.map(i=>`${i.path.join(".")||"(root)"}: ${i.message}`).join("; ");throw new b(`Validation failed: ${r}`)}return e.data}}});import{randomUUID as Ml}from"node:crypto";function Vl(){return Ml()}function Lr(o){let t=o.id??Vl(),e=Li(o.steps),r=gs(o.steps,e);return{...o,id:t,steps:r}}function gs(o,t){return o.map(e=>{let r=e.id;return r||(r=Di(e.name,t),t.add(r)),e.type==="loop"?{...e,id:r,steps:gs(e.steps,t)}:{...e,id:r}})}var Ss=p(()=>{"use strict";Z()});import{Body as _s,Controller as Wl,Delete as Xl,Get as Is,HttpCode as Kl,Inject as js,Param as Ur,Patch as Hl,Post as Gl,Query as zl}from"@nestjs/common";var ue,q,Dt,Ql,xt,xs=p(()=>{"use strict";Z();ee();oe();D();bt();Ss();ue=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},q=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},Dt=function(o,t){return function(e,r){t(e,r,o)}},Ql=new Set(["completed","failed","cancelled"]),xt=class{workflows;jobs;constructor(t,e){this.workflows=t,this.jobs=e}async list(t){if(t!=null&&t!==""&&t!=="single"&&t!=="batch"&&t!=="aggregate")throw new b(`Invalid cardinality filter: ${t}`);return this.workflows.list(t?{cardinality:t}:{})}async get(t){let e=await this.workflows.get(t);if(!e)throw new h(`Workflow not found: ${t}`);return e}async create(t){let e=Lr(t),r=Oe.safeParse(e);if(!r.success){let i=r.error.issues.map(n=>`${n.path.join(".")||"(root)"}: ${n.message}`).join("; ");throw new b(`Validation failed: ${i}`)}return this.workflows.create(r.data)}async update(t,e){let r=Lr({...e,id:t}),i=Oe.safeParse(r);if(!i.success){let u=i.error.issues.map(c=>`${c.path.join(".")||"(root)"}: ${c.message}`).join("; ");throw new b(`Validation failed: ${u}`)}let{id:n,...s}=i.data,a=await this.workflows.update(t,s);if(!a)throw new h(`Workflow not found: ${t}`);return a}async remove(t){if(!await this.workflows.get(t))throw new h(`Workflow not found: ${t}`);let i=(await this.jobs.list({workflowId:t})).filter(s=>!Ql.has(s.status));if(i.length>0){let s=i.length===1?"Job":"Jobs";throw new Xt(`Cannot delete workflow ${t}: ${i.length} non-terminal ${s} still reference it`)}if(!await this.workflows.delete(t))throw new h(`Workflow not found: ${t}`)}};ue([Is(),Dt(0,zl("cardinality")),q("design:type",Function),q("design:paramtypes",[String]),q("design:returntype",Promise)],xt.prototype,"list",null);ue([Is(":id"),Dt(0,Ur("id")),q("design:type",Function),q("design:paramtypes",[String]),q("design:returntype",Promise)],xt.prototype,"get",null);ue([Gl(),Dt(0,_s(new S(ae))),q("design:type",Function),q("design:paramtypes",[Object]),q("design:returntype",Promise)],xt.prototype,"create",null);ue([Hl(":id"),Dt(0,Ur("id")),Dt(1,_s(new S(ae))),q("design:type",Function),q("design:paramtypes",[String,Object]),q("design:returntype",Promise)],xt.prototype,"update",null);ue([Xl(":id"),Kl(204),Dt(0,Ur("id")),q("design:type",Function),q("design:paramtypes",[String]),q("design:returntype",Promise)],xt.prototype,"remove",null);xt=ue([Wl("workflows"),Dt(0,js(O)),Dt(1,js(P)),q("design:paramtypes",[O,P])],xt)});function Es(o,t,e){if(!o)throw new h(`Workflow not found: ${t}`);if(o.appliesTo==="none")throw new b(`Cannot bind a View to workflow '${t}' because appliesTo is 'none'`);if(!Yi(o.appliesTo,e))throw new b(`subjectType '${e}' is not included in workflow '${t}' appliesTo`);return o}function vs(o,t){if(!o)throw new h(`Workflow not found: ${t}`);if(o.appliesTo!=="none")throw new b(`WorkflowShortcut requires appliesTo 'none', got '${String(o.appliesTo)}'`);if(o.cardinality!=="single")throw new b(`WorkflowShortcut requires cardinality 'single', got '${o.cardinality}'`);return o}var Fr=p(()=>{"use strict";Z();D()});import{Body as Jr,Controller as Yl,Delete as Zl,Get as Mr,HttpCode as tp,Inject as Pe,Param as ko,Patch as Ts,Post as ep,Query as op}from"@nestjs/common";var Bt,I,M,st,Rs=p(()=>{"use strict";Z();to();ee();D();bt();Fr();Be();Le();Fe();kr();Bt=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},I=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},M=function(o,t){return function(e,r){t(e,r,o)}},st=class{views;workflows;tickets;repo;documentation;constructor(t,e,r,i,n){this.views=t,this.workflows=e,this.tickets=r,this.repo=i,this.documentation=n}async list(t){if(t!=null&&t!==""){let e=ht.safeParse(t);if(!e.success)throw new b(`Invalid subjectType filter: ${t}`);return this.views.list({subjectType:e.data})}return this.views.list({})}async reorder(t){let e=[];for(let n of t.viewIds){let s=await this.views.get(n);if(!s)throw new b(`Unknown view id in reorder: ${n}`);e.push(s)}if(new Set(e.map(n=>n.subjectType)).size!==1)throw new b("All viewIds in a reorder request must share the same subjectType");return await this.views.reorder(t.viewIds)}async listSubjects(t){return bo(t,this.views,{tickets:this.tickets,repo:this.repo,documentation:this.documentation})}async get(t){let e=await this.views.get(t);if(!e)throw new h(`SubjectView not found: ${t}`);return e}async create(t){return await this.assertBinding(t.workflowId,t.subjectType),this.views.create(t)}async update(t,e){let r=await this.views.get(t);if(!r)throw new h(`SubjectView not found: ${t}`);await this.assertBinding(e.workflowId??r.workflowId,e.subjectType??r.subjectType);let i=await this.views.update(t,e);if(!i)throw new h(`SubjectView not found: ${t}`);return i}async remove(t){if(!await this.views.delete(t))throw new h(`SubjectView not found: ${t}`)}async assertBinding(t,e){let r=await this.workflows.get(t);Es(r,t,e)}};Bt([Mr(),M(0,op("subjectType")),I("design:type",Function),I("design:paramtypes",[String]),I("design:returntype",Promise)],st.prototype,"list",null);Bt([Ts("reorder"),M(0,Jr(new S(Eo))),I("design:type",Function),I("design:paramtypes",[Object]),I("design:returntype",Promise)],st.prototype,"reorder",null);Bt([Mr(":id/subjects"),M(0,ko("id")),I("design:type",Function),I("design:paramtypes",[String]),I("design:returntype",Promise)],st.prototype,"listSubjects",null);Bt([Mr(":id"),M(0,ko("id")),I("design:type",Function),I("design:paramtypes",[String]),I("design:returntype",Promise)],st.prototype,"get",null);Bt([ep(),M(0,Jr(new S(Io))),I("design:type",Function),I("design:paramtypes",[Object]),I("design:returntype",Promise)],st.prototype,"create",null);Bt([Ts(":id"),M(0,ko("id")),M(1,Jr(new S(xo))),I("design:type",Function),I("design:paramtypes",[String,Object]),I("design:returntype",Promise)],st.prototype,"update",null);Bt([Zl(":id"),tp(204),M(0,ko("id")),I("design:type",Function),I("design:paramtypes",[String]),I("design:returntype",Promise)],st.prototype,"remove",null);st=Bt([Yl("views"),M(0,Pe(X)),M(1,Pe(O)),M(2,Pe(Ut)),M(3,Pe(Ft)),M(4,Pe(Jt)),I("design:paramtypes",[X,O,Object,Object,Object])],st)});import{Body as Vr,Controller as rp,Delete as np,Get as Ps,HttpCode as ip,Inject as Os,Param as Wr,Patch as ks,Post as sp}from"@nestjs/common";var Kt,E,$t,wt,As=p(()=>{"use strict";Z();yr();ee();D();bt();Fr();Kt=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},E=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},$t=function(o,t){return function(e,r){t(e,r,o)}},wt=class{shortcuts;workflows;constructor(t,e){this.shortcuts=t,this.workflows=e}async list(){return this.shortcuts.list()}async reorder(t){for(let e of t.shortcutIds)if(!await this.shortcuts.get(e))throw new b(`Unknown shortcut id in reorder: ${e}`);return this.shortcuts.reorder(t.shortcutIds)}async get(t){let e=await this.shortcuts.get(t);if(!e)throw new h(`WorkflowShortcut not found: ${t}`);return e}async create(t){return await this.assertBinding(t.workflowId),this.shortcuts.create(t)}async update(t,e){let r=await this.shortcuts.get(t);if(!r)throw new h(`WorkflowShortcut not found: ${t}`);await this.assertBinding(e.workflowId??r.workflowId);let i=await this.shortcuts.update(t,e);if(!i)throw new h(`WorkflowShortcut not found: ${t}`);return i}async remove(t){if(!await this.shortcuts.delete(t))throw new h(`WorkflowShortcut not found: ${t}`)}async assertBinding(t){let e=await this.workflows.get(t);vs(e,t)}};Kt([Ps(),E("design:type",Function),E("design:paramtypes",[]),E("design:returntype",Promise)],wt.prototype,"list",null);Kt([ks("reorder"),$t(0,Vr(new S(Oo))),E("design:type",Function),E("design:paramtypes",[Object]),E("design:returntype",Promise)],wt.prototype,"reorder",null);Kt([Ps(":id"),$t(0,Wr("id")),E("design:type",Function),E("design:paramtypes",[String]),E("design:returntype",Promise)],wt.prototype,"get",null);Kt([sp(),$t(0,Vr(new S(To))),E("design:type",Function),E("design:paramtypes",[Object]),E("design:returntype",Promise)],wt.prototype,"create",null);Kt([ks(":id"),$t(0,Wr("id")),$t(1,Vr(new S(Ro))),E("design:type",Function),E("design:paramtypes",[String,Object]),E("design:returntype",Promise)],wt.prototype,"update",null);Kt([np(":id"),ip(204),$t(0,Wr("id")),E("design:type",Function),E("design:paramtypes",[String]),E("design:returntype",Promise)],wt.prototype,"remove",null);wt=Kt([rp("workflow-shortcuts"),$t(0,Os(_t)),$t(1,Os(O)),E("design:paramtypes",[_t,O])],wt)});function Ao(o,t,e=50){let r=o!=null&&o!==""?Number(o):e,i=t!=null&&t!==""?Number(t):0;return!Number.isFinite(r)||r<1?{limit:e,offset:Math.max(0,i||0)}:!Number.isFinite(i)||i<0?{limit:r,offset:0}:{limit:Math.floor(r),offset:Math.floor(i)}}function No(o,t,e){return o.slice(e,e+t)}var Xr=p(()=>{"use strict"});import{z as tt}from"zod";var qo,Co,Do,Kr=p(()=>{"use strict";qo=tt.object({workflowId:tt.string().min(1),subjectId:tt.string().min(1).optional(),inputValues:tt.record(tt.string(),tt.unknown())}),Co=tt.object({response:tt.unknown()}),Do=tt.object({workflowId:tt.string().min(1),subjectIds:tt.array(tt.string().min(1))})});import{Body as Hr,Controller as ap,Get as qs,HttpCode as cp,Inject as Ns,Param as Gr,Post as Bo,Query as Ht}from"@nestjs/common";import"zod";var Gt,v,B,up,yt,Cs=p(()=>{"use strict";go();oe();D();bt();Xr();Kr();Gt=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},v=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},B=function(o,t){return function(e,r){t(e,r,o)}},up=["pending","planning","waiting_for_human","waiting_for_children","implementing","testing","completed","failed","cancelled"],yt=class{jobs;runner;constructor(t,e){this.jobs=t,this.runner=e}async list(t,e,r,i,n,s,a){if(e!=null&&e!==""&&!up.includes(e))throw new b(`Invalid status filter: ${e}`);if(n!=null&&n!==""&&n!=="true"&&n!=="false")throw new b(`Invalid topLevelOnly filter: ${n}`);let{limit:u,offset:c}=Ao(s,a),f=await this.jobs.list({...t?{workflowId:t}:{},...e?{status:e}:{},...r?{batchId:r}:{},...i?{parentJobId:i}:{},...n==="true"?{topLevelOnly:!0}:{}});return No(f,u,c)}async latestBySubject(t){return this.jobs.latestBySubject(t.workflowId,t.subjectIds)}async get(t){let e=await this.jobs.get(t);if(!e)throw new h(`Job not found: ${t}`);return e}async create(t){return this.runner.start({workflowId:t.workflowId,...t.subjectId?{subjectId:t.subjectId}:{},inputValues:t.inputValues})}async resume(t,e){return this.runner.resume(t,e.response)}async retry(t){return this.runner.retryFailedJob(t)}};Gt([qs(),B(0,Ht("workflowId")),B(1,Ht("status")),B(2,Ht("batchId")),B(3,Ht("parentJobId")),B(4,Ht("topLevelOnly")),B(5,Ht("limit")),B(6,Ht("offset")),v("design:type",Function),v("design:paramtypes",[String,String,String,String,String,String,String]),v("design:returntype",Promise)],yt.prototype,"list",null);Gt([Bo("latest-by-subject"),cp(200),B(0,Hr(new S(Do))),v("design:type",Function),v("design:paramtypes",[Object]),v("design:returntype",Promise)],yt.prototype,"latestBySubject",null);Gt([qs(":id"),B(0,Gr("id")),v("design:type",Function),v("design:paramtypes",[String]),v("design:returntype",Promise)],yt.prototype,"get",null);Gt([Bo(),B(0,Hr(new S(qo))),v("design:type",Function),v("design:paramtypes",[Object]),v("design:returntype",Promise)],yt.prototype,"create",null);Gt([Bo(":id/resume"),B(0,Gr("id")),B(1,Hr(new S(Co))),v("design:type",Function),v("design:paramtypes",[String,Object]),v("design:returntype",Promise)],yt.prototype,"resume",null);Gt([Bo(":id/retry"),B(0,Gr("id")),v("design:type",Function),v("design:paramtypes",[String]),v("design:returntype",Promise)],yt.prototype,"retry",null);yt=Gt([ap("jobs"),B(0,Ns(P)),B(1,Ns(it)),v("design:paramtypes",[P,it])],yt)});import{z as L}from"zod";var $o,Lo,zr=p(()=>{"use strict";Z();$o=L.discriminatedUnion("mode",[L.object({mode:L.literal("view"),viewId:L.string().min(1)}),L.object({mode:L.literal("manual"),subjectType:ht,subjectIds:L.array(L.string().min(1))})]),Lo=L.object({workflowId:L.string().min(1),selection:$o,triggeredBy:L.enum(["schedule","view_bulk","multiselect"]),notificationOverride:Re.optional(),inputValues:L.record(L.string(),L.unknown())})});import{Body as lp,Controller as pp,Get as Zr,Inject as Qr,Param as Ds,Post as dp,Query as Yr}from"@nestjs/common";import"zod";var ke,V,Et,Lt,Bs=p(()=>{"use strict";go();eo();oe();D();bt();Xr();zr();ke=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},V=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},Et=function(o,t){return function(e,r){t(e,r,o)}},Lt=class{batches;jobs;runner;constructor(t,e,r){this.batches=t,this.jobs=e,this.runner=r}async list(t,e,r){let{limit:i,offset:n}=Ao(e,r),s=await this.batches.list(t?{workflowId:t}:{});return No(s,i,n)}async get(t){let e=await this.batches.get(t);if(!e)throw new h(`JobBatch not found: ${t}`);return e}async listJobs(t){if(!await this.batches.get(t))throw new h(`JobBatch not found: ${t}`);return this.jobs.list({batchId:t})}async launch(t){let e=await this.runner.launch({workflowId:t.workflowId,selection:t.selection,triggeredBy:t.triggeredBy,...t.notificationOverride?{notificationOverride:t.notificationOverride}:{},inputValues:t.inputValues});return"resolvedSubjects"in e&&"jobIds"in e?{kind:"batch",batch:e}:{kind:"job",job:e}}};ke([Zr(),Et(0,Yr("workflowId")),Et(1,Yr("limit")),Et(2,Yr("offset")),V("design:type",Function),V("design:paramtypes",[String,String,String]),V("design:returntype",Promise)],Lt.prototype,"list",null);ke([Zr(":id"),Et(0,Ds("id")),V("design:type",Function),V("design:paramtypes",[String]),V("design:returntype",Promise)],Lt.prototype,"get",null);ke([Zr(":id/jobs"),Et(0,Ds("id")),V("design:type",Function),V("design:paramtypes",[String]),V("design:returntype",Promise)],Lt.prototype,"listJobs",null);ke([dp(),Et(0,lp(new S(Lo))),V("design:type",Function),V("design:paramtypes",[Object]),V("design:returntype",Promise)],Lt.prototype,"launch",null);Lt=ke([pp("batches"),Et(0,Qr(K)),Et(1,Qr(P)),Et(2,Qr(it)),V("design:paramtypes",[K,P,it])],Lt)});import{Body as $s,Controller as fp,Delete as mp,Get as Ls,HttpCode as hp,Inject as bp,Param as tn,Patch as wp,Post as yp,Query as gp}from"@nestjs/common";var le,C,zt,vt,Us=p(()=>{"use strict";Z();br();D();bt();le=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},C=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},zt=function(o,t){return function(e,r){t(e,r,o)}},vt=class{schedules;constructor(t){this.schedules=t}async list(t){if(t==null||t==="")return this.schedules.list();if(t!=="true"&&t!=="false")throw new b(`Invalid enabled filter: ${t}`);return this.schedules.list({enabled:t==="true"})}async get(t){let e=await this.schedules.get(t);if(!e)throw new h(`Schedule not found: ${t}`);return e}async create(t){return this.schedules.create(t)}async update(t,e){let r=await this.schedules.update(t,e);if(!r)throw new h(`Schedule not found: ${t}`);return r}async remove(t){if(!await this.schedules.delete(t))throw new h(`Schedule not found: ${t}`)}};le([Ls(),zt(0,gp("enabled")),C("design:type",Function),C("design:paramtypes",[String]),C("design:returntype",Promise)],vt.prototype,"list",null);le([Ls(":id"),zt(0,tn("id")),C("design:type",Function),C("design:paramtypes",[String]),C("design:returntype",Promise)],vt.prototype,"get",null);le([yp(),zt(0,$s(new S(ce))),C("design:type",Function),C("design:paramtypes",[Object]),C("design:returntype",Promise)],vt.prototype,"create",null);le([wp(":id"),zt(0,tn("id")),zt(1,$s(new S(ce.partial().omit({id:!0})))),C("design:type",Function),C("design:paramtypes",[String,Object]),C("design:returntype",Promise)],vt.prototype,"update",null);le([mp(":id"),hp(204),zt(0,tn("id")),C("design:type",Function),C("design:paramtypes",[String]),C("design:returntype",Promise)],vt.prototype,"remove",null);vt=le([fp("schedules"),zt(0,bp(jt)),C("design:paramtypes",[jt])],vt)});import{Controller as Sp,Inject as jp,Query as Fs,Sse as _p}from"@nestjs/common";import{Observable as Ms}from"rxjs";var Js,Uo,en,Ae,Vs=p(()=>{"use strict";po();Js=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},Uo=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},en=function(o,t){return function(e,r){t(e,r,o)}},Ae=class{events;constructor(t){this.events=t}stream(t,e){return new Ms(r=>{let i=this.events.subscribe(n=>{let s=n;t!=null&&t!==""&&(!("jobId"in s)||s.jobId!==t)||e!=null&&e!==""&&(!("batchId"in s)||s.batchId!==e)||r.next({data:s})});return()=>{i()}})}};Js([_p(),en(0,Fs("jobId")),en(1,Fs("batchId")),Uo("design:type",Function),Uo("design:paramtypes",[String,String]),Uo("design:returntype",Ms)],Ae.prototype,"stream",null);Ae=Js([Sp("events"),en(0,jp(nt)),Uo("design:paramtypes",[nt])],Ae)});import{extendZodWithOpenApi as Ip}from"@asteasolutions/zod-to-openapi";import{z as xp}from"zod";var Ws=p(()=>{"use strict";Ip(xp)});import{z as Xs}from"zod";var Fo,on=p(()=>{"use strict";Fo=Xs.object({value:Xs.string().min(1)})});import{z as l}from"zod";function Jp(o){let t=l.toJSONSchema(o),{$schema:e,...r}=t;return r}function Hs(o){let t=(e,r)=>o.registerComponent("schemas",e,Jp(r)).ref;return{WorkflowDefinition:t("WorkflowDefinition",Oe),WorkflowDefinitionInput:t("WorkflowDefinitionInput",ae),UpdateWorkflowBody:t("UpdateWorkflowBody",Dp),SubjectView:t("SubjectView",_o),CreateSubjectViewBody:t("CreateSubjectViewBody",Io),ReorderViewsBody:t("ReorderViewsBody",Eo),UpdateViewBody:t("UpdateViewBody",Bp),WorkflowShortcut:t("WorkflowShortcut",vo),CreateWorkflowShortcutBody:t("CreateWorkflowShortcutBody",To),UpdateWorkflowShortcutBody:t("UpdateWorkflowShortcutBody",Ro),ReorderShortcutsBody:t("ReorderShortcutsBody",Oo),Schedule:t("Schedule",ce),UpdateScheduleBody:t("UpdateScheduleBody",$p),EngineSettings:t("EngineSettings",$r),UpdateSettingsBody:t("UpdateSettingsBody",Up),SettingsPatchResponse:t("SettingsPatchResponse",Fp),SetSecretBody:t("SetSecretBody",Fo),CreateJobBody:t("CreateJobBody",qo),ResumeJobBody:t("ResumeJobBody",Co),LatestBySubjectBody:t("LatestBySubjectBody",Do),LatestBySubjectResponse:t("LatestBySubjectResponse",Lp),LaunchBody:t("LaunchBody",Lo),Job:t("Job",rn),JobBatch:t("JobBatch",Ks),LaunchResponse:t("LaunchResponse",kp),HealthResponse:t("HealthResponse",Ap),ProviderStatus:t("ProviderStatus",Np),QueryTemplate:t("QueryTemplate",Ai),ResolveQueryTemplateBody:t("ResolveQueryTemplateBody",jo),ResolveQueryTemplateResponse:t("ResolveQueryTemplateResponse",Ni),ErrorResponse:t("ErrorResponse",qp),EngineEvent:t("EngineEvent",Cp),Subject:t("Subject",Jo)}}var Ep,vp,Tp,Rp,Jo,Op,Pp,rn,Ks,kp,Ap,Np,qp,Cp,Dp,Bp,$p,Lp,Up,Fp,T,nn,sn=p(()=>{"use strict";Ws();Z();Kr();zr();on();Ep=l.enum(["pending","planning","waiting_for_human","waiting_for_children","implementing","testing","completed","failed","cancelled"]),vp=l.object({subjectType:l.literal("ticket"),id:l.string(),source:l.enum(["jira","azure-devops","manual"]),title:l.string(),description:l.string().optional(),status:l.string(),assignee:l.string().optional(),url:l.string().optional(),raw:l.record(l.string(),l.unknown()).optional()}),Tp=l.object({subjectType:l.literal("pull_request"),id:l.string(),source:l.enum(["bitbucket","github","manual"]),title:l.string(),description:l.string().optional(),sourceBranch:l.string(),targetBranch:l.string(),author:l.string().optional(),url:l.string().optional(),raw:l.record(l.string(),l.unknown()).optional()}),Rp=l.object({subjectType:l.literal("documentation"),id:l.string(),source:l.enum(["confluence","notion","github_wiki","gitlab_wiki","azure_wiki","web","manual"]),title:l.string(),url:l.string().optional(),raw:l.record(l.string(),l.unknown()).optional()}),Jo=l.discriminatedUnion("subjectType",[vp,Tp,Rp]),Op=l.discriminatedUnion("mode",[l.object({mode:l.literal("single"),subject:Jo}),l.object({mode:l.literal("collection"),subjects:l.array(Jo)})]),Pp=l.object({id:l.string(),stepDefinitionId:l.string(),type:l.string(),status:l.enum(["pending","running","waiting_for_children","completed","failed","skipped"]),startedAt:l.string().optional(),completedAt:l.string().optional(),output:l.unknown().optional(),error:l.string().optional(),childJobIds:l.array(l.string()).optional(),iterations:l.array(l.object({index:l.number().int(),stepExecutions:l.array(l.record(l.string(),l.unknown())),startedAt:l.string(),completedAt:l.string().optional()})).optional()}),rn=l.object({id:l.string(),workflowId:l.string(),status:Ep,subjectContext:Op.optional(),selection:$o.optional(),batchId:l.string().optional(),parentJobId:l.string().optional(),parentStepExecutionId:l.string().optional(),fanOutIndex:l.number().int().optional(),retryOf:l.string().optional(),context:l.record(l.string(),l.unknown()),worktreePath:l.string().optional(),branch:l.string().optional(),currentStepId:l.string().optional(),currentStepExecutionId:l.string().optional(),stepHistory:l.array(Pp),createdAt:l.string(),updatedAt:l.string(),completedAt:l.string().optional()}),Ks=l.object({id:l.string(),workflowId:l.string(),selection:$o,resolvedSubjects:l.array(Jo),jobIds:l.array(l.string()),status:l.enum(["running","completed","completed_with_issues","failed"]),triggeredBy:l.enum(["schedule","view_bulk","multiselect"]),scheduleId:l.string().optional(),notificationOverride:Re.optional(),notificationSent:l.boolean(),createdAt:l.string(),completedAt:l.string().optional()}),kp=l.discriminatedUnion("kind",[l.object({kind:l.literal("job"),job:rn}),l.object({kind:l.literal("batch"),batch:Ks})]),Ap=l.object({ok:l.boolean(),service:l.string(),timestamp:l.string()}),Np=l.object({providerId:l.string(),secretKey:l.string(),configured:l.boolean()}),qp=l.object({error:l.string()}),Cp=l.object({type:l.string(),timestamp:l.string()}).passthrough(),Dp=ae,Bp=xo,$p=ce.partial().omit({id:!0}),Lp=l.record(l.string(),rn.nullable()),Up=Po,Fp=l.object({settings:$r,restartRequired:l.boolean()}),T=l.object({id:l.string().min(1)}),nn=l.object({limit:l.string().optional().openapi({description:"Max items to return (default 50)"}),offset:l.string().optional().openapi({description:"Number of items to skip (default 0)"})})});import{z as x}from"zod";function w(o,t){return{description:t,content:{"application/json":{schema:o}}}}function et(o){return{type:"array",items:o}}function y(o,...t){let e={400:"Validation error",404:"Resource not found",409:"Conflict"};return Object.fromEntries(t.map(r=>[String(r),w(o.ErrorResponse,e[r]??"Error")]))}function Gs(o,t){o.registerPath({method:"get",path:"/health",tags:["Health"],summary:"Health check",responses:{200:w(t.HealthResponse,"Service is healthy")}}),o.registerPath({method:"get",path:"/workflows",tags:["Workflows"],summary:"List workflow definitions",request:{query:x.object({cardinality:x.enum(["single","batch","aggregate"]).optional()})},responses:{200:w(et(t.WorkflowDefinition),"Workflow definitions"),...y(t,400)}}),o.registerPath({method:"get",path:"/workflows/{id}",tags:["Workflows"],summary:"Get a workflow definition",request:{params:T},responses:{200:w(t.WorkflowDefinition,"Workflow definition"),...y(t,404)}}),o.registerPath({method:"post",path:"/workflows",tags:["Workflows"],summary:"Create a workflow definition",request:{body:{required:!0,content:{"application/json":{schema:t.WorkflowDefinitionInput}}}},responses:{201:w(t.WorkflowDefinition,"Created workflow definition"),...y(t,400)}}),o.registerPath({method:"patch",path:"/workflows/{id}",tags:["Workflows"],summary:"Update a workflow definition",request:{params:T,body:{required:!0,content:{"application/json":{schema:t.UpdateWorkflowBody}}}},responses:{200:w(t.WorkflowDefinition,"Updated workflow definition"),...y(t,400,404)}}),o.registerPath({method:"delete",path:"/workflows/{id}",tags:["Workflows"],summary:"Delete a workflow definition",description:"Rejected with 409 if any non-terminal Job still references the workflow. Terminal Jobs (completed, failed, cancelled) do not block deletion.",request:{params:T},responses:{204:{description:"Workflow deleted"},...y(t,404,409)}}),o.registerPath({method:"get",path:"/views",tags:["Views"],summary:"List subject views",request:{query:x.object({subjectType:ht.optional()})},responses:{200:w(et(t.SubjectView),"Subject views"),...y(t,400)}}),o.registerPath({method:"get",path:"/views/{id}",tags:["Views"],summary:"Get a subject view",request:{params:T},responses:{200:w(t.SubjectView,"Subject view"),...y(t,404)}}),o.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:T},responses:{200:w(et(t.Subject),"Matching subjects"),...y(t,404,400)}}),o.registerPath({method:"patch",path:"/views/reorder",tags:["Views"],summary:"Reorder views within a subject type group",request:{body:{required:!0,content:{"application/json":{schema:t.ReorderViewsBody}}}},responses:{200:w(et(t.SubjectView),"Reordered views for the subject type"),...y(t,400)}}),o.registerPath({method:"post",path:"/views",tags:["Views"],summary:"Create a subject view",request:{body:{required:!0,content:{"application/json":{schema:t.CreateSubjectViewBody}}}},responses:{201:w(t.SubjectView,"Created subject view"),...y(t,400)}}),o.registerPath({method:"patch",path:"/views/{id}",tags:["Views"],summary:"Update a subject view",request:{params:T,body:{required:!0,content:{"application/json":{schema:t.UpdateViewBody}}}},responses:{200:w(t.SubjectView,"Updated subject view"),...y(t,400,404)}}),o.registerPath({method:"delete",path:"/views/{id}",tags:["Views"],summary:"Delete a subject view",request:{params:T},responses:{204:{description:"Subject view deleted"},...y(t,404)}}),o.registerPath({method:"get",path:"/jobs",tags:["Jobs"],summary:"List jobs",request:{query:nn.extend({workflowId:x.string().optional(),status:x.enum(["pending","planning","waiting_for_human","waiting_for_children","implementing","testing","completed","failed","cancelled"]).optional(),batchId:x.string().optional(),parentJobId:x.string().optional(),topLevelOnly:x.enum(["true","false"]).optional().openapi({description:"When true, exclude jobs that belong to a batch or a parent (sub_workflow) job"})})},responses:{200:w(et(t.Job),"Jobs"),...y(t,400)}}),o.registerPath({method:"get",path:"/jobs/{id}",tags:["Jobs"],summary:"Get a job",request:{params:T},responses:{200:w(t.Job,"Job"),...y(t,404)}}),o.registerPath({method:"post",path:"/jobs",tags:["Jobs"],summary:"Start a single job",request:{body:{required:!0,content:{"application/json":{schema:t.CreateJobBody}}}},responses:{201:w(t.Job,"Started job"),...y(t,400,404)}}),o.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:t.LatestBySubjectBody}}}},responses:{200:w(t.LatestBySubjectResponse,"Latest job keyed by subject id"),...y(t,400)}}),o.registerPath({method:"post",path:"/jobs/{id}/resume",tags:["Jobs"],summary:"Resume a job waiting for human input",request:{params:T,body:{required:!0,content:{"application/json":{schema:t.ResumeJobBody}}}},responses:{200:w(t.Job,"Resumed job"),...y(t,400,404,409)}}),o.registerPath({method:"post",path:"/jobs/{id}/retry",tags:["Jobs"],summary:"Retry a failed job",request:{params:T},responses:{200:w(t.Job,"Retry job"),...y(t,404,409)}}),o.registerPath({method:"get",path:"/batches",tags:["Batches"],summary:"List job batches",request:{query:nn.extend({workflowId:x.string().optional()})},responses:{200:w(et(t.JobBatch),"Job batches")}}),o.registerPath({method:"get",path:"/batches/{id}",tags:["Batches"],summary:"Get a job batch",request:{params:T},responses:{200:w(t.JobBatch,"Job batch"),...y(t,404)}}),o.registerPath({method:"get",path:"/batches/{id}/jobs",tags:["Batches"],summary:"List jobs in a batch",request:{params:T},responses:{200:w(et(t.Job),"Jobs in the batch"),...y(t,404)}}),o.registerPath({method:"post",path:"/batches",tags:["Batches"],summary:"Launch a batch or aggregate run",description:"Resolves subject selection and starts either a JobBatch (batch cardinality) or a single Job (aggregate cardinality).",request:{body:{required:!0,content:{"application/json":{schema:t.LaunchBody}}}},responses:{201:w(t.LaunchResponse,"Launch result"),...y(t,400,404)}}),o.registerPath({method:"get",path:"/workflow-shortcuts",tags:["Workflow shortcuts"],summary:"List workflow shortcuts",responses:{200:w(et(t.WorkflowShortcut),"Workflow shortcuts")}}),o.registerPath({method:"get",path:"/workflow-shortcuts/{id}",tags:["Workflow shortcuts"],summary:"Get a workflow shortcut",request:{params:T},responses:{200:w(t.WorkflowShortcut,"Workflow shortcut"),...y(t,404)}}),o.registerPath({method:"post",path:"/workflow-shortcuts",tags:["Workflow shortcuts"],summary:"Create a workflow shortcut",request:{body:{required:!0,content:{"application/json":{schema:t.CreateWorkflowShortcutBody}}}},responses:{201:w(t.WorkflowShortcut,"Created workflow shortcut"),...y(t,400,404)}}),o.registerPath({method:"patch",path:"/workflow-shortcuts/reorder",tags:["Workflow shortcuts"],summary:"Reorder workflow shortcuts",request:{body:{required:!0,content:{"application/json":{schema:t.ReorderShortcutsBody}}}},responses:{200:w(et(t.WorkflowShortcut),"Reordered workflow shortcuts"),...y(t,400)}}),o.registerPath({method:"patch",path:"/workflow-shortcuts/{id}",tags:["Workflow shortcuts"],summary:"Update a workflow shortcut",request:{params:T,body:{required:!0,content:{"application/json":{schema:t.UpdateWorkflowShortcutBody}}}},responses:{200:w(t.WorkflowShortcut,"Updated workflow shortcut"),...y(t,400,404)}}),o.registerPath({method:"delete",path:"/workflow-shortcuts/{id}",tags:["Workflow shortcuts"],summary:"Delete a workflow shortcut",request:{params:T},responses:{204:{description:"Workflow shortcut deleted"},...y(t,404)}}),o.registerPath({method:"get",path:"/schedules",tags:["Schedules"],summary:"List schedules",request:{query:x.object({enabled:x.enum(["true","false"]).optional()})},responses:{200:w(et(t.Schedule),"Schedules"),...y(t,400)}}),o.registerPath({method:"get",path:"/schedules/{id}",tags:["Schedules"],summary:"Get a schedule",request:{params:T},responses:{200:w(t.Schedule,"Schedule"),...y(t,404)}}),o.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:t.Schedule}}}},responses:{201:w(t.Schedule,"Created schedule"),...y(t,400)}}),o.registerPath({method:"patch",path:"/schedules/{id}",tags:["Schedules"],summary:"Update a schedule",request:{params:T,body:{required:!0,content:{"application/json":{schema:t.UpdateScheduleBody}}}},responses:{200:w(t.Schedule,"Updated schedule"),...y(t,400,404)}}),o.registerPath({method:"delete",path:"/schedules/{id}",tags:["Schedules"],summary:"Delete a schedule",request:{params:T},responses:{204:{description:"Schedule deleted"},...y(t,404)}}),o.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:w(et(t.ProviderStatus),"Provider configuration status")}}),o.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:x.object({providerId:x.string().min(1)})},responses:{200:w(et(t.QueryTemplate),"Query templates")}}),o.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:x.object({providerId:x.string().min(1),templateId:x.string().min(1)}),body:{required:!0,content:{"application/json":{schema:t.ResolveQueryTemplateBody}}}},responses:{200:w(t.ResolveQueryTemplateResponse,"Resolved query"),...y(t,400,404)}}),o.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:w(t.EngineSettings,"Current engine settings")}}),o.registerPath({method:"patch",path:"/settings",tags:["Settings"],summary:"Update engine settings",description:"Partial merge. restartRequired is true only when activeProviders was in the patch (implementation binding is a boot-time decision). Jira/Bitbucket config fields take effect on the next provider call with no restart.",request:{body:{required:!0,content:{"application/json":{schema:t.UpdateSettingsBody}}}},responses:{200:w(t.SettingsPatchResponse,"Updated settings"),...y(t,400)}}),o.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:x.object({key:x.string().min(1)}),body:{required:!0,content:{"application/json":{schema:t.SetSecretBody}}}},responses:{204:{description:"Secret stored"},...y(t,400)}}),o.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:x.object({jobId:x.string().optional(),batchId:x.string().optional()})},responses:{200:{description:"SSE stream of engine events",content:{"text/event-stream":{schema:t.EngineEvent}}}}})}var zs=p(()=>{"use strict";Z();sn()});import{OpenAPIRegistry as Mp,OpenApiGeneratorV31 as Vp}from"@asteasolutions/zod-to-openapi";function Qs(){if(Mo)return Mo;let o=new Mp,t=Hs(o);return Gs(o,t),Mo=new Vp(o.definitions).generateDocument({openapi:"3.1.0",info:{title:"Kno Engine API",version:"0.1.0",description:"REST API for workflow definitions, jobs, batches, schedules, views, and live events."},servers:[{url:"/api"}]}),Mo}var Mo,Ys=p(()=>{"use strict";sn();zs()});import{Controller as Wp,Get as Xp,Header as Kp}from"@nestjs/common";var Zs,an,Ne,ta=p(()=>{"use strict";Ys();Zs=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},an=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},Ne=class{getOpenApiDocument(){return Qs()}};Zs([Xp("openapi.json"),Kp("Content-Type","application/json"),an("design:type",Function),an("design:paramtypes",[]),an("design:returntype",void 0)],Ne.prototype,"getOpenApiDocument",null);Ne=Zs([Wp()],Ne)});import{Controller as Hp,Get as oa,Inject as ea,Param as cn,Post as Gp,Body as zp,HttpCode as Qp}from"@nestjs/common";var Vo,gt,pe,Qt,ra=p(()=>{"use strict";xr();Er();Z();bt();Vo=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},gt=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},pe=function(o,t){return function(e,r){t(e,r,o)}},Qt=class{providerStatus;queryTemplates;constructor(t,e){this.providerStatus=t,this.queryTemplates=e}async status(){return this.providerStatus.list()}listQueryTemplates(t){return this.queryTemplates.list(t)}resolveQueryTemplate(t,e,r){return{query:this.queryTemplates.resolve(t,e,r.params)}}};Vo([oa("status"),gt("design:type",Function),gt("design:paramtypes",[]),gt("design:returntype",Promise)],Qt.prototype,"status",null);Vo([oa(":providerId/query-templates"),pe(0,cn("providerId")),gt("design:type",Function),gt("design:paramtypes",[String]),gt("design:returntype",Array)],Qt.prototype,"listQueryTemplates",null);Vo([Gp(":providerId/query-templates/:templateId/resolve"),Qp(200),pe(0,cn("providerId")),pe(1,cn("templateId")),pe(2,zp(new S(jo))),gt("design:type",Function),gt("design:paramtypes",[String,String,Object]),gt("design:returntype",Object)],Qt.prototype,"resolveQueryTemplate",null);Qt=Vo([Hp("providers"),pe(0,ea(kt)),pe(1,ea(At)),gt("design:paramtypes",[kt,At])],Qt)});import{Body as Yp,Controller as Zp,Get as td,Inject as ed,Patch as od}from"@nestjs/common";var un,Yt,na,de,ia=p(()=>{"use strict";Z();oo();bt();un=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},Yt=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},na=function(o,t){return function(e,r){t(e,r,o)}},de=class{settings;constructor(t){this.settings=t}get(){return this.settings.get()}async update(t){return{settings:await this.settings.update(t),restartRequired:Qn(t)}}};un([td(),Yt("design:type",Function),Yt("design:paramtypes",[]),Yt("design:returntype",Promise)],de.prototype,"get",null);un([od(),na(0,Yp(new S(Po))),Yt("design:type",Function),Yt("design:paramtypes",[Object]),Yt("design:returntype",Promise)],de.prototype,"update",null);de=un([Zp("settings"),na(0,ed(U)),Yt("design:paramtypes",[U])],de)});import{Body as rd,Controller as nd,HttpCode as id,Inject as sd,Param as ad,Post as cd}from"@nestjs/common";var sa,Wo,ln,qe,aa=p(()=>{"use strict";Tt();D();bt();on();sa=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},Wo=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},ln=function(o,t){return function(e,r){t(e,r,o)}},qe=class{secrets;constructor(t){this.secrets=t}async set(t,e){let r=t.trim();if(!r)throw new b("Secret key must not be empty");await this.secrets.set(r,e.value)}};sa([cd(":key"),id(204),ln(0,ad("key")),ln(1,rd(new S(Fo))),Wo("design:type",Function),Wo("design:paramtypes",[String,Object]),Wo("design:returntype",Promise)],qe.prototype,"set",null);qe=sa([nd("secrets"),ln(0,sd(ot)),Wo("design:paramtypes",[Function])],qe)});import{Module as ld}from"@nestjs/common";import{APP_FILTER as pd}from"@nestjs/core";var ud,Xo,ca=p(()=>{"use strict";xe();Nr();fo();ki();xs();Rs();As();Cs();Bs();Us();Vs();ta();ra();ia();aa();uo();ar();ud=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},Xo=class{};Xo=ud([ld({imports:[ft,se,qt,Nt,Zt],controllers:[xt,st,wt,yt,Lt,vt,Ae,Ne,Qt,de,qe],providers:[{provide:pd,useClass:So}]})],Xo)});import{Module as fd}from"@nestjs/common";var dd,Ko,ua=p(()=>{"use strict";mn();hn();bn();uo();fi();fo();xe();Nr();ca();dd=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},Ko=class{};Ko=dd([fd({imports:[Ce,De,Nt,lo,qt,ft,se,Xo],controllers:[fe]})],Ko)});import{apiReference as md}from"@scalar/nestjs-api-reference";function la(o){o.use("/api/docs",md({url:"/api/openapi.json",pageTitle:"Kno Engine API"}))}var pa=p(()=>{"use strict"});import{createServer as hd}from"node:net";function da(o){return typeof o=="object"&&o!==null&&"code"in o&&o.code==="EADDRINUSE"}async function pn(o,t=20){for(let e=0;e<t;e+=1){let r=o+e;if(await bd(r))return r}throw new Error(`No free port found in ${o}\u2013${o+t-1}`)}function bd(o){return new Promise(t=>{let e=hd();e.once("error",()=>{t(!1)}),e.once("listening",()=>{e.close(()=>t(!0))}),e.listen(o)})}var fa=p(()=>{"use strict"});import{Catch as gd,HttpStatus as Ho,NotFoundException as Sd}from"@nestjs/common";import{existsSync as ma,statSync as jd}from"node:fs";import{extname as ha,join as dn,normalize as _d,relative as Id,sep as xd}from"node:path";function ba(o){return(t,e,r)=>{if(t.method!=="GET"&&t.method!=="HEAD"){r();return}if((t.path??"").startsWith("/api")){r();return}let i=Ed(t.path??"/");if(i){let n=dn(o,i);if(vd(o,n)){e.sendFile(i,{root:o},s=>{s&&r()});return}}if(wa(t)){ya(e,o,n=>{n&&!e.headersSent&&e.status(Ho.NOT_FOUND).end()});return}e.status(Ho.NOT_FOUND).end()}}function wa(o){if(o.method!=="GET"&&o.method!=="HEAD")return!1;let t=o.path??"";if(t.startsWith("/api"))return!1;let e=ha(t);return!(e&&e!==".html")}function ya(o,t,e){o.sendFile("index.html",{root:t},e)}function Ed(o){if(o==="/"||o==="")return"index.html";let t=_d(o.replace(/^\/+/,""));return!t||t==="."||t.startsWith("..")||!ha(t)?null:t}function vd(o,t){if(!ma(t))return!1;try{if(!jd(t).isFile())return!1}catch{return!1}let e=Id(o,t);return e!==""&&!e.startsWith(`..${xd}`)&&!e.startsWith("..")}function ga(o){return dn(o,"index.html")}var wd,yd,Go,Sa=p(()=>{"use strict";wd=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},yd=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},Go=class{staticRoot;constructor(t){this.staticRoot=t}catch(t,e){let r=e.switchToHttp(),i=r.getRequest(),n=r.getResponse();if(wa(i)&&ma(dn(this.staticRoot,"index.html"))){ya(n,this.staticRoot,u=>{u&&!n.headersSent&&n.status(Ho.NOT_FOUND).json({statusCode:Ho.NOT_FOUND,message:"UI index.html could not be served"})});return}let s=t.getStatus(),a=t.getResponse();n.status(s).json(typeof a=="string"?{statusCode:s,message:a}:a)}};Go=wd([gd(Sd),yd("design:paramtypes",[String])],Go)});import{existsSync as Td}from"node:fs";import{dirname as Rd,join as zo}from"node:path";import{fileURLToPath as Od}from"node:url";function ja(){let o=Rd(Od(import.meta.url)),t=[zo(o,"../static"),zo(o,"../../static"),zo(o,"static")];for(let e of t)if(Td(zo(e,"index.html")))return e;return null}var _a=p(()=>{"use strict"});var qd={};import"reflect-metadata";import{existsSync as Pd}from"node:fs";import{Logger as kd}from"@nestjs/common";import{NestFactory as Ad}from"@nestjs/core";async function Nd(){let o=await Ad.create(Ko);o.enableCors(),o.setGlobalPrefix("api"),la(o);let t=ja(),e=t?ga(t):null;t&&e&&Pd(e)?(Qo.log(`Serving UI from ${t}`),o.use(ba(t)),o.useGlobalFilters(new Go(t))):Qo.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 i=await pn(r);for(let n=0;n<5;n+=1)try{await o.listen(i),i!==r?Qo.warn(`Port ${r} is in use; listening on ${i} instead`):Qo.log(`Listening on http://localhost:${i}`);return}catch(s){if(!da(s))throw s;i=await pn(i+1)}throw new Error(`Could not bind a free port starting at ${r}`)}var Qo,Ia=p(()=>{"use strict";ua();pa();fa();Sa();_a();Qo=new kd("Bootstrap");Nd()});import{readFileSync as Cd}from"node:fs";function Dd(){let o=Cd(new URL("../package.json",import.meta.url),"utf8");return JSON.parse(o).version}var Yo=process.argv.slice(2);Yo.includes("--version")||Yo.includes("-v")?console.log(Dd()):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(`
144
+ `)):await Promise.resolve().then(()=>(Ia(),qd));