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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -11,7 +11,7 @@ npm install @knoflows/engine@alpha
11
11
  ## Run
12
12
 
13
13
  ```bash
14
- kno
14
+ knoflows
15
15
  ```
16
16
 
17
17
  The Engine listens on port 3000. API docs: `http://localhost:3000/api/docs`.
package/dist/engine.js CHANGED
@@ -1,17 +1,17 @@
1
1
  #!/usr/bin/env node
2
- var l=(o,t)=>()=>(o&&(t=o(o=0)),t);import{Controller as bs,Get as gs}from"@nestjs/common";var Rn,To,te,Pn=l(()=>{"use strict";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},To=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()}}};Rn([gs(),To("design:type",Function),To("design:paramtypes",[]),To("design:returntype",Object)],te.prototype,"getHealth",null);te=Rn([bs("health")],te)});import{Module as ws}from"@nestjs/common";var ys,_e,An=l(()=>{"use strict";ys=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=ys([ws({})],_e)});import{Module as _s}from"@nestjs/common";var Ss,je,kn=l(()=>{"use strict";Ss=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=Ss([_s({})],je)});var Pt,Ie=l(()=>{"use strict";Pt=Symbol("TICKET_PROVIDER")});import{randomUUID as js}from"node:crypto";function Is(o,t){return Object.entries(t).every(([e,n])=>o[e]===n)}var xe,Nn=l(()=>{"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=>Is(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:js(),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=l(()=>{"use strict";At=Symbol("REPO_PROVIDER")});import{randomUUID as xs}from"node:crypto";function Es(o,t){return Object.entries(t).every(([e,n])=>e==="status"?o.raw?.status===n:o[e]===n)}var ve,Cn=l(()=>{"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=>Es(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:xs(),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=l(()=>{"use strict";kt=Symbol("DOCUMENTATION_PROVIDER")});import{randomUUID as vs}from"node:crypto";var Ts,Oe,Dn=l(()=>{"use strict";Ts=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:vs(),subjectId:t,body:e,createdAt:new Date().toISOString()}),this.comments.set(t,i)}assertCommentsSupported(t){if(Ts.has(t.source))throw new Error(`Comments are not supported for documentation source '${t.source}'`)}}});var ee,Oo=l(()=>{"use strict";ee=Symbol("AGENT_PROVIDER")});import{createCipheriv as Os,createDecipheriv as Rs,randomBytes as $n}from"node:crypto";import{mkdir as qn,readFile as Ln,writeFile as Bn}from"node:fs/promises";import{join as Po}from"node:path";function ct(o){return`kno.${o}.apiKey`}function Ns(o){return Po(o,"secrets")}function Fn(o){return new Ao(Ns(o.dataDir),o.keyring)}function Cs(o){try{return o(Re,"__kno_probe__").getPassword(),!0}catch(t){return ko(t)}}function ko(o){let t=o instanceof Error?o.message:String(o);return/noentry|no matching entry|not found|no such/i.test(t)}var Re,Jn,Ps,Ro,As,ks,Ao,H,yt=l(()=>{"use strict";Re="kno-flows";Jn="aes-256-gcm",Ps=12,Ro=32,As="master.key",ks="store.json",Ao=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){ko(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){ko(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 Cs(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 Ln(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 qn(this.secretsDir,{recursive:!0}),await Bn(this.storePath(),JSON.stringify(t,null,2),{encoding:"utf8",mode:384})}async encrypt(t){let e=await this.loadOrCreateMasterKey(),n=$n(Ps),i=Os(Jn,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=Rs(Jn,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 qn(this.secretsDir,{recursive:!0});let t=this.masterKeyPath();try{let n=(await Ln(t,"utf8")).trim(),i=Buffer.from(n,"hex");if(i.length!==Ro)throw new Error(`Secret store master key at ${t} is not ${Ro} bytes`);return this.masterKey=i,i}catch(n){if(n.code!=="ENOENT")throw n}let e=$n(Ro);return await Bn(t,e.toString("hex"),{encoding:"utf8",mode:384}),this.masterKey=e,e}storePath(){return Po(this.secretsDir,ks)}masterKeyPath(){return Po(this.secretsDir,As)}};H=Symbol("SECRET_STORE")});function Pe(o){let t=ct(o),e=Ls[o]??o;return new Error(`${e} API key not configured \u2014 set '${t}' via the setup script`)}function Un(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 $s){let i=t.get(n);i?.length&&e.push(`## ${Ds[n]}
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]}
3
3
  ${i.join(`
4
4
 
5
5
  `)}`)}return e.join(`
6
6
 
7
- `)}function oe(o){let t=[],e=Un(o.knowledge);return e&&t.push(e),t.push(`# Objective
7
+ `)}function oe(o){let t=[],e=Kn(o.knowledge);return e&&t.push(e),t.push(`# Objective
8
8
  ${o.objective}`),t.push(`# Output format
9
- ${qs[o.outputFormat]}`),t.join(`
9
+ ${Js[o.outputFormat]}`),t.join(`
10
10
 
11
- `)}function ne(o,t){return t==="free_text"?o:Mn(o)}function Mn(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 Ds,$s,qs,Ls,Ae=l(()=>{"use strict";yt();Ds={user:"User preferences",organization:"Organization guidelines",project:"Project context"},$s=["user","organization","project"],qs={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."},Ls={anthropic:"Anthropic",cursor:"Cursor"}});async function*Js(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 Bs,ke,Vn=l(()=>{"use strict";Ae();yt();Ae();Bs=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??Js,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(Bs);if(!t)throw Pe("anthropic");return t}}});function Us(o,t){return{apiKey:o,model:{id:"composer-2.5"},local:{...t?{cwd:t}:{},settingSources:[]}}}async function Ms(){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 Fs,Ne,Kn=l(()=>{"use strict";Ae();yt();Fs=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 Ms(),r=Us(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(Fs);if(!t)throw Pe("cursor");return t}}});var re,No=l(()=>{"use strict";re=Symbol("NOTIFICATION_PROVIDER")});var Ce,Xn=l(()=>{"use strict";Ce=class{async send(t){console.log("[notification]",JSON.stringify(t))}}});var ie,Co=l(()=>{"use strict";ie=Symbol("KNOWLEDGE_PROVIDER")});import{readdir as Vs,readFile as Ks}from"node:fs/promises";import{join as Hn}from"node:path";var De,Wn=l(()=>{"use strict";De=class{baseDir;constructor(t){this.baseDir=t}async resolve(t,e){let n=Hn(this.baseDir,t),i;try{i=await Vs(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=Hn(n,a),c=await Ks(u,"utf8");s.push({tier:t,content:c,sourceRef:u})}return s}}});import{Module as Hs}from"@nestjs/common";import{mkdirSync as Ws}from"node:fs";import{dirname as Gs,join as zs}from"node:path";import{fileURLToPath as Ys}from"node:url";var Xs,Gn,Bt,Do=l(()=>{"use strict";yt();Xs=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},Gn=zs(Gs(Ys(import.meta.url)),"../../data");Ws(Gn,{recursive:!0});Bt=class{};Bt=Xs([Hs({providers:[{provide:H,useFactory:()=>Fn({dataDir:Gn})}],exports:[H]})],Bt)});import{index as Qs,sqliteTable as Zs,text as tt}from"drizzle-orm/sqlite-core";var et,$e=l(()=>{"use strict";et=Zs("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=>[Qs("workflow_definitions_cardinality_idx").on(o.cardinality)])});import{index as zn,integer as ta,sqliteTable as ea,text as se}from"drizzle-orm/sqlite-core";var ot,$o=l(()=>{"use strict";ot=ea("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:ta("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 Yn,integer as oa,sqliteTable as na,text as nt}from"drizzle-orm/sqlite-core";var wt,qe=l(()=>{"use strict";wt=na("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:oa("notification_sent",{mode:"boolean"}).notNull(),createdAt:nt("created_at").notNull(),completedAt:nt("completed_at")},o=>[Yn("job_batches_workflow_id_idx").on(o.workflowId),Yn("job_batches_schedule_id_idx").on(o.scheduleId)])});import{index as Le,integer as ra,sqliteTable as ia,text as v}from"drizzle-orm/sqlite-core";var rt,ae=l(()=>{"use strict";$e();qe();rt=ia("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:ra("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 Qn,sqliteTable as sa,text as ce}from"drizzle-orm/sqlite-core";var Jt,qo=l(()=>{"use strict";ae();Jt=sa("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=>[Qn("job_subjects_job_id_idx").on(o.jobId),Qn("job_subjects_subject_lookup_idx").on(o.subjectType,o.subjectId)])});import{index as Zn,integer as aa,sqliteTable as ca,text as W}from"drizzle-orm/sqlite-core";var Nt,Lo=l(()=>{"use strict";ae();Nt=ca("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:aa("iteration_index")},o=>[Zn("job_step_executions_job_id_idx").on(o.jobId),Zn("job_step_executions_parent_idx").on(o.parentStepExecutionId)])});import{index as ua,integer as da,sqliteTable as pa,text as ut}from"drizzle-orm/sqlite-core";var St,Bo=l(()=>{"use strict";St=pa("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:da("enabled",{mode:"boolean"}).notNull(),lastFiredAt:ut("last_fired_at"),createdAt:ut("created_at").notNull()},o=>[ua("schedules_enabled_idx").on(o.enabled)])});import{sqliteTable as la,text as tr}from"drizzle-orm/sqlite-core";var ue,Ft,Jo=l(()=>{"use strict";ue="default",Ft=la("settings",{id:tr("id").primaryKey(),data:tr("data",{mode:"json"}).$type().notNull()})});import{defineRelations as fa}from"drizzle-orm";var ma,er,or=l(()=>{"use strict";$e();$o();ae();qo();Lo();qe();Bo();Jo();ma={workflowDefinitions:et,subjectViews:ot,jobs:rt,jobSubjects:Jt,jobStepExecutions:Nt,jobBatches:wt,schedules:St,settings:Ft},er=fa(ma,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 ha}from"drizzle-orm/node-sqlite";import{DatabaseSync as _l}from"node:sqlite";function nr(o){return o.exec("PRAGMA foreign_keys = ON;"),ha({client:o,relations:er})}var rr=l(()=>{"use strict";or()});function ba(o,t,e){return o.prepare(`PRAGMA table_info(${t})`).all().some(i=>i.name===e)}function ga(o){ba(o,"subject_views","order")||o.exec('ALTER TABLE subject_views ADD COLUMN "order" INTEGER NOT NULL DEFAULT 0'),o.exec(`
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(`
12
12
  CREATE INDEX IF NOT EXISTS subject_views_subject_type_order_idx
13
13
  ON subject_views (subject_type, "order");
14
- `)}function Fo(o){o.exec(`
14
+ `)}function Mo(o){o.exec(`
15
15
  PRAGMA foreign_keys = ON;
16
16
 
17
17
  CREATE TABLE IF NOT EXISTS workflow_definitions (
@@ -127,8 +127,8 @@ ${qs[o.outputFormat]}`),t.join(`
127
127
  id TEXT PRIMARY KEY NOT NULL,
128
128
  data TEXT NOT NULL
129
129
  );
130
- `),ga(o)}var ir=l(()=>{"use strict"});import{Injectable as Sa}from"@nestjs/common";import{mkdirSync as _a}from"node:fs";import{dirname as ja}from"node:path";import{fileURLToPath as Ia}from"node:url";import{DatabaseSync as sr}from"node:sqlite";var ya,wa,G,ar=l(()=>{"use strict";rr();ir();ya=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)},G=class{sqlite;db;constructor(){let e=process.env.KNO_SQLITE_PATH??Ia(new URL("../../data/kno.db",import.meta.url));e===":memory:"?this.sqlite=new sr(":memory:"):(_a(ja(e),{recursive:!0}),this.sqlite=new sr(e)),this.db=nr(this.sqlite),Fo(this.sqlite)}async onModuleInit(){Fo(this.sqlite)}getDb(){return this.db}getSqlite(){return this.sqlite}};G=ya([Sa(),wa("design:paramtypes",[])],G)});import{Injectable as va}from"@nestjs/common";import{eq as cr}from"drizzle-orm";var xa,Ea,L,Be=l(()=>{"use strict";$e();xa=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},Ea=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(cr(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(cr(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=xa([va(),Ea("design:paramtypes",[Object,Function])],L)});import{Injectable as Ra}from"@nestjs/common";import{eq as Uo}from"drizzle-orm";var Ta,Oa,ur,B,Je=l(()=>{"use strict";$o();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)},ur=["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(Uo(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(Uo(ot.id,t[i]));return this.list({subjectType:n})}async delete(t){return await this.get(t)?(await this.db.delete(ot).where(Uo(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=ur.indexOf(e.subjectType)-ur.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=Ta([Ra(),Oa("design:paramtypes",[Object])],B)});import{Injectable as ka}from"@nestjs/common";import{eq as Mo}from"drizzle-orm";import{randomUUID as Na}from"node:crypto";function Ca(o){return o?o.mode==="single"?[o.subject]:o.subjects:[]}function Da(o){if(o.length!==0)return o.length===1?{mode:"single",subject:o[0]}:{mode:"collection",subjects:o}}function pr(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(...pr(o,s.stepExecutions,r.id,s.index));return i}function $a(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=>dr(f,e(f.id)));return{index:a,stepExecutions:c,startedAt:qa(c),...Ba(c)?{completedAt:La(c)}:{}}})};return(t.get(null)??[]).filter(i=>i.iterationIndex==null).map(i=>dr(i,e(i.id)))}function dr(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 qa(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 La(o){return o.map(e=>e.completedAt).filter(e=>e!=null).reduce((e,n)=>e>n?e:n)}function Ba(o){return o.length>0&&o.every(t=>t.completedAt!=null)}var Pa,Aa,x,Ut=l(()=>{"use strict";ae();qo();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)},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(Mo(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(Mo(Jt.jobId,t));let n=Ca(e);n.length!==0&&await this.db.insert(Jt).values(n.map(i=>({id:Na(),jobId:t,subjectType:i.subjectType,subjectId:i.id,snapshot:i})))}async replaceStepExecutions(t,e){await this.db.delete(Nt).where(Mo(Nt.jobId,t));let n=pr(t,e);n.length!==0&&await this.db.insert(Nt).values(n)}toDomain(t,e,n){let i=Da(e.map(s=>s.snapshot)),r=$a(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=Pa([ka(),Aa("design:paramtypes",[Object])],x)});import{Injectable as Ua}from"@nestjs/common";import{eq as Ma}from"drizzle-orm";var Ja,Fa,J,Fe=l(()=>{"use strict";qe();Ja=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},Fa=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(Ma(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=Ja([Ua(),Fa("design:paramtypes",[Object])],J)});import{Injectable as Xa}from"@nestjs/common";import{eq as lr}from"drizzle-orm";var Va,Ka,dt,Vo=l(()=>{"use strict";Bo();Va=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},Ka=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(lr(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(lr(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=Va([Xa(),Ka("design:paramtypes",[Object])],dt)});import{Injectable as Ga}from"@nestjs/common";import{eq as za}from"drizzle-orm";function Ya(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 Ko({activeProviders:e,...n&&Object.keys(n).length>0?{jira:n}:{},...i&&Object.keys(i).length>0?{bitbucket:i}:{}})}function Ko(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 fr(o){return Object.prototype.hasOwnProperty.call(o,"activeProviders")}var Ha,Wa,D,Ue=l(()=>{"use strict";Jo();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)},D=class{db;constructor(t){this.db=t}async get(){let t=await this.db.query.settings.findFirst({where:{id:ue}});return Ko(t?t.data:{})}async update(t){let e=Ya(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=Ha([Ga(),Wa("design:paramtypes",[Object])],D)});import{Module as Za}from"@nestjs/common";var Qa,tc,it,de=l(()=>{"use strict";ar();Be();Je();Ut();Fe();Vo();Ue();Qa=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=[L,B,x,J,dt,D],it=class{};it=Qa([Za({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,...tc]})],it)});function Xo(o){return o==null?"":typeof o=="string"?o:hr(o).replace(/\n+$/,"")}function mr(o){return{version:1,type:"doc",content:o.split(`
131
- `).map(e=>({type:"paragraph",content:e.length===0?[]:[{type:"text",text:e}]}))}}function hr(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(hr).join("");return t.type==="paragraph"||t.type==="heading"||t.type==="blockquote"||t.type==="listItem"?`${e}
133
- `:e}var br=l(()=>{"use strict"});function nc(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 gr(o,t){let e=String(o.key??o.id??""),n=o.fields??{},i=Xo(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,ec,oc,Me,Xe,Ho=l(()=>{"use strict";br();Mt="kno.jira.apiToken",ec=50,oc=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 gr(n,e)}async query(t){let{baseUrl:e}=await this.requireConfig(),n=nc(t),i=[],r,s=new Set;for(let a=0;a<oc&&i.length<Me;a++){let u={jql:n,maxResults:Math.min(ec,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(gr(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:Xo(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:mr(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 ic(o,t){return`${o}#${t}`}function sc(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 ac(o){if(typeof o.q=="string"&&o.q.trim().length>0)return o.q;if(uc(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 cc(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 uc(o){return o!=null&&o!==""}function yr(o,t){let e=String(o.id??""),n=typeof o.description=="string"?o.description:"";return{id:ic(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 dc(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,rc,We,Wo=l(()=>{"use strict";Vt="kno.bitbucket.apiToken",rc="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 yr(r,e)}async query(t){let e=sc(t),{baseUrl:n,workspace:i}=await this.requireConfig(),r=ac(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(yr(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(dc(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=cc(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()||rc).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 mc,Logger as hc,Inject as bc}from"@nestjs/common";async function wr(o){let t=[];for(let e of gc){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 yc(o,t){let e=await wr(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 Sr(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 _r(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 jr(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 pc,lc,fc,Go,gc,_t,zo=l(()=>{"use strict";yt();Ho();Wo();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},lc=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},fc=function(o,t){return function(e,n){t(e,n,o)}},gc=[{providerId:"anthropic",secretKey:ct("anthropic")},{providerId:"cursor",secretKey:ct("cursor")},{providerId:"jira",secretKey:Mt},{providerId:"bitbucket",secretKey:Vt}];_t=Go=class{secrets;logger=new hc(Go.name);constructor(t){this.secrets=t}async onModuleInit(){await yc(this.secrets,t=>this.logger.warn(t))}list(){return wr(this.secrets)}};_t=Go=pc([mc(),fc(0,bc(H)),lc("design:paramtypes",[Function])],_t)});import{Module as Sc}from"@nestjs/common";import{fileURLToPath as _c}from"node:url";import{dirname as jc,join as Ic}from"node:path";var wc,xc,jt,Ge=l(()=>{"use strict";Ie();Nn();Ee();Cn();Te();Dn();Oo();Vn();Kn();No();Xn();Co();Wn();Do();yt();de();Ue();zo();Ho();Wo();wc=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},xc=Ic(jc(_c(import.meta.url)),"../../../knowledge"),jt=class{};jt=wc([Sc({imports:[Bt,it],providers:[{provide:Pt,useFactory:async(o,t)=>_r(await t.get())==="jira"?new Xe(o,t):new xe([]),inject:[H,D]},{provide:At,useFactory:async(o,t)=>jr(await t.get())==="bitbucket"?new We(o,t):new ve([]),inject:[H,D]},{provide:kt,useFactory:()=>new Oe([])},{provide:ee,useFactory:async(o,t)=>Sr(await t.get())==="cursor"?new Ne(o):new ke(o),inject:[H,D]},{provide:re,useClass:Ce},{provide:ie,useFactory:()=>new De(xc)},_t],exports:[Pt,At,kt,ee,re,ie,_t]})],jt)});import{Module as vc}from"@nestjs/common";var Ec,ze,Ir=l(()=>{"use strict";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},ze=class{};ze=Ec([vc({})],ze)});import{Injectable as Oc}from"@nestjs/common";var Tc,z,Ye=l(()=>{"use strict";Tc=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=Tc([Oc()],z)});import{Global as Pc,Module as Ac}from"@nestjs/common";var Rc,It,Qe=l(()=>{"use strict";Ye();Rc=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=Rc([Pc(),Ac({providers:[z],exports:[z]})],It)});import{Injectable as Cc}from"@nestjs/common";import{execFile as Dc}from"node:child_process";import{mkdirSync as xr}from"node:fs";import{join as Yo}from"node:path";import{promisify as $c}from"node:util";function Er(o){return o==null?"":typeof o=="string"?o:o.toString("utf8")}function vr(o){return Yo(o,"worktrees")}var kc,Nc,qc,pt,Qo=l(()=>{"use strict";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},Nc=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},qc=$c(Dc),pt=class{worktreesRoot;constructor(t){this.worktreesRoot=t,xr(this.worktreesRoot,{recursive:!0})}async createWorktree(t,e){let n=e.worktreePath??Yo(this.worktreesRoot,t);return xr(Yo(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 qc("git",e,{cwd:t,encoding:"utf8",windowsHide:!0});return{stdout:n.stdout??"",stderr:n.stderr??""}}catch(n){let i=n,r=Er(i.stderr),s=Er(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=kc([Cc(),Nc("design:paramtypes",[String])],pt)});import{Module as Bc}from"@nestjs/common";import{mkdirSync as Jc}from"node:fs";import{dirname as Fc,join as Uc}from"node:path";import{fileURLToPath as Mc}from"node:url";var Lc,Tr,Ze,Or=l(()=>{"use strict";Qo();Lc=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},Tr=Uc(Fc(Mc(import.meta.url)),"../../data");Jc(Tr,{recursive:!0});Ze=class{};Ze=Lc([Bc({providers:[{provide:pt,useFactory:()=>new pt(vr(Tr))}],exports:[pt]})],Ze)});var Ct,g,b,Dt,Y=l(()=>{"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=Vc(t,n.trim());return i==null?"":typeof i=="string"?i:JSON.stringify(i)})}function Vc(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 Rr=l(()=>{"use strict"});function Pr(o,t){switch(o){case"questionnaire":return Zo(t);case"confirmation":return Kc(t);case"conversation":return Xc(t);default:return o}}function Zo(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 Kc(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)?[]:Zo(o)}function Xc(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?Zo(o):[]}var Ar=l(()=>{"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 tn(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:tn(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 kr(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 Nr=l(()=>{"use strict"});import{z as F}from"zod";function Cr(o,t){let e=Yc[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 Hc,Wc,Gc,zc,Yc,Dr=l(()=>{"use strict";Hc=F.object({questions:F.array(F.object({id:F.string(),prompt:F.string()}))}),Wc=F.object({approved:F.boolean()}),Gc=F.object({suggestions:F.array(F.object({body:F.string()}))}),zc=F.string(),Yc={questionnaire:Hc,confirmation:Wc,comment_suggestions:Gc,free_text:zc}});function $r(o){return o==="completed"||o==="failed"||o==="cancelled"}function en(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=>$r(i.status)),groupCount:e.size}}function qr(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 Lr=l(()=>{"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 on=l(()=>{"use strict";Y()});import{Inject as M,Injectable as tu}from"@nestjs/common";import{randomUUID as nn}from"node:crypto";import{exec as eu}from"node:child_process";import{promisify as ou}from"node:util";function Br(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 iu(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 su(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 Jr(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 Qc,Zc,U,nu,ru,Q,ro=l(()=>{"use strict";Be();Ut();Fe();Je();Ye();Oo();Ie();Ee();Te();No();Co();Qo();Y();Rr();Ar();Nr();Dr();Lr();on();Qc=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},Zc=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)}},nu=ou(eu),ru=["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}`);Jr(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:nn(),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}')`);Jr(e.inputSchema,t.inputValues);let n=t.subjectContext??await this.resolveSubjectContext(e,t.subjectId),i=new Date().toISOString();return this.jobs.create({id:nn(),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:nn(),stepDefinitionId:c.id,type:c.type,status:"running",startedAt:f},y=tn(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:kr(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(Br(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(Br(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=en(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,hs)=>(E.fanOutIndex??0)-(hs.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=en(r,m=>m.fanOutIndex);if(!s||s.groupCount!==i.resolvedSubjects.length||!s.allTerminal)return;let{activeJobs:a}=s,u=qr(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:ru,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=Cr(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 nu(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=iu(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=Pr(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=su(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=Qc([tu(),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)),Zc("design:paramtypes",[L,x,J,B,z,Object,Object,Object,Object,Object,Object,pt])],Q)});import{Module as cu}from"@nestjs/common";var au,Xt,rn=l(()=>{"use strict";de();Ge();Qe();Or();ro();au=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=au([cu({imports:[it,jt,It,Ze],providers:[Q],exports:[Q]})],Xt)});import{Catch as du}from"@nestjs/common";var uu,io,Fr=l(()=>{"use strict";Y();uu=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=uu([du(Ct)],io)});import{z as V}from"zod";var at,Ht,so,ao,sn=l(()=>{"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 Ur=l(()=>{"use strict";sn()});function pu(o){let t=o.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"");return t.length>0?t:"step"}function Mr(o,t){let e=pu(o);if(!t.has(e))return e;let n=2;for(;t.has(`${e}-${n}`);)n+=1;return`${e}-${n}`}function Vr(o,t){for(let e of o)e.id&&t.push(e.id),e.type==="loop"&&Array.isArray(e.steps)&&Vr(e.steps,t)}function Kr(o){let t=[];Vr(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 Xr(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 an=l(()=>{"use strict"});import{z as p}from"zod";var lu,me,fu,xt,Hr,Wr,Gr,zr,Yr,Qr,Zr,ti,mu,ei,oi,he,hu,bu,gu,yu,wu,Su,_u,ni,Wt,ri=l(()=>{"use strict";sn();an();lu=p.enum(["on_fail","on_complete","on_needs_input"]),me=p.object({triggers:p.array(lu),messageTemplate:p.string().optional()}),fu=p.object({name:p.string().min(1),label:p.string().min(1),type:p.enum(["string","number","boolean","select"]),options:p.array(p.string()).optional(),required:p.boolean(),defaultValue:p.unknown().optional()}),xt=p.string().min(1),Hr=p.object({type:p.literal("agent"),id:p.string().min(1),name:xt,objective:p.string().min(1),knowledgeScope:p.array(p.enum(["user","organization","project"])).optional(),outputFormat:p.enum(["questionnaire","confirmation","comment_suggestions","free_text"])}),Wr=p.object({type:p.literal("interaction"),id:p.string().min(1),name:xt,interaction:p.union([p.literal("questionnaire"),p.literal("confirmation"),p.literal("conversation")]),notify:p.boolean().optional()}),Gr=p.object({type:p.literal("shell"),id:p.string().min(1),name:xt,command:p.string().min(1)}),zr=p.object({type:p.literal("git"),id:p.string().min(1),name:xt,operation:p.enum(["create_worktree","checkout","create_branch","commit","push"]),params:p.record(p.string(),p.unknown())}),Yr=p.object({type:p.literal("provider_action"),id:p.string().min(1),name:xt,action:p.enum(["get_subject","get_comments","post_comment","update_status","get_content"]),params:p.record(p.string(),p.unknown()).optional()}),Qr=p.object({type:p.literal("sub_workflow"),id:p.string().min(1),name:xt,workflowId:p.string().min(1),forEach:p.literal("selection")}),Zr=p.discriminatedUnion("type",[p.object({type:p.literal("field_empty"),stepId:p.string().min(1),field:p.string().min(1)}),p.object({type:p.literal("field_equals"),stepId:p.string().min(1),field:p.string().min(1),value:p.unknown()})]),ti=p.discriminatedUnion("action",[p.object({action:p.literal("fail")}),p.object({action:p.literal("continue")}),p.object({action:p.literal("ask_human")})]),mu=p.object({type:p.literal("loop"),id:p.string().min(1),name:xt,steps:p.array(p.lazy(()=>ei)),until:Zr,maxIterations:p.number().int().nonnegative(),onMaxIterations:ti}),ei=p.lazy(()=>p.discriminatedUnion("type",[zr,Yr,Gr,Hr,Wr,Qr,mu])),oi=p.object({id:p.string().min(1),name:p.string().min(1),description:p.string().optional(),appliesTo:p.union([at,p.array(at),p.literal("none")]),cardinality:p.enum(["single","batch","aggregate"]),inputSchema:p.array(fu),steps:p.array(ei),notificationPolicy:me}),he=oi.superRefine((o,t)=>{let e=Kr(o.steps);e.length!==0&&t.addIssue({code:"custom",path:["steps"],message:`Duplicate step id(s): ${e.join(", ")}`})}),hu=Hr.extend({id:p.string().min(1).optional()}),bu=Wr.extend({id:p.string().min(1).optional()}),gu=Gr.extend({id:p.string().min(1).optional()}),yu=zr.extend({id:p.string().min(1).optional()}),wu=Yr.extend({id:p.string().min(1).optional()}),Su=Qr.extend({id:p.string().min(1).optional()}),_u=p.object({type:p.literal("loop"),id:p.string().min(1).optional(),name:xt,steps:p.array(p.lazy(()=>ni)),until:Zr,maxIterations:p.number().int().nonnegative(),onMaxIterations:ti}),ni=p.lazy(()=>p.discriminatedUnion("type",[yu,wu,gu,hu,bu,Su,_u])),Wt=oi.omit({id:!0,steps:!0}).extend({id:p.string().min(1).optional(),steps:p.array(ni)})});var ii=l(()=>{"use strict";ri();an()});var si=l(()=>{"use strict"});var ai=l(()=>{"use strict";si()});var ci=l(()=>{"use strict"});var ui=l(()=>{"use strict";ci()});var di=l(()=>{"use strict"});var pi=l(()=>{"use strict";di()});import{z as k}from"zod";var Gt,li=l(()=>{"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 fi=l(()=>{"use strict";li()});import{z as K}from"zod";var mi,hi,bi,gi,cn,co,yi=l(()=>{"use strict";mi=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(),hi=K.object({ticket:K.enum(["jira","manual"]).optional(),repo:K.enum(["bitbucket","manual"]).optional(),agent:K.enum(["claude","cursor"]).optional()}),bi=K.object({baseUrl:mi,email:K.string().min(1).optional()}),gi=K.object({baseUrl:mi,email:K.string().min(1).optional(),workspace:K.string().min(1).optional()}),cn=K.object({activeProviders:hi.optional(),jira:bi.optional(),bitbucket:gi.optional()}),co=K.object({activeProviders:hi.optional(),jira:bi.partial().optional(),bitbucket:gi.partial().optional()})});var wi=l(()=>{"use strict";yi()});var Si=l(()=>{"use strict"});var _i=l(()=>{"use strict";Si()});var lt=l(()=>{"use strict";Ur();ii();ai();ui();pi();fi();wi();_i()});var j,Et=l(()=>{"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 ju}from"node:crypto";function Iu(){return ju()}function un(o){let t=o.id??Iu(),e=Xr(o.steps),n=ji(o.steps,e);return{...o,id:t,steps:n}}function ji(o,t){return o.map(e=>{let n=e.id;return n||(n=Mr(e.name,t),t.add(n)),e.type==="loop"?{...e,id:n,steps:ji(e.steps,t)}:{...e,id:n}})}var Ii=l(()=>{"use strict";lt()});import{Body as Ei,Controller as xu,Delete as Eu,Get as vi,HttpCode as vu,Inject as xi,Param as dn,Patch as Tu,Post as Ou,Query as Ru}from"@nestjs/common";var zt,T,vt,Pu,ft,Ti=l(()=>{"use strict";lt();Be();Ut();Y();Et();Ii();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)}},Pu=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=un(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=un({...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=>!Pu.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([vi(),vt(0,Ru("cardinality")),T("design:type",Function),T("design:paramtypes",[String]),T("design:returntype",Promise)],ft.prototype,"list",null);zt([vi(":id"),vt(0,dn("id")),T("design:type",Function),T("design:paramtypes",[String]),T("design:returntype",Promise)],ft.prototype,"get",null);zt([Ou(),vt(0,Ei(new j(Wt))),T("design:type",Function),T("design:paramtypes",[Object]),T("design:returntype",Promise)],ft.prototype,"create",null);zt([Tu(":id"),vt(0,dn("id")),vt(1,Ei(new j(Wt))),T("design:type",Function),T("design:paramtypes",[String,Object]),T("design:returntype",Promise)],ft.prototype,"update",null);zt([Eu(":id"),vu(204),vt(0,dn("id")),T("design:type",Function),T("design:paramtypes",[String]),T("design:returntype",Promise)],ft.prototype,"remove",null);ft=zt([xu("workflows"),vt(0,xi(L)),vt(1,xi(x)),T("design:paramtypes",[L,x])],ft)});import{Body as pn,Controller as Au,Delete as ku,Get as ln,HttpCode as Nu,Inject as uo,Param as po,Patch as Oi,Post as Cu,Query as Du}from"@nestjs/common";var Tt,_,X,Z,Ri=l(()=>{"use strict";lt();Je();Y();Et();Ie();Ee();Te();on();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([ln(),X(0,Du("subjectType")),_("design:type",Function),_("design:paramtypes",[String]),_("design:returntype",Promise)],Z.prototype,"list",null);Tt([Oi("reorder"),X(0,pn(new j(ao))),_("design:type",Function),_("design:paramtypes",[Object]),_("design:returntype",Promise)],Z.prototype,"reorder",null);Tt([ln(":id/subjects"),X(0,po("id")),_("design:type",Function),_("design:paramtypes",[String]),_("design:returntype",Promise)],Z.prototype,"listSubjects",null);Tt([ln(":id"),X(0,po("id")),_("design:type",Function),_("design:paramtypes",[String]),_("design:returntype",Promise)],Z.prototype,"get",null);Tt([Cu(),X(0,pn(new j(so))),_("design:type",Function),_("design:paramtypes",[Object]),_("design:returntype",Promise)],Z.prototype,"create",null);Tt([Oi(":id"),X(0,po("id")),X(1,pn(new j(Ht.partial().omit({id:!0,order:!0})))),_("design:type",Function),_("design:paramtypes",[String,Object]),_("design:returntype",Promise)],Z.prototype,"update",null);Tt([ku(":id"),Nu(204),X(0,po("id")),_("design:type",Function),_("design:paramtypes",[String]),_("design:returntype",Promise)],Z.prototype,"remove",null);Z=Tt([Au("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 fn=l(()=>{"use strict"});import{z as Ot}from"zod";var mo,ho,mn=l(()=>{"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 Ai,Controller as $u,Get as ki,Inject as Pi,Param as hn,Post as bn,Query as $t}from"@nestjs/common";import"zod";var Yt,O,N,qu,mt,Ni=l(()=>{"use strict";ro();Ut();Y();Et();fn();mn();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)}},qu=["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!==""&&!qu.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([ki(),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([ki(":id"),N(0,hn("id")),O("design:type",Function),O("design:paramtypes",[String]),O("design:returntype",Promise)],mt.prototype,"get",null);Yt([bn(),N(0,Ai(new j(mo))),O("design:type",Function),O("design:paramtypes",[Object]),O("design:returntype",Promise)],mt.prototype,"create",null);Yt([bn(":id/resume"),N(0,hn("id")),N(1,Ai(new j(ho))),O("design:type",Function),O("design:paramtypes",[String,Object]),O("design:returntype",Promise)],mt.prototype,"resume",null);Yt([bn(":id/retry"),N(0,hn("id")),O("design:type",Function),O("design:paramtypes",[String]),O("design:returntype",Promise)],mt.prototype,"retry",null);mt=Yt([$u("jobs"),N(0,Pi(x)),N(1,Pi(Q)),O("design:paramtypes",[x,Q])],mt)});import{z as C}from"zod";var bo,go,gn=l(()=>{"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 Lu,Controller as Bu,Get as Sn,Inject as yn,Param as Ci,Post as Ju,Query as wn}from"@nestjs/common";import"zod";var be,q,ht,Rt,Di=l(()=>{"use strict";ro();Fe();Ut();Y();Et();fn();gn();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([Sn(),ht(0,wn("workflowId")),ht(1,wn("limit")),ht(2,wn("offset")),q("design:type",Function),q("design:paramtypes",[String,String,String]),q("design:returntype",Promise)],Rt.prototype,"list",null);be([Sn(":id"),ht(0,Ci("id")),q("design:type",Function),q("design:paramtypes",[String]),q("design:returntype",Promise)],Rt.prototype,"get",null);be([Sn(":id/jobs"),ht(0,Ci("id")),q("design:type",Function),q("design:paramtypes",[String]),q("design:returntype",Promise)],Rt.prototype,"listJobs",null);be([Ju(),ht(0,Lu(new j(go))),q("design:type",Function),q("design:paramtypes",[Object]),q("design:returntype",Promise)],Rt.prototype,"launch",null);Rt=be([Bu("batches"),ht(0,yn(J)),ht(1,yn(x)),ht(2,yn(Q)),q("design:paramtypes",[J,x,Q])],Rt)});import{Body as $i,Controller as Fu,Delete as Uu,Get as qi,HttpCode as Mu,Inject as Vu,Param as _n,Patch as Ku,Post as Xu,Query as Hu}from"@nestjs/common";var Qt,R,qt,bt,Li=l(()=>{"use strict";lt();Vo();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([qi(),qt(0,Hu("enabled")),R("design:type",Function),R("design:paramtypes",[String]),R("design:returntype",Promise)],bt.prototype,"list",null);Qt([qi(":id"),qt(0,_n("id")),R("design:type",Function),R("design:paramtypes",[String]),R("design:returntype",Promise)],bt.prototype,"get",null);Qt([Xu(),qt(0,$i(new j(Gt))),R("design:type",Function),R("design:paramtypes",[Object]),R("design:returntype",Promise)],bt.prototype,"create",null);Qt([Ku(":id"),qt(0,_n("id")),qt(1,$i(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([Uu(":id"),Mu(204),qt(0,_n("id")),R("design:type",Function),R("design:paramtypes",[String]),R("design:returntype",Promise)],bt.prototype,"remove",null);bt=Qt([Fu("schedules"),qt(0,Vu(dt)),R("design:paramtypes",[dt])],bt)});import{Controller as Wu,Inject as Gu,Query as Bi,Sse as zu}from"@nestjs/common";import{Observable as Fi}from"rxjs";var Ji,yo,jn,ge,Ui=l(()=>{"use strict";Ye();Ji=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)},jn=function(o,t){return function(e,n){t(e,n,o)}},ge=class{events;constructor(t){this.events=t}stream(t,e){return new Fi(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()}})}};Ji([zu(),jn(0,Bi("jobId")),jn(1,Bi("batchId")),yo("design:type",Function),yo("design:paramtypes",[String,String]),yo("design:returntype",Fi)],ge.prototype,"stream",null);ge=Ji([Wu("events"),jn(0,Gu(z)),yo("design:paramtypes",[z])],ge)});import{extendZodWithOpenApi as Yu}from"@asteasolutions/zod-to-openapi";import{z as Qu}from"zod";var Mi=l(()=>{"use strict";Yu(Qu)});import{z as Vi}from"zod";var wo,In=l(()=>{"use strict";wo=Vi.object({value:Vi.string().min(1)})});import{z as d}from"zod";function hd(o){let t=d.toJSONSchema(o),{$schema:e,...n}=t;return n}function Hi(o){let t=(e,n)=>o.registerComponent("schemas",e,hd(n)).ref;return{WorkflowDefinition:t("WorkflowDefinition",he),WorkflowDefinitionInput:t("WorkflowDefinitionInput",Wt),UpdateWorkflowBody:t("UpdateWorkflowBody",dd),SubjectView:t("SubjectView",Ht),CreateSubjectViewBody:t("CreateSubjectViewBody",so),ReorderViewsBody:t("ReorderViewsBody",ao),UpdateViewBody:t("UpdateViewBody",pd),Schedule:t("Schedule",Gt),UpdateScheduleBody:t("UpdateScheduleBody",ld),EngineSettings:t("EngineSettings",cn),UpdateSettingsBody:t("UpdateSettingsBody",fd),SettingsPatchResponse:t("SettingsPatchResponse",md),SetSecretBody:t("SetSecretBody",wo),CreateJobBody:t("CreateJobBody",mo),ResumeJobBody:t("ResumeJobBody",ho),LaunchBody:t("LaunchBody",go),Job:t("Job",Ki),JobBatch:t("JobBatch",Xi),LaunchResponse:t("LaunchResponse",id),HealthResponse:t("HealthResponse",sd),ProviderStatus:t("ProviderStatus",ad),ErrorResponse:t("ErrorResponse",cd),EngineEvent:t("EngineEvent",ud),Subject:t("Subject",So)}}var Zu,td,ed,od,So,nd,rd,Ki,Xi,id,sd,ad,cd,ud,dd,pd,ld,fd,md,P,xn,En=l(()=>{"use strict";Mi();lt();mn();gn();In();Zu=d.enum(["pending","planning","waiting_for_human","waiting_for_children","implementing","testing","completed","failed","cancelled"]),td=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()}),ed=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()}),od=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",[td,ed,od]),nd=d.discriminatedUnion("mode",[d.object({mode:d.literal("single"),subject:So}),d.object({mode:d.literal("collection"),subjects:d.array(So)})]),rd=d.object({id:d.string(),stepDefinitionId:d.string(),type:d.string(),status:d.enum(["pending","running","waiting_for_children","completed","failed","skipped"]),startedAt:d.string().optional(),completedAt:d.string().optional(),output:d.unknown().optional(),error:d.string().optional(),childJobIds:d.array(d.string()).optional(),iterations:d.array(d.object({index:d.number().int(),stepExecutions:d.array(d.record(d.string(),d.unknown())),startedAt:d.string(),completedAt:d.string().optional()})).optional()}),Ki=d.object({id:d.string(),workflowId:d.string(),status:Zu,subjectContext:nd.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(rd),createdAt:d.string(),updatedAt:d.string(),completedAt:d.string().optional()}),Xi=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()}),id=d.discriminatedUnion("kind",[d.object({kind:d.literal("job"),job:Ki}),d.object({kind:d.literal("batch"),batch:Xi})]),sd=d.object({ok:d.boolean(),service:d.string(),timestamp:d.string()}),ad=d.object({providerId:d.string(),secretKey:d.string(),configured:d.boolean()}),cd=d.object({error:d.string()}),ud=d.object({type:d.string(),timestamp:d.string()}).passthrough(),dd=Wt,pd=Ht.partial().omit({id:!0,order:!0}),ld=Gt.partial().omit({id:!0}),fd=co,md=d.object({settings:cn,restartRequired:d.boolean()}),P=d.object({id:d.string().min(1)}),xn=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 Wi(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:xn.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:xn.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 Gi=l(()=>{"use strict";lt();En()});import{OpenAPIRegistry as bd,OpenApiGeneratorV31 as gd}from"@asteasolutions/zod-to-openapi";function zi(){if(_o)return _o;let o=new bd,t=Hi(o);return Wi(o,t),_o=new gd(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,Yi=l(()=>{"use strict";En();Gi()});import{Controller as yd,Get as wd,Header as Sd}from"@nestjs/common";var Qi,vn,ye,Zi=l(()=>{"use strict";Yi();Qi=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},vn=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},ye=class{getOpenApiDocument(){return zi()}};Qi([wd("openapi.json"),Sd("Content-Type","application/json"),vn("design:type",Function),vn("design:paramtypes",[]),vn("design:returntype",void 0)],ye.prototype,"getOpenApiDocument",null);ye=Qi([yd()],ye)});import{Controller as jd,Get as Id,Inject as xd}from"@nestjs/common";var ts,jo,_d,we,es=l(()=>{"use strict";zo();ts=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)},_d=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()}};ts([Id("status"),jo("design:type",Function),jo("design:paramtypes",[]),jo("design:returntype",Promise)],we.prototype,"status",null);we=ts([jd("providers"),_d(0,xd(_t)),jo("design:paramtypes",[_t])],we)});import{Body as Ed,Controller as vd,Get as Td,Inject as Od,Patch as Rd}from"@nestjs/common";var Tn,Lt,os,Zt,ns=l(()=>{"use strict";lt();Ue();Et();Tn=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)},os=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:fr(t)}}};Tn([Td(),Lt("design:type",Function),Lt("design:paramtypes",[]),Lt("design:returntype",Promise)],Zt.prototype,"get",null);Tn([Rd(),os(0,Ed(new j(co))),Lt("design:type",Function),Lt("design:paramtypes",[Object]),Lt("design:returntype",Promise)],Zt.prototype,"update",null);Zt=Tn([vd("settings"),os(0,Od(D)),Lt("design:paramtypes",[D])],Zt)});import{Body as Pd,Controller as Ad,HttpCode as kd,Inject as Nd,Param as Cd,Post as Dd}from"@nestjs/common";var rs,Io,On,Se,is=l(()=>{"use strict";yt();Y();Et();In();rs=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)},On=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)}};rs([Dd(":key"),kd(204),On(0,Cd("key")),On(1,Pd(new j(wo))),Io("design:type",Function),Io("design:paramtypes",[String,Object]),Io("design:returntype",Promise)],Se.prototype,"set",null);Se=rs([Ad("secrets"),On(0,Nd(H)),Io("design:paramtypes",[Function])],Se)});import{Module as qd}from"@nestjs/common";import{APP_FILTER as Ld}from"@nestjs/core";var $d,xo,ss=l(()=>{"use strict";de();rn();Qe();Fr();Ti();Ri();Ni();Di();Li();Ui();Zi();es();ns();is();Ge();Do();$d=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=$d([qd({imports:[it,Xt,It,jt,Bt],controllers:[ft,Z,mt,Rt,bt,ge,ye,we,Zt,Se],providers:[{provide:Ld,useClass:io}]})],xo)});import{Module as Jd}from"@nestjs/common";var Bd,Eo,as=l(()=>{"use strict";Pn();An();kn();Ge();Ir();Qe();de();rn();ss();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},Eo=class{};Eo=Bd([Jd({imports:[_e,je,jt,ze,It,it,Xt,xo],controllers:[te]})],Eo)});import{apiReference as Fd}from"@scalar/nestjs-api-reference";function cs(o){o.use("/api/docs",Fd({url:"/api/openapi.json",pageTitle:"Kno Engine API"}))}var us=l(()=>{"use strict"});import{existsSync as Ud}from"node:fs";import{dirname as Md,join as ds}from"node:path";import{fileURLToPath as Vd}from"node:url";function ps(){let o=Md(Vd(import.meta.url)),t=[ds(o,"../../static"),ds(o,"../static")];for(let e of t)if(Ud(e))return e;return null}var ls=l(()=>{"use strict"});var Wd={};import"reflect-metadata";import{existsSync as Kd}from"node:fs";import{join as fs}from"node:path";import{NestFactory as Xd}from"@nestjs/core";async function Hd(){let o=await Xd.create(Eo);o.enableCors(),o.setGlobalPrefix("api"),cs(o);let t=ps();t&&Kd(fs(t,"index.html"))&&(o.useStaticAssets(t),o.use((n,i,r)=>{if(n.method!=="GET"&&n.method!=="HEAD"||n.path.startsWith("/api"))return r();i.sendFile(fs(t,"index.html"))}));let e=Number(process.env.PORT??3e3);await o.listen(e)}var ms=l(()=>{"use strict";as();us();ls();Hd()});import{readFileSync as Gd}from"node:fs";function zd(){let o=Gd(new URL("../package.json",import.meta.url),"utf8");return JSON.parse(o).version}var vo=process.argv.slice(2);vo.includes("--version")||vo.includes("-v")?console.log(zd()):vo.includes("--help")||vo.includes("-h")?console.log(["Usage: kno [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 HTTP port to listen on (default 3000)"," KNO_SQLITE_PATH SQLite file path, or :memory: for an ephemeral database"].join(`
134
- `)):await Promise.resolve().then(()=>(ms(),Wd));
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));
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "@knoflows/engine",
3
- "version": "0.1.0-alpha.2",
3
+ "version": "0.1.0-alpha.3",
4
4
  "type": "module",
5
5
  "license": "UNLICENSED",
6
6
  "bin": {
7
- "kno": "dist/engine.js"
7
+ "knoflows": "dist/engine.js"
8
8
  },
9
9
  "files": [
10
10
  "dist/engine.js",
@@ -34,7 +34,8 @@
34
34
  "test:provider-status": "tsx src/providers/provider-status.test.ts",
35
35
  "test:runner": "tsx src/runner/test/resolve-view-subjects.test.ts && tsx src/runner/test/workflow-runner.agent-interaction.test.ts && tsx src/runner/test/workflow-runner.git-shell-provider.test.ts && tsx src/runner/test/workflow-runner.loop-subworkflow.test.ts && tsx src/runner/test/workflow-runner.batch-aggregate.test.ts && tsx src/runner/test/workflow-runner.agent-output-validation.test.ts",
36
36
  "test:api": "tsx src/api/test/api-test.ts && tsx src/api/test/boot-empty-secrets.test.ts && tsx src/api/test/providers-status.test.ts && tsx src/api/test/settings.test.ts",
37
- "test:workflows-ids": "tsx src/api/workflows/assign-missing-ids.test.ts"
37
+ "test:workflows-ids": "tsx src/api/workflows/assign-missing-ids.test.ts",
38
+ "test:listen-port": "tsx src/listen-port.test.ts"
38
39
  },
39
40
  "dependencies": {
40
41
  "@anthropic-ai/claude-agent-sdk": "^0.3.243",