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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/engine.js +10 -10
  2. package/package.json +1 -1
package/dist/engine.js CHANGED
@@ -1,17 +1,17 @@
1
1
  #!/usr/bin/env node
2
- var p=(o,t)=>()=>(o&&(t=o(o=0)),t);import{Controller as ja,Get as _a}from"@nestjs/common";var pn,Yo,fe,dn=p(()=>{"use strict";pn=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},Yo=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},fe=class{getHealth(){return{ok:!0,service:"kno-engine",timestamp:new Date().toISOString()}}};pn([_a(),Yo("design:type",Function),Yo("design:paramtypes",[]),Yo("design:returntype",Object)],fe.prototype,"getHealth",null);fe=pn([ja("health")],fe)});import{Module as xa}from"@nestjs/common";var Ia,Ce,fn=p(()=>{"use strict";Ia=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},Ce=class{};Ce=Ia([xa({})],Ce)});import{Module as va}from"@nestjs/common";var Ea,De,mn=p(()=>{"use strict";Ea=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},De=class{};De=Ea([va({})],De)});var Jt,Be=p(()=>{"use strict";Jt=Symbol("TICKET_PROVIDER")});import{randomUUID as Ta}from"node:crypto";function Ra(o,t){return Object.entries(t).every(([e,r])=>o[e]===r)}var $e,hn=p(()=>{"use strict";$e=class{tickets;comments;constructor(t=[]){this.tickets=new Map(t.map(e=>[e.id,structuredClone(e)])),this.comments=new Map}async get(t){let e=this.tickets.get(t);if(!e)throw new Error(`Ticket not found: ${t}`);return structuredClone(e)}async query(t){return[...this.tickets.values()].filter(e=>Ra(e,t)).map(e=>structuredClone(e))}async getComments(t){return await this.get(t),structuredClone(this.comments.get(t)??[])}async postComment(t,e){await this.get(t);let r=this.comments.get(t)??[];r.push({id:Ta(),subjectId:t,body:e,createdAt:new Date().toISOString()}),this.comments.set(t,r)}async updateStatus(t,e){let r=this.tickets.get(t);if(!r)throw new Error(`Ticket not found: ${t}`);r.status=e}}});var Ft,Le=p(()=>{"use strict";Ft=Symbol("REPO_PROVIDER")});import{randomUUID as Oa}from"node:crypto";function Pa(o,t){return Object.entries(t).every(([e,r])=>e==="status"?o.raw?.status===r:o[e]===r)}var Je,bn=p(()=>{"use strict";Je=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=>Pa(e,t)).map(e=>structuredClone(e))}async getComments(t){return await this.get(t),structuredClone(this.comments.get(t)??[])}async postComment(t,e){await this.get(t);let r=this.comments.get(t)??[];r.push({id:Oa(),subjectId:t,body:e,createdAt:new Date().toISOString()}),this.comments.set(t,r)}async updateStatus(t,e){let r=this.pullRequests.get(t);if(!r)throw new Error(`Pull request not found: ${t}`);r.raw={...r.raw??{},status:e}}}});var Ut,Fe=p(()=>{"use strict";Ut=Symbol("DOCUMENTATION_PROVIDER")});import{randomUUID as ka}from"node:crypto";var Aa,Ue,wn=p(()=>{"use strict";Aa=new Set(["github_wiki","gitlab_wiki","azure_wiki","web"]),Ue=class{pages;contentById;comments;constructor(t=[]){this.pages=new Map,this.contentById=new Map,this.comments=new Map;for(let e of t){let{content:r,...i}=e;this.pages.set(i.id,structuredClone(i)),r!==void 0&&this.contentById.set(i.id,r)}}async get(t){let e=this.pages.get(t);if(!e)throw new Error(`Documentation page not found: ${t}`);return structuredClone(e)}async getContent(t){await this.get(t);let e=this.contentById.get(t);if(e===void 0)throw new Error(`Documentation content not found: ${t}`);return e}async query(t){let e=t.pageIds;if(!Array.isArray(e))throw new Error("Documentation query requires { pageIds: string[] }");let r=[];for(let i of e)r.push(await this.get(String(i)));return r}async getComments(t){let e=await this.get(t);return this.assertCommentsSupported(e),structuredClone(this.comments.get(t)??[])}async postComment(t,e){let r=await this.get(t);this.assertCommentsSupported(r);let i=this.comments.get(t)??[];i.push({id:ka(),subjectId:t,body:e,createdAt:new Date().toISOString()}),this.comments.set(t,i)}assertCommentsSupported(t){if(Aa.has(t.source))throw new Error(`Comments are not supported for documentation source '${t.source}'`)}}});var me,Zo=p(()=>{"use strict";me=Symbol("AGENT_PROVIDER")});import{createCipheriv as Na,createDecipheriv as qa,randomBytes as yn}from"node:crypto";import{mkdir as gn,readFile as Sn,writeFile as jn}from"node:fs/promises";import{join as er}from"node:path";function St(o){return`kno.${o}.apiKey`}function $a(o){return er(o,"secrets")}function In(o){return new or($a(o.dataDir),o.keyring)}function La(o){try{return o(Me,"__kno_probe__").getPassword(),!0}catch(t){return rr(t)}}function rr(o){let t=o instanceof Error?o.message:String(o);return/noentry|no matching entry|not found|no such/i.test(t)}var Me,_n,Ca,tr,Da,Ba,or,ot,Tt=p(()=>{"use strict";Me="kno-flows";_n="aes-256-gcm",Ca=12,tr=32,Da="master.key",Ba="store.json",or=class{secretsDir;keyring;keyringResolved=!1;masterKey=null;constructor(t,e){this.secretsDir=t,this.keyring=e,e!==void 0&&(this.keyringResolved=!0)}async get(t){let e=await this.resolveKeyring();if(e)try{let r=e(Me,t).getPassword();if(r!=null)return r}catch(r){rr(r)||this.disableKeyring()}return this.fileGet(t)}async set(t,e){let r=await this.resolveKeyring();if(r)try{r(Me,t).setPassword(e),await this.fileDelete(t);return}catch{this.disableKeyring()}await this.fileSet(t,e)}async delete(t){let e=await this.resolveKeyring();if(e)try{e(Me,t).deletePassword()}catch(r){rr(r)||this.disableKeyring()}await this.fileDelete(t)}disableKeyring(){this.keyring=null,this.keyringResolved=!0}async resolveKeyring(){if(this.keyringResolved)return this.keyring??null;this.keyringResolved=!0;try{let{Entry:t}=await import("@napi-rs/keyring"),e=(r,i)=>new t(r,i);return La(e)?(this.keyring=e,e):(this.keyring=null,null)}catch{return this.keyring=null,null}}async fileGet(t){let r=(await this.readStore())[t];return r?this.decrypt(r):null}async fileSet(t,e){let r=await this.readStore();r[t]=await this.encrypt(e),await this.writeStore(r)}async fileDelete(t){let e=await this.readStore();t in e&&(delete e[t],await this.writeStore(e))}async readStore(){try{let t=await Sn(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 gn(this.secretsDir,{recursive:!0}),await jn(this.storePath(),JSON.stringify(t,null,2),{encoding:"utf8",mode:384})}async encrypt(t){let e=await this.loadOrCreateMasterKey(),r=yn(Ca),i=Na(_n,e,r),n=Buffer.concat([i.update(t,"utf8"),i.final()]);return{iv:r.toString("base64"),tag:i.getAuthTag().toString("base64"),ciphertext:n.toString("base64")}}async decrypt(t){let e=await this.loadOrCreateMasterKey(),r=qa(_n,e,Buffer.from(t.iv,"base64"));return r.setAuthTag(Buffer.from(t.tag,"base64")),Buffer.concat([r.update(Buffer.from(t.ciphertext,"base64")),r.final()]).toString("utf8")}async loadOrCreateMasterKey(){if(this.masterKey)return this.masterKey;await gn(this.secretsDir,{recursive:!0});let t=this.masterKeyPath();try{let r=(await Sn(t,"utf8")).trim(),i=Buffer.from(r,"hex");if(i.length!==tr)throw new Error(`Secret store master key at ${t} is not ${tr} bytes`);return this.masterKey=i,i}catch(r){if(r.code!=="ENOENT")throw r}let e=yn(tr);return await jn(t,e.toString("hex"),{encoding:"utf8",mode:384}),this.masterKey=e,e}storePath(){return er(this.secretsDir,Ba)}masterKeyPath(){return er(this.secretsDir,Da)}};ot=Symbol("SECRET_STORE")});function Ve(o){let t=St(o),e=Ma[o]??o;return new Error(`${e} API key not configured \u2014 set '${t}' via the setup script`)}function xn(o){let t=new Map;for(let r of o){let i=r.content.trim();if(!i)continue;let n=t.get(r.tier)??[];n.push(i),t.set(r.tier,n)}let e=[];for(let r of Fa){let i=t.get(r);i?.length&&e.push(`## ${Ja[r]}
2
+ var p=(o,t)=>()=>(o&&(t=o(o=0)),t);import{Controller as Ea,Get as va}from"@nestjs/common";var fn,Zo,fe,mn=p(()=>{"use strict";fn=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},Zo=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},fe=class{getHealth(){return{ok:!0,service:"kno-engine",timestamp:new Date().toISOString()}}};fn([va(),Zo("design:type",Function),Zo("design:paramtypes",[]),Zo("design:returntype",Object)],fe.prototype,"getHealth",null);fe=fn([Ea("health")],fe)});import{Module as Ra}from"@nestjs/common";var Ta,Ce,hn=p(()=>{"use strict";Ta=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},Ce=class{};Ce=Ta([Ra({})],Ce)});import{Module as Pa}from"@nestjs/common";var Oa,De,bn=p(()=>{"use strict";Oa=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},De=class{};De=Oa([Pa({})],De)});var Ut,Be=p(()=>{"use strict";Ut=Symbol("TICKET_PROVIDER")});import{randomUUID as ka}from"node:crypto";function Aa(o,t){return Object.entries(t).every(([e,r])=>o[e]===r)}var $e,wn=p(()=>{"use strict";$e=class{tickets;comments;constructor(t=[]){this.tickets=new Map(t.map(e=>[e.id,structuredClone(e)])),this.comments=new Map}async get(t){let e=this.tickets.get(t);if(!e)throw new Error(`Ticket not found: ${t}`);return structuredClone(e)}async query(t){return[...this.tickets.values()].filter(e=>Aa(e,t)).map(e=>structuredClone(e))}async getComments(t){return await this.get(t),structuredClone(this.comments.get(t)??[])}async postComment(t,e){await this.get(t);let r=this.comments.get(t)??[];r.push({id:ka(),subjectId:t,body:e,createdAt:new Date().toISOString()}),this.comments.set(t,r)}async updateStatus(t,e){let r=this.tickets.get(t);if(!r)throw new Error(`Ticket not found: ${t}`);r.status=e}}});var Ft,Le=p(()=>{"use strict";Ft=Symbol("REPO_PROVIDER")});import{randomUUID as Na}from"node:crypto";function qa(o,t){return Object.entries(t).every(([e,r])=>e==="status"?o.raw?.status===r:o[e]===r)}var Ue,yn=p(()=>{"use strict";Ue=class{pullRequests;comments;constructor(t=[]){this.pullRequests=new Map(t.map(e=>[e.id,structuredClone(e)])),this.comments=new Map}async get(t){let e=this.pullRequests.get(t);if(!e)throw new Error(`Pull request not found: ${t}`);return structuredClone(e)}async query(t){return[...this.pullRequests.values()].filter(e=>qa(e,t)).map(e=>structuredClone(e))}async getComments(t){return await this.get(t),structuredClone(this.comments.get(t)??[])}async postComment(t,e){await this.get(t);let r=this.comments.get(t)??[];r.push({id:Na(),subjectId:t,body:e,createdAt:new Date().toISOString()}),this.comments.set(t,r)}async updateStatus(t,e){let r=this.pullRequests.get(t);if(!r)throw new Error(`Pull request not found: ${t}`);r.raw={...r.raw??{},status:e}}}});var Jt,Fe=p(()=>{"use strict";Jt=Symbol("DOCUMENTATION_PROVIDER")});import{randomUUID as Ca}from"node:crypto";var Da,Je,gn=p(()=>{"use strict";Da=new Set(["github_wiki","gitlab_wiki","azure_wiki","web"]),Je=class{pages;contentById;comments;constructor(t=[]){this.pages=new Map,this.contentById=new Map,this.comments=new Map;for(let e of t){let{content:r,...i}=e;this.pages.set(i.id,structuredClone(i)),r!==void 0&&this.contentById.set(i.id,r)}}async get(t){let e=this.pages.get(t);if(!e)throw new Error(`Documentation page not found: ${t}`);return structuredClone(e)}async getContent(t){await this.get(t);let e=this.contentById.get(t);if(e===void 0)throw new Error(`Documentation content not found: ${t}`);return e}async query(t){let e=t.pageIds;if(!Array.isArray(e))throw new Error("Documentation query requires { pageIds: string[] }");let r=[];for(let i of e)r.push(await this.get(String(i)));return r}async getComments(t){let e=await this.get(t);return this.assertCommentsSupported(e),structuredClone(this.comments.get(t)??[])}async postComment(t,e){let r=await this.get(t);this.assertCommentsSupported(r);let i=this.comments.get(t)??[];i.push({id:Ca(),subjectId:t,body:e,createdAt:new Date().toISOString()}),this.comments.set(t,i)}assertCommentsSupported(t){if(Da.has(t.source))throw new Error(`Comments are not supported for documentation source '${t.source}'`)}}});var me,tr=p(()=>{"use strict";me=Symbol("AGENT_PROVIDER")});import{createCipheriv as Ba,createDecipheriv as $a,randomBytes as Sn}from"node:crypto";import{mkdir as jn,readFile as _n,writeFile as In}from"node:fs/promises";import{join as or}from"node:path";function St(o){return`kno.${o}.apiKey`}function Ja(o){return or(o,"secrets")}function En(o){return new rr(Ja(o.dataDir),o.keyring)}function Ma(o){try{return o(Me,"__kno_probe__").getPassword(),!0}catch(t){return nr(t)}}function nr(o){let t=o instanceof Error?o.message:String(o);return/noentry|no matching entry|not found|no such/i.test(t)}var Me,xn,La,er,Ua,Fa,rr,ot,Tt=p(()=>{"use strict";Me="kno-flows";xn="aes-256-gcm",La=12,er=32,Ua="master.key",Fa="store.json",rr=class{secretsDir;keyring;keyringResolved=!1;masterKey=null;constructor(t,e){this.secretsDir=t,this.keyring=e,e!==void 0&&(this.keyringResolved=!0)}async get(t){let e=await this.resolveKeyring();if(e)try{let r=e(Me,t).getPassword();if(r!=null)return r}catch(r){nr(r)||this.disableKeyring()}return this.fileGet(t)}async set(t,e){let r=await this.resolveKeyring();if(r)try{r(Me,t).setPassword(e),await this.fileDelete(t);return}catch{this.disableKeyring()}await this.fileSet(t,e)}async delete(t){let e=await this.resolveKeyring();if(e)try{e(Me,t).deletePassword()}catch(r){nr(r)||this.disableKeyring()}await this.fileDelete(t)}disableKeyring(){this.keyring=null,this.keyringResolved=!0}async resolveKeyring(){if(this.keyringResolved)return this.keyring??null;this.keyringResolved=!0;try{let{Entry:t}=await import("@napi-rs/keyring"),e=(r,i)=>new t(r,i);return Ma(e)?(this.keyring=e,e):(this.keyring=null,null)}catch{return this.keyring=null,null}}async fileGet(t){let r=(await this.readStore())[t];return r?this.decrypt(r):null}async fileSet(t,e){let r=await this.readStore();r[t]=await this.encrypt(e),await this.writeStore(r)}async fileDelete(t){let e=await this.readStore();t in e&&(delete e[t],await this.writeStore(e))}async readStore(){try{let t=await _n(this.storePath(),"utf8"),e=JSON.parse(t);if(e==null||typeof e!="object"||Array.isArray(e))throw new Error(`Corrupt secret store at ${this.storePath()}`);return e}catch(t){if(t.code==="ENOENT")return{};throw t}}async writeStore(t){await jn(this.secretsDir,{recursive:!0}),await In(this.storePath(),JSON.stringify(t,null,2),{encoding:"utf8",mode:384})}async encrypt(t){let e=await this.loadOrCreateMasterKey(),r=Sn(La),i=Ba(xn,e,r),n=Buffer.concat([i.update(t,"utf8"),i.final()]);return{iv:r.toString("base64"),tag:i.getAuthTag().toString("base64"),ciphertext:n.toString("base64")}}async decrypt(t){let e=await this.loadOrCreateMasterKey(),r=$a(xn,e,Buffer.from(t.iv,"base64"));return r.setAuthTag(Buffer.from(t.tag,"base64")),Buffer.concat([r.update(Buffer.from(t.ciphertext,"base64")),r.final()]).toString("utf8")}async loadOrCreateMasterKey(){if(this.masterKey)return this.masterKey;await jn(this.secretsDir,{recursive:!0});let t=this.masterKeyPath();try{let r=(await _n(t,"utf8")).trim(),i=Buffer.from(r,"hex");if(i.length!==er)throw new Error(`Secret store master key at ${t} is not ${er} bytes`);return this.masterKey=i,i}catch(r){if(r.code!=="ENOENT")throw r}let e=Sn(er);return await In(t,e.toString("hex"),{encoding:"utf8",mode:384}),this.masterKey=e,e}storePath(){return or(this.secretsDir,Fa)}masterKeyPath(){return or(this.secretsDir,Ua)}};ot=Symbol("SECRET_STORE")});function Ve(o){let t=St(o),e=Ka[o]??o;return new Error(`${e} API key not configured \u2014 set '${t}' via the setup script`)}function vn(o){let t=new Map;for(let r of o){let i=r.content.trim();if(!i)continue;let n=t.get(r.tier)??[];n.push(i),t.set(r.tier,n)}let e=[];for(let r of Wa){let i=t.get(r);i?.length&&e.push(`## ${Va[r]}
3
3
  ${i.join(`
4
4
 
5
5
  `)}`)}return e.join(`
6
6
 
7
- `)}function he(o){let t=[],e=xn(o.knowledge);return e&&t.push(e),t.push(`# Objective
7
+ `)}function he(o){let t=[],e=vn(o.knowledge);return e&&t.push(e),t.push(`# Objective
8
8
  ${o.objective}`),t.push(`# Output format
9
- ${Ua[o.outputFormat]}`),t.join(`
9
+ ${Xa[o.outputFormat]}`),t.join(`
10
10
 
11
- `)}function be(o,t){return t==="free_text"?o:En(o)}function En(o){let t=[...o.matchAll(/```json\s*([\s\S]*?)```/gi)].map(i=>i[1].trim()),e=[...o.matchAll(/```\s*([\s\S]*?)```/g)].map(i=>i[1].trim()),r=[...t].reverse();r.length===0&&r.push(...[...e].reverse()),r.push(o.trim());for(let i of r)if(i)try{return JSON.parse(i)}catch{continue}throw new Error("No valid JSON block found in agent response")}var Ja,Fa,Ua,Ma,We=p(()=>{"use strict";Tt();Ja={user:"User preferences",organization:"Organization guidelines",project:"Project context"},Fa=["user","organization","project"],Ua={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."},Ma={anthropic:"Anthropic",cursor:"Cursor"}});async function*Wa(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 Va,Xe,vn=p(()=>{"use strict";We();Tt();We();Va=St("anthropic"),Xe=class{secrets;queryFn;constructor(t,e){this.secrets=t,this.queryFn=e}async run(t){let e=await this.requireApiKey(),r=he(t),i={permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,env:{...process.env,ANTHROPIC_API_KEY:e}};t.cwd&&(i.cwd=t.cwd),t.sessionId&&(i.resume=t.sessionId);let n=this.queryFn??Wa,s,a,u;for await(let c of n({prompt:r,options:i}))c.session_id&&(s=c.session_id),c.type==="result"&&(c.subtype==="success"&&typeof c.result=="string"?a=c.result:u=c.errors?.join("; ")||c.subtype||"Claude agent returned an error result");if(u)throw new Error(`Claude agent failed: ${u}`);if(a==null)throw new Error("Claude agent returned no result text");if(!s)throw new Error("Claude agent returned no session id");return{raw:a,parsed:be(a,t.outputFormat),sessionId:s}}async requireApiKey(){let t=await this.secrets.get(Va);if(!t)throw Ve("anthropic");return t}}});function Ka(o,t){return{apiKey:o,model:{id:"composer-2.5"},local:{...t?{cwd:t}:{},settingSources:[]}}}async function Ha(){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 Xa,Ke,Tn=p(()=>{"use strict";We();Tt();Xa=St("cursor"),Ke=class{secrets;sdk;constructor(t,e){this.secrets=t,this.sdk=e}async run(t){let e=await this.requireApiKey(),r=he(t),i=this.sdk??await Ha(),n=Ka(e,t.cwd),s=t.sessionId?await i.resume(t.sessionId,n):await i.create(n);try{let u=await(await s.send(r)).wait();if(u.status!=="finished")throw new Error(u.error?.message||`Cursor agent ended with status '${u.status}'`);let c=u.result??"";return{raw:c,parsed:be(c,t.outputFormat),sessionId:s.agentId}}finally{await s[Symbol.asyncDispose]?.()}}async requireApiKey(){let t=await this.secrets.get(Xa);if(!t)throw Ve("cursor");return t}}});var we,nr=p(()=>{"use strict";we=Symbol("NOTIFICATION_PROVIDER")});var He,Rn=p(()=>{"use strict";He=class{async send(t){console.log("[notification]",JSON.stringify(t))}}});var ye,ir=p(()=>{"use strict";ye=Symbol("KNOWLEDGE_PROVIDER")});import{readdir as Ga,readFile as za}from"node:fs/promises";import{join as On}from"node:path";var Ge,Pn=p(()=>{"use strict";Ge=class{baseDir;constructor(t){this.baseDir=t}async resolve(t,e){let r=On(this.baseDir,t),i;try{i=await Ga(r)}catch(a){if(a.code==="ENOENT")return[];throw a}let n=i.filter(a=>a.endsWith(".md")).sort(),s=[];for(let a of n){let u=On(r,a),c=await za(u,"utf8");s.push({tier:t,content:c,sourceRef:u})}return s}}});import{Module as Ya}from"@nestjs/common";import{mkdirSync as Za}from"node:fs";import{dirname as tc,join as ec}from"node:path";import{fileURLToPath as oc}from"node:url";var Qa,kn,Zt,sr=p(()=>{"use strict";Tt();Qa=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},kn=ec(tc(oc(import.meta.url)),"../../data");Za(kn,{recursive:!0});Zt=class{};Zt=Qa([Ya({providers:[{provide:ot,useFactory:()=>In({dataDir:kn})}],exports:[ot]})],Zt)});import{index as rc,sqliteTable as nc,text as at}from"drizzle-orm/sqlite-core";var ct,ze=p(()=>{"use strict";ct=nc("workflow_definitions",{id:at("id").primaryKey(),name:at("name").notNull(),description:at("description"),appliesTo:at("applies_to",{mode:"json"}).$type().notNull(),cardinality:at("cardinality",{enum:["single","batch","aggregate"]}).notNull(),inputSchema:at("input_schema",{mode:"json"}).$type().notNull(),steps:at("steps",{mode:"json"}).$type().notNull(),notificationPolicy:at("notification_policy",{mode:"json"}).$type().notNull(),createdAt:at("created_at").notNull(),updatedAt:at("updated_at").notNull()},o=>[rc("workflow_definitions_cardinality_idx").on(o.cardinality)])});import{index as An,integer as ic,sqliteTable as sc,text as Mt}from"drizzle-orm/sqlite-core";var ut,ar=p(()=>{"use strict";ut=sc("subject_views",{id:Mt("id").primaryKey(),name:Mt("name").notNull(),subjectType:Mt("subject_type").$type().notNull(),workflowId:Mt("workflow_id").notNull(),query:Mt("query",{mode:"json"}).$type().notNull(),description:Mt("description"),queryTemplate:Mt("query_template",{mode:"json"}).$type(),order:ic("order").notNull().default(0)},o=>[An("subject_views_subject_type_idx").on(o.subjectType),An("subject_views_subject_type_order_idx").on(o.subjectType,o.order)])});import{index as Nn,integer as ac,sqliteTable as cc,text as lt}from"drizzle-orm/sqlite-core";var Rt,Qe=p(()=>{"use strict";Rt=cc("job_batches",{id:lt("id").primaryKey(),workflowId:lt("workflow_id").notNull(),selection:lt("selection",{mode:"json"}).$type().notNull(),resolvedSubjects:lt("resolved_subjects",{mode:"json"}).$type().notNull(),status:lt("status",{enum:["running","completed","completed_with_issues","failed"]}).notNull(),triggeredBy:lt("triggered_by",{enum:["schedule","view_bulk","multiselect"]}).notNull(),scheduleId:lt("schedule_id"),notificationOverride:lt("notification_override",{mode:"json"}).$type(),notificationSent:ac("notification_sent",{mode:"boolean"}).notNull(),createdAt:lt("created_at").notNull(),completedAt:lt("completed_at")},o=>[Nn("job_batches_workflow_id_idx").on(o.workflowId),Nn("job_batches_schedule_id_idx").on(o.scheduleId)])});import{index as Ye,integer as uc,sqliteTable as lc,text as A}from"drizzle-orm/sqlite-core";var N,ge=p(()=>{"use strict";ze();Qe();N=lc("jobs",{id:A("id").primaryKey(),workflowId:A("workflow_id").notNull().references(()=>ct.id),status:A("status").$type().notNull(),selection:A("selection",{mode:"json"}).$type(),batchId:A("batch_id").references(()=>Rt.id),parentJobId:A("parent_job_id"),parentStepExecutionId:A("parent_step_execution_id"),fanOutIndex:uc("fan_out_index"),retryOf:A("retry_of"),context:A("context",{mode:"json"}).$type().notNull(),worktreePath:A("worktree_path"),branch:A("branch"),currentStepId:A("current_step_id"),currentStepExecutionId:A("current_step_execution_id"),createdAt:A("created_at").notNull(),updatedAt:A("updated_at").notNull(),completedAt:A("completed_at")},o=>[Ye("jobs_workflow_id_idx").on(o.workflowId),Ye("jobs_status_idx").on(o.status),Ye("jobs_batch_id_idx").on(o.batchId),Ye("jobs_parent_job_id_idx").on(o.parentJobId)])});import{index as qn,sqliteTable as pc,text as Se}from"drizzle-orm/sqlite-core";var pt,cr=p(()=>{"use strict";ge();pt=pc("job_subjects",{id:Se("id").primaryKey(),jobId:Se("job_id").notNull().references(()=>N.id),subjectType:Se("subject_type").$type().notNull(),subjectId:Se("subject_id").notNull(),snapshot:Se("snapshot",{mode:"json"}).$type().notNull()},o=>[qn("job_subjects_job_id_idx").on(o.jobId),qn("job_subjects_subject_lookup_idx").on(o.subjectType,o.subjectId)])});import{index as Cn,integer as dc,sqliteTable as fc,text as rt}from"drizzle-orm/sqlite-core";var Vt,ur=p(()=>{"use strict";ge();Vt=fc("job_step_executions",{id:rt("id").primaryKey(),jobId:rt("job_id").notNull().references(()=>N.id),stepDefinitionId:rt("step_definition_id").notNull(),type:rt("type").$type().notNull(),status:rt("status").$type().notNull(),startedAt:rt("started_at"),completedAt:rt("completed_at"),output:rt("output",{mode:"json"}).$type(),error:rt("error"),childJobIds:rt("child_job_ids",{mode:"json"}).$type(),parentStepExecutionId:rt("parent_step_execution_id").references(()=>Vt.id),iterationIndex:dc("iteration_index")},o=>[Cn("job_step_executions_job_id_idx").on(o.jobId),Cn("job_step_executions_parent_idx").on(o.parentStepExecutionId)])});import{index as mc,integer as hc,sqliteTable as bc,text as Ot}from"drizzle-orm/sqlite-core";var Pt,lr=p(()=>{"use strict";Pt=bc("schedules",{id:Ot("id").primaryKey(),viewId:Ot("view_id").notNull(),triggerType:Ot("trigger_type",{enum:["cron"]}).notNull(),cadence:Ot("cadence").notNull(),notificationOverride:Ot("notification_override",{mode:"json"}).$type(),missedFirePolicy:Ot("missed_fire_policy",{enum:["skip","catch_up"]}).notNull(),enabled:hc("enabled",{mode:"boolean"}).notNull(),lastFiredAt:Ot("last_fired_at"),createdAt:Ot("created_at").notNull()},o=>[mc("schedules_enabled_idx").on(o.enabled)])});import{integer as wc,sqliteTable as yc,text as je}from"drizzle-orm/sqlite-core";var dt,pr=p(()=>{"use strict";dt=yc("workflow_shortcuts",{id:je("id").primaryKey(),name:je("name").notNull(),workflowId:je("workflow_id").notNull(),inputValues:je("input_values",{mode:"json"}).$type().notNull(),lastJobId:je("last_job_id"),order:wc("order").notNull().default(0)})});import{sqliteTable as gc,text as Dn}from"drizzle-orm/sqlite-core";var _e,te,dr=p(()=>{"use strict";_e="default",te=gc("settings",{id:Dn("id").primaryKey(),data:Dn("data",{mode:"json"}).$type().notNull()})});import{defineRelations as Sc}from"drizzle-orm";var jc,Bn,$n=p(()=>{"use strict";ze();ar();ge();cr();ur();Qe();lr();pr();dr();jc={workflowDefinitions:ct,subjectViews:ut,jobs:N,jobSubjects:pt,jobStepExecutions:Vt,jobBatches:Rt,schedules:Pt,workflowShortcuts:dt,settings:te},Bn=Sc(jc,o=>({workflowDefinitions:{},subjectViews:{},schedules:{},workflowShortcuts:{},settings:{},jobs:{subjects:o.many.jobSubjects({from:o.jobs.id,to:o.jobSubjects.jobId}),stepExecutions:o.many.jobStepExecutions({from:o.jobs.id,to:o.jobStepExecutions.jobId}),batch:o.one.jobBatches({from:o.jobs.batchId,to:o.jobBatches.id})},jobSubjects:{job:o.one.jobs({from:o.jobSubjects.jobId,to:o.jobs.id})},jobStepExecutions:{job:o.one.jobs({from:o.jobStepExecutions.jobId,to:o.jobs.id}),parent:o.one.jobStepExecutions({from:o.jobStepExecutions.parentStepExecutionId,to:o.jobStepExecutions.id,alias:"job_step_executions_parent"}),children:o.many.jobStepExecutions({from:o.jobStepExecutions.id,to:o.jobStepExecutions.parentStepExecutionId,alias:"job_step_executions_children"})},jobBatches:{jobs:o.many.jobs({from:o.jobBatches.id,to:o.jobs.batchId})}}))});import{drizzle as _c}from"drizzle-orm/node-sqlite";import{DatabaseSync as nm}from"node:sqlite";function Ln(o){return o.exec("PRAGMA foreign_keys = ON;"),_c({client:o,relations:Bn})}var Jn=p(()=>{"use strict";$n()});function Ze(o,t,e){return o.prepare(`PRAGMA table_info(${t})`).all().some(i=>i.name===e)}function Ic(o){Ze(o,"subject_views","order")||o.exec('ALTER TABLE subject_views ADD COLUMN "order" INTEGER NOT NULL DEFAULT 0'),Ze(o,"subject_views","query_template")||o.exec("ALTER TABLE subject_views ADD COLUMN query_template TEXT"),Ze(o,"subject_views","workflow_id")||o.exec("ALTER TABLE subject_views ADD COLUMN workflow_id TEXT NOT NULL DEFAULT ''"),Ze(o,"schedules","workflow_id")&&o.exec("ALTER TABLE schedules DROP COLUMN workflow_id"),o.exec(`
11
+ `)}function be(o,t){return t==="free_text"?o:Tn(o)}function Tn(o){let t=[...o.matchAll(/```json\s*([\s\S]*?)```/gi)].map(i=>i[1].trim()),e=[...o.matchAll(/```\s*([\s\S]*?)```/g)].map(i=>i[1].trim()),r=[...t].reverse();r.length===0&&r.push(...[...e].reverse()),r.push(o.trim());for(let i of r)if(i)try{return JSON.parse(i)}catch{continue}throw new Error("No valid JSON block found in agent response")}var Va,Wa,Xa,Ka,We=p(()=>{"use strict";Tt();Va={user:"User preferences",organization:"Organization guidelines",project:"Project context"},Wa=["user","organization","project"],Xa={questionnaire:'Respond with a single fenced JSON block matching this shape exactly: {"questions":[{"id":"<string>","prompt":"<string>"}]}. No other prose outside the fence.',confirmation:'Respond with a single fenced JSON block matching this shape exactly: {"approved":<boolean>}. No other prose outside the fence.',comment_suggestions:'Respond with a single fenced JSON block matching this shape exactly: {"suggestions":[{"body":"<string>"}]}. No other prose outside the fence.',free_text:"Respond in plain text. Do not wrap the answer in a JSON object."},Ka={anthropic:"Anthropic",cursor:"Cursor"}});async function*Ga(o){let{query:t}=await import("@anthropic-ai/claude-agent-sdk"),e=o.options;yield*t({prompt:o.prompt,options:{permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,...e?.cwd?{cwd:e.cwd}:{},...e?.resume?{resume:e.resume}:{},...e?.env?{env:e.env}:{}}})}var Ha,Xe,Rn=p(()=>{"use strict";We();Tt();We();Ha=St("anthropic"),Xe=class{secrets;queryFn;constructor(t,e){this.secrets=t,this.queryFn=e}async run(t){let e=await this.requireApiKey(),r=he(t),i={permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,env:{...process.env,ANTHROPIC_API_KEY:e}};t.cwd&&(i.cwd=t.cwd),t.sessionId&&(i.resume=t.sessionId);let n=this.queryFn??Ga,s,a,u;for await(let c of n({prompt:r,options:i}))c.session_id&&(s=c.session_id),c.type==="result"&&(c.subtype==="success"&&typeof c.result=="string"?a=c.result:u=c.errors?.join("; ")||c.subtype||"Claude agent returned an error result");if(u)throw new Error(`Claude agent failed: ${u}`);if(a==null)throw new Error("Claude agent returned no result text");if(!s)throw new Error("Claude agent returned no session id");return{raw:a,parsed:be(a,t.outputFormat),sessionId:s}}async requireApiKey(){let t=await this.secrets.get(Ha);if(!t)throw Ve("anthropic");return t}}});function Qa(o,t){return{apiKey:o,model:{id:"composer-2.5"},local:{...t?{cwd:t}:{},settingSources:[]}}}async function Ya(){let{Agent:o}=await import("@cursor/sdk");return{create:t=>o.create({apiKey:t.apiKey,model:t.model,local:{...t.local?.cwd?{cwd:t.local.cwd}:{},settingSources:[]}}),resume:(t,e)=>o.resume(t,{apiKey:e.apiKey,model:e.model,local:{...e.local?.cwd?{cwd:e.local.cwd}:{},settingSources:[]}})}}var za,Ke,On=p(()=>{"use strict";We();Tt();za=St("cursor"),Ke=class{secrets;sdk;constructor(t,e){this.secrets=t,this.sdk=e}async run(t){let e=await this.requireApiKey(),r=he(t),i=this.sdk??await Ya(),n=Qa(e,t.cwd),s=t.sessionId?await i.resume(t.sessionId,n):await i.create(n);try{let u=await(await s.send(r)).wait();if(u.status!=="finished")throw new Error(u.error?.message||`Cursor agent ended with status '${u.status}'`);let c=u.result??"";return{raw:c,parsed:be(c,t.outputFormat),sessionId:s.agentId}}finally{await s[Symbol.asyncDispose]?.()}}async requireApiKey(){let t=await this.secrets.get(za);if(!t)throw Ve("cursor");return t}}});var we,ir=p(()=>{"use strict";we=Symbol("NOTIFICATION_PROVIDER")});var He,Pn=p(()=>{"use strict";He=class{async send(t){console.log("[notification]",JSON.stringify(t))}}});var ye,sr=p(()=>{"use strict";ye=Symbol("KNOWLEDGE_PROVIDER")});import{readdir as Za,readFile as tc}from"node:fs/promises";import{join as kn}from"node:path";var Ge,An=p(()=>{"use strict";Ge=class{baseDir;constructor(t){this.baseDir=t}async resolve(t,e){let r=kn(this.baseDir,t),i;try{i=await Za(r)}catch(a){if(a.code==="ENOENT")return[];throw a}let n=i.filter(a=>a.endsWith(".md")).sort(),s=[];for(let a of n){let u=kn(r,a),c=await tc(u,"utf8");s.push({tier:t,content:c,sourceRef:u})}return s}}});import{Module as oc}from"@nestjs/common";import{mkdirSync as rc}from"node:fs";import{dirname as nc,join as ic}from"node:path";import{fileURLToPath as sc}from"node:url";var ec,Nn,Zt,ar=p(()=>{"use strict";Tt();ec=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},Nn=ic(nc(sc(import.meta.url)),"../../data");rc(Nn,{recursive:!0});Zt=class{};Zt=ec([oc({providers:[{provide:ot,useFactory:()=>En({dataDir:Nn})}],exports:[ot]})],Zt)});import{index as ac,sqliteTable as cc,text as at}from"drizzle-orm/sqlite-core";var ct,ze=p(()=>{"use strict";ct=cc("workflow_definitions",{id:at("id").primaryKey(),name:at("name").notNull(),description:at("description"),appliesTo:at("applies_to",{mode:"json"}).$type().notNull(),cardinality:at("cardinality",{enum:["single","batch","aggregate"]}).notNull(),inputSchema:at("input_schema",{mode:"json"}).$type().notNull(),steps:at("steps",{mode:"json"}).$type().notNull(),notificationPolicy:at("notification_policy",{mode:"json"}).$type().notNull(),createdAt:at("created_at").notNull(),updatedAt:at("updated_at").notNull()},o=>[ac("workflow_definitions_cardinality_idx").on(o.cardinality)])});import{index as qn,integer as uc,sqliteTable as lc,text as Mt}from"drizzle-orm/sqlite-core";var ut,cr=p(()=>{"use strict";ut=lc("subject_views",{id:Mt("id").primaryKey(),name:Mt("name").notNull(),subjectType:Mt("subject_type").$type().notNull(),workflowId:Mt("workflow_id").notNull(),query:Mt("query",{mode:"json"}).$type().notNull(),description:Mt("description"),queryTemplate:Mt("query_template",{mode:"json"}).$type(),order:uc("order").notNull().default(0)},o=>[qn("subject_views_subject_type_idx").on(o.subjectType),qn("subject_views_subject_type_order_idx").on(o.subjectType,o.order)])});import{index as Cn,integer as pc,sqliteTable as dc,text as lt}from"drizzle-orm/sqlite-core";var Rt,Qe=p(()=>{"use strict";Rt=dc("job_batches",{id:lt("id").primaryKey(),workflowId:lt("workflow_id").notNull(),selection:lt("selection",{mode:"json"}).$type().notNull(),resolvedSubjects:lt("resolved_subjects",{mode:"json"}).$type().notNull(),status:lt("status",{enum:["running","completed","completed_with_issues","failed"]}).notNull(),triggeredBy:lt("triggered_by",{enum:["schedule","view_bulk","multiselect"]}).notNull(),scheduleId:lt("schedule_id"),notificationOverride:lt("notification_override",{mode:"json"}).$type(),notificationSent:pc("notification_sent",{mode:"boolean"}).notNull(),createdAt:lt("created_at").notNull(),completedAt:lt("completed_at")},o=>[Cn("job_batches_workflow_id_idx").on(o.workflowId),Cn("job_batches_schedule_id_idx").on(o.scheduleId)])});import{index as Ye,integer as fc,sqliteTable as mc,text as A}from"drizzle-orm/sqlite-core";var N,ge=p(()=>{"use strict";ze();Qe();N=mc("jobs",{id:A("id").primaryKey(),workflowId:A("workflow_id").notNull().references(()=>ct.id),status:A("status").$type().notNull(),selection:A("selection",{mode:"json"}).$type(),batchId:A("batch_id").references(()=>Rt.id),parentJobId:A("parent_job_id"),parentStepExecutionId:A("parent_step_execution_id"),fanOutIndex:fc("fan_out_index"),retryOf:A("retry_of"),context:A("context",{mode:"json"}).$type().notNull(),worktreePath:A("worktree_path"),branch:A("branch"),currentStepId:A("current_step_id"),currentStepExecutionId:A("current_step_execution_id"),createdAt:A("created_at").notNull(),updatedAt:A("updated_at").notNull(),completedAt:A("completed_at")},o=>[Ye("jobs_workflow_id_idx").on(o.workflowId),Ye("jobs_status_idx").on(o.status),Ye("jobs_batch_id_idx").on(o.batchId),Ye("jobs_parent_job_id_idx").on(o.parentJobId)])});import{index as Dn,sqliteTable as hc,text as Se}from"drizzle-orm/sqlite-core";var pt,ur=p(()=>{"use strict";ge();pt=hc("job_subjects",{id:Se("id").primaryKey(),jobId:Se("job_id").notNull().references(()=>N.id),subjectType:Se("subject_type").$type().notNull(),subjectId:Se("subject_id").notNull(),snapshot:Se("snapshot",{mode:"json"}).$type().notNull()},o=>[Dn("job_subjects_job_id_idx").on(o.jobId),Dn("job_subjects_subject_lookup_idx").on(o.subjectType,o.subjectId)])});import{index as Bn,integer as bc,sqliteTable as wc,text as rt}from"drizzle-orm/sqlite-core";var Vt,lr=p(()=>{"use strict";ge();Vt=wc("job_step_executions",{id:rt("id").primaryKey(),jobId:rt("job_id").notNull().references(()=>N.id),stepDefinitionId:rt("step_definition_id").notNull(),type:rt("type").$type().notNull(),status:rt("status").$type().notNull(),startedAt:rt("started_at"),completedAt:rt("completed_at"),output:rt("output",{mode:"json"}).$type(),error:rt("error"),childJobIds:rt("child_job_ids",{mode:"json"}).$type(),parentStepExecutionId:rt("parent_step_execution_id").references(()=>Vt.id),iterationIndex:bc("iteration_index")},o=>[Bn("job_step_executions_job_id_idx").on(o.jobId),Bn("job_step_executions_parent_idx").on(o.parentStepExecutionId)])});import{index as yc,integer as gc,sqliteTable as Sc,text as Ot}from"drizzle-orm/sqlite-core";var Pt,pr=p(()=>{"use strict";Pt=Sc("schedules",{id:Ot("id").primaryKey(),viewId:Ot("view_id").notNull(),triggerType:Ot("trigger_type",{enum:["cron"]}).notNull(),cadence:Ot("cadence").notNull(),notificationOverride:Ot("notification_override",{mode:"json"}).$type(),missedFirePolicy:Ot("missed_fire_policy",{enum:["skip","catch_up"]}).notNull(),enabled:gc("enabled",{mode:"boolean"}).notNull(),lastFiredAt:Ot("last_fired_at"),createdAt:Ot("created_at").notNull()},o=>[yc("schedules_enabled_idx").on(o.enabled)])});import{integer as jc,sqliteTable as _c,text as je}from"drizzle-orm/sqlite-core";var dt,dr=p(()=>{"use strict";dt=_c("workflow_shortcuts",{id:je("id").primaryKey(),name:je("name").notNull(),workflowId:je("workflow_id").notNull(),inputValues:je("input_values",{mode:"json"}).$type().notNull(),lastJobId:je("last_job_id"),order:jc("order").notNull().default(0)})});import{sqliteTable as Ic,text as $n}from"drizzle-orm/sqlite-core";var _e,te,fr=p(()=>{"use strict";_e="default",te=Ic("settings",{id:$n("id").primaryKey(),data:$n("data",{mode:"json"}).$type().notNull()})});import{defineRelations as xc}from"drizzle-orm";var Ec,Ln,Un=p(()=>{"use strict";ze();cr();ge();ur();lr();Qe();pr();dr();fr();Ec={workflowDefinitions:ct,subjectViews:ut,jobs:N,jobSubjects:pt,jobStepExecutions:Vt,jobBatches:Rt,schedules:Pt,workflowShortcuts:dt,settings:te},Ln=xc(Ec,o=>({workflowDefinitions:{},subjectViews:{},schedules:{},workflowShortcuts:{},settings:{},jobs:{subjects:o.many.jobSubjects({from:o.jobs.id,to:o.jobSubjects.jobId}),stepExecutions:o.many.jobStepExecutions({from:o.jobs.id,to:o.jobStepExecutions.jobId}),batch:o.one.jobBatches({from:o.jobs.batchId,to:o.jobBatches.id})},jobSubjects:{job:o.one.jobs({from:o.jobSubjects.jobId,to:o.jobs.id})},jobStepExecutions:{job:o.one.jobs({from:o.jobStepExecutions.jobId,to:o.jobs.id}),parent:o.one.jobStepExecutions({from:o.jobStepExecutions.parentStepExecutionId,to:o.jobStepExecutions.id,alias:"job_step_executions_parent"}),children:o.many.jobStepExecutions({from:o.jobStepExecutions.id,to:o.jobStepExecutions.parentStepExecutionId,alias:"job_step_executions_children"})},jobBatches:{jobs:o.many.jobs({from:o.jobBatches.id,to:o.jobs.batchId})}}))});import{drizzle as vc}from"drizzle-orm/node-sqlite";import{DatabaseSync as pm}from"node:sqlite";function Fn(o){return o.exec("PRAGMA foreign_keys = ON;"),vc({client:o,relations:Ln})}var Jn=p(()=>{"use strict";Un()});function Ze(o,t,e){return o.prepare(`PRAGMA table_info(${t})`).all().some(i=>i.name===e)}function Tc(o){Ze(o,"subject_views","order")||o.exec('ALTER TABLE subject_views ADD COLUMN "order" INTEGER NOT NULL DEFAULT 0'),Ze(o,"subject_views","query_template")||o.exec("ALTER TABLE subject_views ADD COLUMN query_template TEXT"),Ze(o,"subject_views","workflow_id")||o.exec("ALTER TABLE subject_views ADD COLUMN workflow_id TEXT NOT NULL DEFAULT ''"),Ze(o,"schedules","workflow_id")&&o.exec("ALTER TABLE schedules DROP COLUMN workflow_id"),o.exec(`
12
12
  CREATE INDEX IF NOT EXISTS subject_views_subject_type_order_idx
13
13
  ON subject_views (subject_type, "order");
14
- `)}function fr(o){o.exec(`
14
+ `)}function mr(o){o.exec(`
15
15
  PRAGMA foreign_keys = ON;
16
16
 
17
17
  CREATE TABLE IF NOT EXISTS workflow_definitions (
@@ -137,8 +137,8 @@ ${Ua[o.outputFormat]}`),t.join(`
137
137
  id TEXT PRIMARY KEY NOT NULL,
138
138
  data TEXT NOT NULL
139
139
  );
140
- `),Ic(o)}var Fn=p(()=>{"use strict"});import{Injectable as vc}from"@nestjs/common";import{mkdirSync as Tc}from"node:fs";import{dirname as Rc}from"node:path";import{fileURLToPath as Oc}from"node:url";import{DatabaseSync as Un}from"node:sqlite";var xc,Ec,W,Mn=p(()=>{"use strict";Jn();Fn();xc=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},Ec=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},W=class{sqlite;db;constructor(){let e=process.env.KNO_SQLITE_PATH??Oc(new URL("../../data/kno.db",import.meta.url));e===":memory:"?this.sqlite=new Un(":memory:"):(Tc(Rc(e),{recursive:!0}),this.sqlite=new Un(e)),this.db=Ln(this.sqlite),fr(this.sqlite)}async onModuleInit(){fr(this.sqlite)}getDb(){return this.db}getSqlite(){return this.sqlite}};W=xc([vc(),Ec("design:paramtypes",[])],W)});import{Injectable as Ac}from"@nestjs/common";import{eq as Vn}from"drizzle-orm";var Pc,kc,O,ee=p(()=>{"use strict";ze();Pc=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},kc=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},O=class{db;sqlite;constructor(t,e){this.db=t,this.sqlite=e}async create(t){let e=new Date().toISOString();return await this.db.insert(ct).values({id:t.id,name:t.name,description:t.description??null,appliesTo:t.appliesTo,cardinality:t.cardinality,inputSchema:t.inputSchema,steps:t.steps,notificationPolicy:t.notificationPolicy,createdAt:e,updatedAt:e}),await this.get(t.id)}async get(t){let e=await this.db.query.workflowDefinitions.findFirst({where:{id:t}});return e?this.toDomain(e):null}async update(t,e){let r=await this.get(t);return r?(await this.db.update(ct).set({name:e.name??r.name,description:e.description!==void 0?e.description??null:r.description??null,appliesTo:e.appliesTo??r.appliesTo,cardinality:e.cardinality??r.cardinality,inputSchema:e.inputSchema??r.inputSchema,steps:e.steps??r.steps,notificationPolicy:e.notificationPolicy??r.notificationPolicy,updatedAt:new Date().toISOString()}).where(Vn(ct.id,t)),this.get(t)):null}async list(t={}){return(t.cardinality?await this.db.query.workflowDefinitions.findMany({where:{cardinality:t.cardinality}}):await this.db.query.workflowDefinitions.findMany()).map(r=>this.toDomain(r))}async delete(t){if(!await this.get(t))return!1;try{this.sqlite?.exec("PRAGMA foreign_keys = OFF"),await this.db.delete(ct).where(Vn(ct.id,t))}finally{this.sqlite?.exec("PRAGMA foreign_keys = ON")}return!0}toDomain(t){return{id:t.id,name:t.name,...t.description!=null?{description:t.description}:{},appliesTo:t.appliesTo,cardinality:t.cardinality,inputSchema:t.inputSchema,steps:t.steps,notificationPolicy:t.notificationPolicy}}};O=Pc([Ac(),kc("design:paramtypes",[Object,Function])],O)});import{Injectable as Cc}from"@nestjs/common";import{eq as mr}from"drizzle-orm";var Nc,qc,Wn,X,to=p(()=>{"use strict";ar();Nc=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},qc=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},Wn=["ticket","pull_request","documentation"],X=class{db;constructor(t){this.db=t}async create(t){let e=await this.nextOrder(t.subjectType);return await this.db.insert(ut).values({id:t.id,name:t.name,subjectType:t.subjectType,workflowId:t.workflowId,query:t.query,description:t.description??null,queryTemplate:t.queryTemplate??null,order:e}),await this.get(t.id)}async get(t){let e=await this.db.query.subjectViews.findFirst({where:{id:t}});return e?this.toDomain(e):null}async update(t,e){let r=await this.get(t);if(!r)return null;let i=e.queryTemplate!==void 0?e.queryTemplate:e.query!==void 0?void 0:r.queryTemplate;return await this.db.update(ut).set({name:e.name??r.name,subjectType:e.subjectType??r.subjectType,workflowId:e.workflowId??r.workflowId,query:e.query??r.query,description:e.description!==void 0?e.description??null:r.description??null,queryTemplate:i??null}).where(mr(ut.id,t)),this.get(t)}async list(t={}){let e=t.subjectType?await this.db.query.subjectViews.findMany({where:{subjectType:t.subjectType}}):await this.db.query.subjectViews.findMany();return this.sortViews(e.map(r=>this.toDomain(r)))}async reorder(t){let e=[];for(let i of t){let n=await this.get(i);if(!n)return[];e.push(n)}let r=e[0].subjectType;if(!e.every(i=>i.subjectType===r))return[];for(let i=0;i<t.length;i+=1)await this.db.update(ut).set({order:i}).where(mr(ut.id,t[i]));return this.list({subjectType:r})}async delete(t){return await this.get(t)?(await this.db.delete(ut).where(mr(ut.id,t)),!0):!1}async nextOrder(t){let e=await this.db.query.subjectViews.findMany({where:{subjectType:t}});return e.length===0?0:Math.max(...e.map(r=>r.order))+1}sortViews(t){return[...t].sort((e,r)=>{let i=Wn.indexOf(e.subjectType)-Wn.indexOf(r.subjectType);return i!==0?i:e.order-r.order})}toDomain(t){return{id:t.id,name:t.name,subjectType:t.subjectType,workflowId:t.workflowId,query:t.query,order:t.order,...t.description!=null?{description:t.description}:{},...t.queryTemplate!=null?{queryTemplate:t.queryTemplate}:{}}}};X=Nc([Cc(),qc("design:paramtypes",[Object])],X)});import{Injectable as $c}from"@nestjs/common";import{and as Lc,desc as Jc,eq as Ie,inArray as Fc}from"drizzle-orm";import{randomUUID as Uc}from"node:crypto";function Mc(o){return o?o.mode==="single"?[o.subject]:o.subjects:[]}function Vc(o){if(o.length!==0)return o.length===1?{mode:"single",subject:o[0]}:{mode:"collection",subjects:o}}function Kn(o,t,e=null,r=null){let i=[];for(let n of t)if(i.push({id:n.id,jobId:o,stepDefinitionId:n.stepDefinitionId,type:n.type,status:n.status,startedAt:n.startedAt??null,completedAt:n.completedAt??null,output:n.output??null,error:n.error??null,childJobIds:n.childJobIds??null,parentStepExecutionId:e,iterationIndex:r}),n.iterations)for(let s of n.iterations)i.push(...Kn(o,s.stepExecutions,n.id,s.index));return i}function Wc(o){let t=new Map;for(let i of o){let n=i.parentStepExecutionId,s=t.get(n)??[];s.push(i),t.set(n,s)}let e=i=>{let n=t.get(i)??[];if(n.length===0)return;let s=new Map;for(let a of n){if(a.iterationIndex==null)continue;let u=s.get(a.iterationIndex)??[];u.push(a),s.set(a.iterationIndex,u)}if(s.size!==0)return[...s.entries()].sort(([a],[u])=>a-u).map(([a,u])=>{let c=u.map(f=>Xn(f,e(f.id)));return{index:a,stepExecutions:c,startedAt:Xc(c),...Hc(c)?{completedAt:Kc(c)}:{}}})};return(t.get(null)??[]).filter(i=>i.iterationIndex==null).map(i=>Xn(i,e(i.id)))}function Xn(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 Xc(o){let t=o.map(e=>e.startedAt).filter(e=>e!=null);return t.length===0?"":t.reduce((e,r)=>e<r?e:r)}function Kc(o){return o.map(e=>e.completedAt).filter(e=>e!=null).reduce((e,r)=>e>r?e:r)}function Hc(o){return o.length>0&&o.every(t=>t.completedAt!=null)}var Dc,Bc,P,oe=p(()=>{"use strict";ge();cr();ur();Dc=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},Bc=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},P=class{db;constructor(t){this.db=t}async create(t){return await this.db.insert(N).values(this.jobToRow(t)),await this.replaceSubjects(t.id,t.subjectContext),await this.replaceStepExecutions(t.id,t.stepHistory),await this.get(t.id)}async get(t){let e=await this.db.query.jobs.findFirst({where:{id:t},with:{subjects:!0,stepExecutions:!0}});return e?this.toDomain(e,e.subjects,e.stepExecutions):null}async update(t,e){let r=await this.get(t);if(!r)return null;let i={...r,...e,id:t,context:e.context??r.context,stepHistory:e.stepHistory??r.stepHistory,updatedAt:e.updatedAt??new Date().toISOString()};return await this.db.update(N).set({workflowId:i.workflowId,status:i.status,selection:i.selection??null,batchId:i.batchId??null,parentJobId:i.parentJobId??null,parentStepExecutionId:i.parentStepExecutionId??null,fanOutIndex:i.fanOutIndex??null,retryOf:i.retryOf??null,context:i.context,worktreePath:i.worktreePath??null,branch:i.branch??null,currentStepId:i.currentStepId??null,currentStepExecutionId:i.currentStepExecutionId??null,createdAt:i.createdAt,updatedAt:i.updatedAt,completedAt:i.completedAt??null}).where(Ie(N.id,t)),e.subjectContext!==void 0&&await this.replaceSubjects(t,e.subjectContext),e.stepHistory!==void 0&&await this.replaceStepExecutions(t,e.stepHistory),this.get(t)}async list(t={}){let e={};t.workflowId!==void 0&&(e.workflowId=t.workflowId),t.status!==void 0&&(e.status=t.status),t.batchId!==void 0&&(e.batchId=t.batchId),t.parentJobId!==void 0&&(e.parentJobId=t.parentJobId),t.parentStepExecutionId!==void 0&&(e.parentStepExecutionId=t.parentStepExecutionId);let i=(Object.keys(e).length>0?await this.db.query.jobs.findMany({where:e,with:{subjects:!0,stepExecutions:!0}}):await this.db.query.jobs.findMany({with:{subjects:!0,stepExecutions:!0}})).map(n=>this.toDomain(n,n.subjects,n.stepExecutions));return t.topLevelOnly?i.filter(n=>n.batchId==null&&n.parentJobId==null):i}async latestBySubject(t,e){let r={};for(let c of e)r[c]=null;if(e.length===0)return r;let i=await this.db.select({subjectId:pt.subjectId,jobId:N.id,createdAt:N.createdAt}).from(pt).innerJoin(N,Ie(pt.jobId,N.id)).where(Lc(Ie(N.workflowId,t),Fc(pt.subjectId,e))).orderBy(Jc(N.createdAt)),n=new Map;for(let c of i)n.has(c.subjectId)||n.set(c.subjectId,c.jobId);let s=[...new Set(n.values())],a=await Promise.all(s.map(c=>this.get(c))),u=new Map(a.filter(c=>c!=null).map(c=>[c.id,c]));for(let[c,f]of n)r[c]=u.get(f)??null;return r}jobToRow(t){return{id:t.id,workflowId:t.workflowId,status:t.status,selection:t.selection??null,batchId:t.batchId??null,parentJobId:t.parentJobId??null,parentStepExecutionId:t.parentStepExecutionId??null,fanOutIndex:t.fanOutIndex??null,retryOf:t.retryOf??null,context:t.context,worktreePath:t.worktreePath??null,branch:t.branch??null,currentStepId:t.currentStepId??null,currentStepExecutionId:t.currentStepExecutionId??null,createdAt:t.createdAt,updatedAt:t.updatedAt,completedAt:t.completedAt??null}}async replaceSubjects(t,e){await this.db.delete(pt).where(Ie(pt.jobId,t));let r=Mc(e);r.length!==0&&await this.db.insert(pt).values(r.map(i=>({id:Uc(),jobId:t,subjectType:i.subjectType,subjectId:i.id,snapshot:i})))}async replaceStepExecutions(t,e){await this.db.delete(Vt).where(Ie(Vt.jobId,t));let r=Kn(t,e);r.length!==0&&await this.db.insert(Vt).values(r)}toDomain(t,e,r){let i=Vc(e.map(s=>s.snapshot)),n=Wc(r);return{id:t.id,workflowId:t.workflowId,status:t.status,...i?{subjectContext:i}:{},...t.selection!=null?{selection:t.selection}:{},...t.batchId!=null?{batchId:t.batchId}:{},...t.parentJobId!=null?{parentJobId:t.parentJobId}:{},...t.parentStepExecutionId!=null?{parentStepExecutionId:t.parentStepExecutionId}:{},...t.fanOutIndex!=null?{fanOutIndex:t.fanOutIndex}:{},...t.retryOf!=null?{retryOf:t.retryOf}:{},context:t.context,...t.worktreePath!=null?{worktreePath:t.worktreePath}:{},...t.branch!=null?{branch:t.branch}:{},...t.currentStepId!=null?{currentStepId:t.currentStepId}:{},...t.currentStepExecutionId!=null?{currentStepExecutionId:t.currentStepExecutionId}:{},stepHistory:n,createdAt:t.createdAt,updatedAt:t.updatedAt,...t.completedAt!=null?{completedAt:t.completedAt}:{}}}};P=Dc([$c(),Bc("design:paramtypes",[Object])],P)});import{Injectable as Qc}from"@nestjs/common";import{eq as Yc}from"drizzle-orm";var Gc,zc,K,eo=p(()=>{"use strict";Qe();Gc=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},zc=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},K=class{db;constructor(t){this.db=t}async create(t){return await this.db.insert(Rt).values({id:t.id,workflowId:t.workflowId,selection:t.selection,resolvedSubjects:t.resolvedSubjects,status:t.status,triggeredBy:t.triggeredBy,scheduleId:t.scheduleId??null,notificationOverride:t.notificationOverride??null,notificationSent:t.notificationSent,createdAt:t.createdAt,completedAt:t.completedAt??null}),await this.get(t.id)}async get(t){let e=await this.db.query.jobBatches.findFirst({where:{id:t},with:{jobs:!0}});return e?this.toDomain(e,e.jobs.map(r=>r.id)):null}async update(t,e){let r=await this.get(t);return r?(await this.db.update(Rt).set({workflowId:e.workflowId??r.workflowId,selection:e.selection??r.selection,resolvedSubjects:e.resolvedSubjects??r.resolvedSubjects,status:e.status??r.status,triggeredBy:e.triggeredBy??r.triggeredBy,scheduleId:e.scheduleId!==void 0?e.scheduleId??null:r.scheduleId??null,notificationOverride:e.notificationOverride!==void 0?e.notificationOverride??null:r.notificationOverride??null,notificationSent:e.notificationSent??r.notificationSent,createdAt:e.createdAt??r.createdAt,completedAt:e.completedAt!==void 0?e.completedAt??null:r.completedAt??null}).where(Yc(Rt.id,t)),this.get(t)):null}async list(t={}){return(t.workflowId?await this.db.query.jobBatches.findMany({where:{workflowId:t.workflowId},with:{jobs:!0}}):await this.db.query.jobBatches.findMany({with:{jobs:!0}})).map(r=>this.toDomain(r,r.jobs.map(i=>i.id)))}toDomain(t,e){return{id:t.id,workflowId:t.workflowId,selection:t.selection,resolvedSubjects:t.resolvedSubjects,jobIds:e,status:t.status,triggeredBy:t.triggeredBy,...t.scheduleId!=null?{scheduleId:t.scheduleId}:{},...t.notificationOverride!=null?{notificationOverride:t.notificationOverride}:{},notificationSent:t.notificationSent,createdAt:t.createdAt,...t.completedAt!=null?{completedAt:t.completedAt}:{}}}};K=Gc([Qc(),zc("design:paramtypes",[Object])],K)});import{Injectable as eu}from"@nestjs/common";import{eq as Hn}from"drizzle-orm";var Zc,tu,jt,hr=p(()=>{"use strict";lr();Zc=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},tu=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},jt=class{db;constructor(t){this.db=t}async create(t){return await this.db.insert(Pt).values({id:t.id,viewId:t.viewId,triggerType:t.trigger.type,cadence:t.trigger.cadence,notificationOverride:t.notificationOverride??null,missedFirePolicy:t.missedFirePolicy,enabled:t.enabled,lastFiredAt:t.lastFiredAt??null,createdAt:t.createdAt}),await this.get(t.id)}async get(t){let e=await this.db.query.schedules.findFirst({where:{id:t}});return e?this.toDomain(e):null}async update(t,e){let r=await this.get(t);if(!r)return null;let i=e.trigger??r.trigger;return await this.db.update(Pt).set({viewId:e.viewId??r.viewId,triggerType:i.type,cadence:i.cadence,notificationOverride:e.notificationOverride!==void 0?e.notificationOverride??null:r.notificationOverride??null,missedFirePolicy:e.missedFirePolicy??r.missedFirePolicy,enabled:e.enabled??r.enabled,lastFiredAt:e.lastFiredAt!==void 0?e.lastFiredAt??null:r.lastFiredAt??null,createdAt:e.createdAt??r.createdAt}).where(Hn(Pt.id,t)),this.get(t)}async list(t={}){return(t.enabled!==void 0?await this.db.query.schedules.findMany({where:{enabled:t.enabled}}):await this.db.query.schedules.findMany()).map(r=>this.toDomain(r))}async delete(t){return await this.get(t)?(await this.db.delete(Pt).where(Hn(Pt.id,t)),!0):!1}async findDue(t){return(await this.list({enabled:!0})).filter(r=>r.lastFiredAt==null||r.lastFiredAt<t)}toDomain(t){return{id:t.id,viewId:t.viewId,trigger:{type:"cron",cadence:t.cadence},...t.notificationOverride!=null?{notificationOverride:t.notificationOverride}:{},missedFirePolicy:t.missedFirePolicy,enabled:t.enabled,...t.lastFiredAt!=null?{lastFiredAt:t.lastFiredAt}:{},createdAt:t.createdAt}}};jt=Zc([eu(),tu("design:paramtypes",[Object])],jt)});import{Injectable as nu}from"@nestjs/common";import{eq as br}from"drizzle-orm";var ou,ru,_t,wr=p(()=>{"use strict";pr();ou=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},ru=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},_t=class{db;constructor(t){this.db=t}async create(t){let e=await this.nextOrder();return await this.db.insert(dt).values({id:t.id,name:t.name,workflowId:t.workflowId,inputValues:t.inputValues,lastJobId:t.lastJobId??null,order:e}),await this.get(t.id)}async get(t){let e=await this.db.query.workflowShortcuts.findFirst({where:{id:t}});return e?this.toDomain(e):null}async update(t,e){let r=await this.get(t);return r?(await this.db.update(dt).set({name:e.name??r.name,workflowId:e.workflowId??r.workflowId,inputValues:e.inputValues??r.inputValues,lastJobId:e.lastJobId!==void 0?e.lastJobId??null:r.lastJobId??null}).where(br(dt.id,t)),this.get(t)):null}async list(){return(await this.db.query.workflowShortcuts.findMany()).map(e=>this.toDomain(e)).sort((e,r)=>e.order-r.order)}async reorder(t){let e=[];for(let r of t){let i=await this.get(r);if(!i)return[];e.push(i)}for(let r=0;r<t.length;r+=1)await this.db.update(dt).set({order:r}).where(br(dt.id,t[r]));return this.list()}async delete(t){return await this.get(t)?(await this.db.delete(dt).where(br(dt.id,t)),!0):!1}async nextOrder(){let t=await this.db.query.workflowShortcuts.findMany();return t.length===0?0:Math.max(...t.map(e=>e.order))+1}toDomain(t){return{id:t.id,name:t.name,workflowId:t.workflowId,inputValues:t.inputValues,order:t.order,...t.lastJobId!=null?{lastJobId:t.lastJobId}:{}}}};_t=ou([nu(),ru("design:paramtypes",[Object])],_t)});import{Injectable as au}from"@nestjs/common";import{eq as cu}from"drizzle-orm";function uu(o,t){let e={...o.activeProviders,...t.activeProviders},r=t.jira!==void 0?{...o.jira,...t.jira}:o.jira,i=t.bitbucket!==void 0?{...o.bitbucket,...t.bitbucket}:o.bitbucket;return yr({activeProviders:e,...r&&Object.keys(r).length>0?{jira:r}:{},...i&&Object.keys(i).length>0?{bitbucket:i}:{}})}function yr(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 Gn(o){return Object.prototype.hasOwnProperty.call(o,"activeProviders")}var iu,su,J,oo=p(()=>{"use strict";dr();iu=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},su=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 get(){let t=await this.db.query.settings.findFirst({where:{id:_e}});return yr(t?t.data:{})}async update(t){let e=uu(await this.get(),t);return await this.db.query.settings.findFirst({where:{id:_e}})?await this.db.update(te).set({data:e}).where(cu(te.id,_e)):await this.db.insert(te).values({id:_e,data:e}),e}};J=iu([au(),su("design:paramtypes",[Object])],J)});import{Module as pu}from"@nestjs/common";var lu,du,ft,xe=p(()=>{"use strict";Mn();ee();to();oe();eo();hr();wr();oo();lu=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},du=[O,X,P,K,jt,_t,J],ft=class{};ft=lu([pu({providers:[W,{provide:O,useFactory:o=>new O(o.getDb(),o.getSqlite()),inject:[W]},{provide:X,useFactory:o=>new X(o.getDb()),inject:[W]},{provide:P,useFactory:o=>new P(o.getDb()),inject:[W]},{provide:K,useFactory:o=>new K(o.getDb()),inject:[W]},{provide:jt,useFactory:o=>new jt(o.getDb()),inject:[W]},{provide:_t,useFactory:o=>new _t(o.getDb()),inject:[W]},{provide:J,useFactory:o=>new J(o.getDb()),inject:[W]}],exports:[W,...du]})],ft)});function gr(o){return o==null?"":typeof o=="string"?o:Qn(o).replace(/\n+$/,"")}function zn(o){return{version:1,type:"doc",content:o.split(`
141
- `).map(e=>({type:"paragraph",content:e.length===0?[]:[{type:"text",text:e}]}))}}function Qn(o){if(o==null||typeof o!="object")return"";let t=o;if(t.type==="text")return t.text??"";if(t.type==="hardBreak")return`
142
- `;let e=(t.content??[]).map(Qn).join("");return t.type==="paragraph"||t.type==="heading"||t.type==="blockquote"||t.type==="listItem"?`${e}
143
- `:e}var Yn=p(()=>{"use strict"});function hu(o){if(typeof o.jql=="string"&&o.jql.trim().length>0)return o.jql;let t=[];if(no(o.project)&&t.push(`project = ${io(o.project)}`),no(o.status)&&t.push(`status = ${io(o.status)}`),no(o.assignee)&&t.push(`assignee = ${io(o.assignee)}`),no(o.sprintId)){let e=o.sprintId;t.push(typeof e=="number"||/^\d+$/.test(String(e))?`sprint = ${Number(e)}`:`sprint = ${io(e)}`)}if(t.length===0)throw new Error("Jira query requires jql or at least one of project, status, assignee, sprintId");return t.join(" AND ")}function no(o){return o!=null&&o!==""}function io(o){return`"${String(o).replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Zn(o,t){let e=String(o.key??o.id??""),r=o.fields??{},i=gr(r.description);return{id:e,source:"jira",title:String(r.summary??""),...i?{description:i}:{},status:String(r.status?.name??""),...r.assignee?.displayName?{assignee:String(r.assignee.displayName)}:{},url:`${t.replace(/\/$/,"")}/browse/${e}`,raw:o}}var re,fu,mu,ro,so,Sr=p(()=>{"use strict";Yn();re="kno.jira.apiToken",fu=50,mu=10,ro=500,so=class{secrets;settings;fetchFn;constructor(t,e,r=fetch){this.secrets=t,this.settings=e,this.fetchFn=r}async get(t){let{baseUrl:e}=await this.requireConfig(),r=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(t)}`);return Zn(r,e)}async query(t){let{baseUrl:e}=await this.requireConfig(),r=hu(t),i=[],n,s=new Set;for(let a=0;a<mu&&i.length<ro;a++){let u={jql:r,maxResults:Math.min(fu,ro-i.length),fields:["summary","description","status","assignee"]};n&&(u.nextPageToken=n);let c=await this.request("POST","/rest/api/3/search/jql",{body:u}),f=Array.isArray(c.issues)?c.issues:[];for(let j of f){if(i.length>=ro)break;i.push(Zn(j,e))}let m=typeof c.nextPageToken=="string"?c.nextPageToken:void 0;if(c.isLast===!0||!m||f.length===0||m===n||s.has(m))break;s.add(m),n=m}return i}async getComments(t){let e=[],r=0,i=100,n=ro;for(;e.length<n;){let s=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(t)}/comment?startAt=${r}&maxResults=${i}`),a=Array.isArray(s.comments)?s.comments:[];for(let u of a)e.push({id:String(u.id??""),subjectId:t,body:gr(u.body),...u.author?.displayName?{author:u.author.displayName}:{},createdAt:u.created??"",raw:u});if(r+=a.length,a.length===0||typeof s.total=="number"&&r>=s.total||a.length<i)break}return e}async postComment(t,e){await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(t)}/comment`,{body:{body:zn(e)}})}async updateStatus(t,e){let r=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(t)}/transitions`),i=Array.isArray(r.transitions)?r.transitions:[],n=e.trim().toLowerCase(),s=i.find(a=>(a.to?.name??"").trim().toLowerCase()===n);if(!s?.id){let a=i.map(c=>c.to?.name).filter(c=>typeof c=="string"&&c.length>0),u=a.length>0?a.join(", "):"(none)";throw new Error(`No Jira transition to status '${e}' from the current state. Available: ${u}`)}await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(t)}/transitions`,{body:{transition:{id:s.id}}})}async requireConfig(){let t=(await this.settings.get()).jira,e=t?.baseUrl?.trim(),r=t?.email?.trim(),i=await this.secrets.get(re),n=[];if(e||n.push("settings.jira.baseUrl"),r||n.push("settings.jira.email"),i||n.push(`SecretStore '${re}'`),n.length>0)throw new Error(`Jira is not configured \u2014 missing ${n.join(", ")}. Set jira.baseUrl and jira.email via PATCH /api/settings, and store the API token with: POST /api/secrets/${re} or npm --workspace apps/engine run set-secret -- ${re} <value>`);return{baseUrl:e,email:r,token:i}}async request(t,e,r={}){let{baseUrl:i,email:n,token:s}=await this.requireConfig(),a=`${i.replace(/\/$/,"")}${e}`,u={Authorization:`Basic ${Buffer.from(`${n}:${s}`).toString("base64")}`,Accept:"application/json"};r.body!==void 0&&(u["Content-Type"]="application/json");let c=await this.fetchFn(a,{method:t,headers:u,...r.body!==void 0?{body:JSON.stringify(r.body)}:{}});if(!c.ok){let m=await c.text().catch(()=>"");throw new Error(`Jira ${t} ${e} failed (${c.status}): ${m||c.statusText}`)}if(c.status===204)return;let f=await c.text();if(f)return JSON.parse(f)}}});function ao(o){let t=o.trim(),e=t.lastIndexOf("#");if(e<=0||e===t.length-1)throw new Error(`Bitbucket pull request id must be '{repoSlug}#{prNumber}' (e.g. 'kno-engine#42'), got '${o}'`);let r=t.slice(0,e),i=t.slice(e+1);if(!/^\d+$/.test(i))throw new Error(`Bitbucket pull request id must be '{repoSlug}#{prNumber}' with a numeric PR number, got '${o}'`);return{repoSlug:r,prNumber:i}}function wu(o,t){return`${o}#${t}`}function yu(o){let t=o.repoSlug;if(typeof t!="string"||t.trim().length===0)throw new Error("Bitbucket query requires filter.repoSlug or filter.role \u2014 repo-scoped listing needs repoSlug; workspace-wide listing needs role (author|reviewer)");return t.trim()}function gu(o){if(typeof o.repoSlug=="string"&&o.repoSlug.trim().length>0||!oi(o.role))return;let t=String(o.role).trim().toLowerCase();if(t!=="author"&&t!=="reviewer")throw new Error(`Bitbucket query filter.role must be 'author' or 'reviewer', got '${String(o.role)}'`);return t}function ei(o){if(!oi(o))return;let t=String(o).trim().toUpperCase();if(t!=="OPEN"&&t!=="MERGED"&&t!=="DECLINED")throw new Error(`Bitbucket query filter.state must be OPEN, MERGED, or DECLINED, got '${String(o)}'`);return t}function Su(o){if(typeof o.q=="string"&&o.q.trim().length>0)return o.q;let t=ei(o.state);if(t)return`state="${t}"`}function ju(o){let t=o.destination?.repository?.name;if(typeof t=="string"&&t.trim().length>0)return t.trim();let e=o.destination?.repository?.full_name;if(typeof e=="string"&&e.includes("/"))return e.slice(e.lastIndexOf("/")+1);throw new Error("Bitbucket workspace pull request is missing destination.repository slug")}function _u(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 oi(o){return o!=null&&o!==""}function ti(o,t){let e=String(o.id??""),r=typeof o.description=="string"?o.description:"";return{id:wu(t,e),source:"bitbucket",title:String(o.title??""),...r?{description:r}:{},sourceBranch:String(o.source?.branch?.name??""),targetBranch:String(o.destination?.branch?.name??""),...o.author?.display_name?{author:o.author.display_name}:{},...o.links?.html?.href?{url:o.links.html.href}:{},raw:o}}function Iu(o,t){let e=o.user?.display_name??o.author?.display_name;return{id:String(o.id??""),subjectId:t,body:o.content?.raw??"",...e?{author:e}:{},createdAt:o.created_on??"",raw:o}}var ne,bu,co,jr=p(()=>{"use strict";ne="kno.bitbucket.apiToken",bu="https://api.bitbucket.org/2.0",co=class{secrets;settings;fetchFn;constructor(t,e,r=fetch){this.secrets=t,this.settings=e,this.fetchFn=r}async get(t){let{repoSlug:e,prNumber:r}=ao(t),{workspace:i}=await this.requireConfig(),n=await this.request("GET",this.prPath(i,e,r));return ti(n,e)}async query(t){let e=gu(t);if(e)return this.queryWorkspacePullRequests(e,t);let r=yu(t),{baseUrl:i,workspace:n}=await this.requireConfig(),s=Su(t),a=new URLSearchParams({pagelen:String(50)});s&&a.set("q",s);let u=`${i.replace(/\/$/,"")}/repositories/${encodeURIComponent(n)}/${encodeURIComponent(r)}/pullrequests?${a.toString()}`;return this.collectPullRequests(u,r)}async queryWorkspacePullRequests(t,e){let{baseUrl:r,workspace:i,email:n}=await this.requireConfig(),s=new URLSearchParams({pagelen:String(50)}),a=ei(e.state);a&&s.set("state",a),t==="reviewer"&&s.set("role","REVIEWER");let u=`${r.replace(/\/$/,"")}/workspaces/${encodeURIComponent(i)}/pullrequests/${encodeURIComponent(n)}?${s.toString()}`;return this.collectPullRequests(u)}async collectPullRequests(t,e){let r=[],i=new Set,n=t;for(let s=0;s<10&&r.length<500&&!(!n||i.has(n));s++){i.add(n);let a=await this.request("GET",n),u=Array.isArray(a.values)?a.values:[];for(let f of u){if(r.length>=500)break;r.push(ti(f,e??ju(f)))}let c=typeof a.next=="string"&&a.next.length>0?a.next:void 0;if(!c||u.length===0)break;n=c}return r}async getComments(t){let{repoSlug:e,prNumber:r}=ao(t),{workspace:i}=await this.requireConfig(),n=[],s=new Set,a=`${this.prPath(i,e,r)}/comments?pagelen=50`;for(let u=0;u<10&&n.length<500&&!(!a||s.has(a));u++){s.add(a);let c=await this.request("GET",a),f=Array.isArray(c.values)?c.values:[];for(let j of f)n.push(Iu(j,t));let m=typeof c.next=="string"&&c.next.length>0?c.next:void 0;if(!m||f.length===0)break;a=m}return n}async postComment(t,e){let{repoSlug:r,prNumber:i}=ao(t),{workspace:n}=await this.requireConfig();await this.request("POST",`${this.prPath(n,r,i)}/comments`,{body:{content:{raw:e}}})}async updateStatus(t,e){let{repoSlug:r,prNumber:i}=ao(t),{workspace:n}=await this.requireConfig(),s=_u(e);await this.request("POST",`${this.prPath(n,r,i)}/${s}`)}prPath(t,e,r){return`/repositories/${encodeURIComponent(t)}/${encodeURIComponent(e)}/pullrequests/${encodeURIComponent(r)}`}async requireConfig(){let t=(await this.settings.get()).bitbucket,e=(t?.baseUrl?.trim()||bu).replace(/\/$/,""),r=t?.email?.trim(),i=t?.workspace?.trim(),n=await this.secrets.get(ne),s=[];if(r||s.push("settings.bitbucket.email"),i||s.push("settings.bitbucket.workspace"),n||s.push(`SecretStore '${ne}'`),s.length>0)throw new Error(`Bitbucket is not configured \u2014 missing ${s.join(", ")}. Set bitbucket.email and bitbucket.workspace via PATCH /api/settings, and store the API token with: POST /api/secrets/${ne} or npm --workspace apps/engine run set-secret -- ${ne} <value>`);return{baseUrl:e,email:r,workspace:i,token:n}}async request(t,e,r={}){let{baseUrl:i,email:n,token:s}=await this.requireConfig(),a=e.startsWith("http://")||e.startsWith("https://")?e:`${i}${e.startsWith("/")?e:`/${e}`}`,u={Authorization:`Basic ${Buffer.from(`${n}:${s}`).toString("base64")}`,Accept:"application/json"};r.body!==void 0&&(u["Content-Type"]="application/json");let c=await this.fetchFn(a,{method:t,headers:u,...r.body!==void 0?{body:JSON.stringify(r.body)}:{}});if(!c.ok){let m=await c.text().catch(()=>"");throw new Error(`Bitbucket ${t} ${e} failed (${c.status}): ${m||c.statusText}`)}if(c.status===204)return;let f=await c.text();if(f)return JSON.parse(f)}}});import{Injectable as Tu,Logger as Ru,Inject as Ou}from"@nestjs/common";async function ri(o){let t=[];for(let e of Pu){let r=await o.get(e.secretKey);t.push({providerId:e.providerId,secretKey:e.secretKey,configured:typeof r=="string"&&r.length>0})}return t}async function ku(o,t){let e=await ri(o);for(let r of e)r.configured||t(`${r.providerId} API key not configured (looked up as '${r.secretKey}'). GET /api/providers/status lists what's missing; store a key with: POST /api/secrets/${r.secretKey} or npm --workspace apps/engine run set-secret -- ${r.secretKey} <value>`)}function ni(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 ii(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 si(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 xu,Eu,vu,_r,Pu,kt,Ir=p(()=>{"use strict";Tt();Sr();jr();xu=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},Eu=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},vu=function(o,t){return function(e,r){t(e,r,o)}},Pu=[{providerId:"anthropic",secretKey:St("anthropic")},{providerId:"cursor",secretKey:St("cursor")},{providerId:"jira",secretKey:re},{providerId:"bitbucket",secretKey:ne}];kt=_r=class{secrets;logger=new Ru(_r.name);constructor(t){this.secrets=t}async onModuleInit(){await ku(this.secrets,t=>this.logger.warn(t))}list(){return ri(this.secrets)}};kt=_r=xu([Tu(),vu(0,Ou(ot)),Eu("design:paramtypes",[Function])],kt)});var Wt,h,b,Xt,D=p(()=>{"use strict";Wt=class extends Error{constructor(t){super(t),this.name=this.constructor.name}},h=class extends Wt{httpStatus=404},b=class extends Wt{httpStatus=400},Xt=class extends Wt{httpStatus=409}});function ci(o,t){switch(o){case"my-open-prs":return{role:"author",state:"OPEN"};case"reviewing":return{role:"reviewer",state:"OPEN"};case"repo-open-prs":{let e=typeof t.repoSlug=="string"?t.repoSlug.trim():"";if(!e)throw new b("Bitbucket template 'repo-open-prs' requires params.repoSlug");return{repoSlug:e,state:"OPEN"}}default:throw new h(`Unknown Bitbucket query template: ${o}`)}}var ai,ui=p(()=>{"use strict";D();ai=[{id:"my-open-prs",label:"My open pull requests",params:[]},{id:"reviewing",label:"Pull requests I'm reviewing",params:[]},{id:"repo-open-prs",label:"Open pull requests in a repository",params:[{name:"repoSlug",label:"Repository",type:"string",required:!0}]}]});import{Injectable as Nu}from"@nestjs/common";var Au,li,At,xr=p(()=>{"use strict";D();ui();Au=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},li={bitbucket:{list:()=>ai,resolve:ci}},At=class{list(t){return li[t]?.list()??[]}resolve(t,e,r){let i=li[t];if(!i)throw new h(`No query templates for provider '${t}'`);let n=i.list().find(s=>s.id===e);if(!n)throw new h(`Unknown query template '${e}' for provider '${t}'`);for(let s of n.params){if(!s.required)continue;let a=r[s.name];if(a==null||typeof a=="string"&&a.trim()==="")throw new b(`Template '${e}' requires params.${s.name}`)}return i.resolve(e,r)}};At=Au([Nu()],At)});import{Module as Cu}from"@nestjs/common";import{fileURLToPath as Du}from"node:url";import{dirname as Bu,join as $u}from"node:path";var qu,Lu,Nt,uo=p(()=>{"use strict";Be();hn();Le();bn();Fe();wn();Zo();vn();Tn();nr();Rn();ir();Pn();sr();Tt();xe();oo();Ir();Sr();jr();xr();qu=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},Lu=$u(Bu(Du(import.meta.url)),"../../../knowledge"),Nt=class{};Nt=qu([Cu({imports:[Zt,ft],providers:[{provide:Jt,useFactory:async(o,t)=>ii(await t.get())==="jira"?new so(o,t):new $e([]),inject:[ot,J]},{provide:Ft,useFactory:async(o,t)=>si(await t.get())==="bitbucket"?new co(o,t):new Je([]),inject:[ot,J]},{provide:Ut,useFactory:()=>new Ue([])},{provide:me,useFactory:async(o,t)=>ni(await t.get())==="cursor"?new Ke(o):new Xe(o),inject:[ot,J]},{provide:we,useClass:He},{provide:ye,useFactory:()=>new Ge(Lu)},kt,At],exports:[Jt,Ft,Ut,me,we,ye,kt,At]})],Nt)});import{Module as Fu}from"@nestjs/common";var Ju,lo,pi=p(()=>{"use strict";Ju=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},lo=class{};lo=Ju([Fu({})],lo)});import{Injectable as Mu}from"@nestjs/common";var Uu,nt,po=p(()=>{"use strict";Uu=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},nt=class{listeners=new Set;emit(t){for(let e of this.listeners)e(t)}subscribe(t){return this.listeners.add(t),()=>this.listeners.delete(t)}};nt=Uu([Mu()],nt)});import{Global as Wu,Module as Xu}from"@nestjs/common";var Vu,qt,fo=p(()=>{"use strict";po();Vu=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},qt=class{};qt=Vu([Wu(),Xu({providers:[nt],exports:[nt]})],qt)});import{Injectable as Gu}from"@nestjs/common";import{execFile as zu}from"node:child_process";import{mkdirSync as di}from"node:fs";import{join as Er}from"node:path";import{promisify as Qu}from"node:util";function fi(o){return o==null?"":typeof o=="string"?o:o.toString("utf8")}function mi(o){return Er(o,"worktrees")}var Ku,Hu,Yu,It,vr=p(()=>{"use strict";Ku=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},Hu=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},Yu=Qu(zu),It=class{worktreesRoot;constructor(t){this.worktreesRoot=t,di(this.worktreesRoot,{recursive:!0})}async createWorktree(t,e){let r=e.worktreePath??Er(this.worktreesRoot,t);return di(Er(r,".."),{recursive:!0}),await this.git(e.repoPath,["worktree","add","-b",e.branchName,r,e.baseBranch]),{worktreePath:r,branch:e.branchName}}async checkout(t,e){await this.git(t,["checkout",e.branch])}async createBranch(t,e){e.baseBranch?await this.git(t,["checkout","-b",e.branchName,e.baseBranch]):await this.git(t,["checkout","-b",e.branchName])}async commit(t,e){return e.addAll!==!1&&await this.git(t,["add","-A"]),await this.git(t,["commit","-m",e.message]),{sha:(await this.git(t,["rev-parse","HEAD"])).stdout.trim()}}async push(t,e={}){let r=e.remote??"origin";e.branch?await this.git(t,["push",r,e.branch]):await this.git(t,["push",r,"HEAD"])}async git(t,e){try{let r=await Yu("git",e,{cwd:t,encoding:"utf8",windowsHide:!0});return{stdout:r.stdout??"",stderr:r.stderr??""}}catch(r){let i=r,n=fi(i.stderr),s=fi(i.stdout),a=n||s||i.message||"unknown git error";throw new Error(`git ${e.join(" ")} failed (cwd=${t}, code=${String(i.code??"?")}): ${a}`)}}};It=Ku([Gu(),Hu("design:paramtypes",[String])],It)});import{Module as tl}from"@nestjs/common";import{mkdirSync as el}from"node:fs";import{dirname as ol,join as rl}from"node:path";import{fileURLToPath as nl}from"node:url";var Zu,hi,mo,bi=p(()=>{"use strict";vr();Zu=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},hi=rl(ol(nl(import.meta.url)),"../../data");el(hi,{recursive:!0});mo=class{};mo=Zu([tl({providers:[{provide:It,useFactory:()=>new It(mi(hi))}],exports:[It]})],mo)});function ho(o,t){return o.replace(/\{\{\s*([^}]+?)\s*\}\}/g,(e,r)=>{let i=il(t,r.trim());return i==null?"":typeof i=="string"?i:JSON.stringify(i)})}function il(o,t){let e=t.split(".").filter(Boolean),r=o;for(let i of e){if(r==null||typeof r!="object")return;r=r[i]}return r}function Ee(o,t){return typeof o=="string"?ho(o,t):Array.isArray(o)?o.map(e=>Ee(e,t)):o&&typeof o=="object"?Object.fromEntries(Object.entries(o).map(([e,r])=>[e,Ee(r,t)])):o}var wi=p(()=>{"use strict"});function yi(o,t){switch(o){case"questionnaire":return Tr(t);case"confirmation":return sl(t);case"conversation":return al(t);default:return o}}function Tr(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 sl(o){if(typeof o=="string"&&o.trim())return[o.trim()];if(!o||typeof o!="object")return[];let t=o;for(let e of["prompt","message","summary","question"]){let r=t[e];if(typeof r=="string"&&r.trim())return[r.trim()]}return"approved"in t&&!("questions"in t)?[]:Tr(o)}function al(o){if(typeof o=="string"&&o.trim())return[o.trim()];if(!o||typeof o!="object")return[];let t=o;for(let e of["prompt","message","text"]){let r=t[e];if(typeof r=="string"&&r.trim())return[r.trim()]}return"suggestions"in t?[]:"questions"in t?Tr(o):[]}var gi=p(()=>{"use strict"});function ie(o,t){for(let e of o){if(e.id===t)return e;if(e.iterations)for(let r of e.iterations){let i=ie(r.stepExecutions,t);if(i)return i}}}function ve(o,t,e,r){for(let i=0;i<o.length;i++){let n=o[i];if(n.id===t)return{execution:n,siblings:o,index:i,parentLoopExecutionId:e,iterationIndex:r};if(n.iterations)for(let s of n.iterations){let a=ve(s.stepExecutions,t,n.id,s.index);if(a)return a}}}function F(o,t,e){return o.map(r=>r.id===t?e(r):r.iterations?{...r,iterations:r.iterations.map(i=>({...i,stepExecutions:F(i.stepExecutions,t,e)}))}:r)}function Rr(o,t,e,r){return e==null?[...o,t]:o.map(i=>{if(i.id===e){let n=[...i.iterations??[]],s=n.find(a=>a.index===r);if(s){let a={...s,stepExecutions:[...s.stepExecutions,t]},u=n.findIndex(c=>c.index===r);n[u]=a}else{let a={index:r,stepExecutions:[t],startedAt:t.startedAt??new Date().toISOString()};n.push(a),n.sort((u,c)=>u.index-c.index)}return{...i,iterations:n}}return i.iterations?{...i,iterations:i.iterations.map(n=>({...n,stepExecutions:Rr(n.stepExecutions,t,e,r)}))}:i})}function Te(o,t){for(let e of o){if(e.id===t)return e;if(e.type==="loop"){let r=Te(e.steps,t);if(r)return r}}}function Si(o,t,e){return F(o,t,r=>{let i=(r.iterations??[]).map(n=>{if(n.index!==e)return n;let s=n.stepExecutions.every(a=>a.completedAt)?n.stepExecutions.map(a=>a.completedAt).reduce((a,u)=>a>u?a:u):void 0;return{...n,...s?{completedAt:s}:{}}});return{...r,iterations:i}})}var ji=p(()=>{"use strict"});import{z as H}from"zod";function _i(o,t){let e=dl[o].safeParse(t);if(!e.success){let r=e.error.issues.map(i=>`${i.path.length?i.path.join("."):"(root)"}: ${i.message}`).join("; ");throw new Error(`Agent output failed validation for format '${o}': ${r}`)}return e.data}var cl,ul,ll,pl,dl,Ii=p(()=>{"use strict";cl=H.object({questions:H.array(H.object({id:H.string(),prompt:H.string()}))}),ul=H.object({approved:H.boolean()}),ll=H.object({suggestions:H.array(H.object({body:H.string()}))}),pl=H.string(),dl={questionnaire:cl,confirmation:ul,comment_suggestions:ll,free_text:pl}});function xi(o){return o==="completed"||o==="failed"||o==="cancelled"}function Or(o,t){let e=new Map;for(let i of o){let n=t(i);if(n==null)continue;let s=e.get(n)??[];s.push(i),e.set(n,s)}if(e.size===0)return null;let r=[];for(let i of e.values()){let n=new Set(i.map(a=>a.retryOf).filter(a=>a!=null)),s=i.find(a=>!n.has(a.id));if(!s)return null;r.push(s)}return{activeJobs:r,allTerminal:r.every(i=>xi(i.status)),groupCount:e.size}}function Ei(o){let t=o.every(r=>r.status==="completed"),e=o.every(r=>r.status==="failed"||r.status==="cancelled");return t?"completed":e?"failed":"completed_with_issues"}var vi=p(()=>{"use strict"});async function bo(o,t,e){let r=await t.get(o);if(!r)throw new h(`SubjectView not found: ${o}`);if(r.subjectType==="ticket")return(await e.tickets.query(r.query)).map(n=>({subjectType:"ticket",...n}));if(r.subjectType==="pull_request")return(await e.repo.query(r.query)).map(n=>({subjectType:"pull_request",...n}));if(r.subjectType==="documentation")return(await e.documentation.query(r.query)).map(n=>({subjectType:"documentation",...n}));throw new b(`Unsupported subjectType on view: ${r.subjectType}`)}var Pr=p(()=>{"use strict";D()});import{Inject as z,Injectable as hl}from"@nestjs/common";import{randomUUID as kr}from"node:crypto";import{exec as bl}from"node:child_process";import{promisify as wl}from"node:util";function Ti(o,t){let e=t[o.stepId];if(e==null||typeof e!="object")return o.type==="field_empty";let r=e[o.field];return o.type==="field_empty"?r==null?!0:typeof r=="string"||Array.isArray(r)?r.length===0:!1:r===o.value}function Sl(o,t){let e=i=>{let n=[];for(let s of i)n.push(s),s.type==="loop"&&n.push(...e(s.steps));return n},r=i=>{let n=i.findIndex(s=>s.id===t);if(n>=0){for(let s=n-1;s>=0;s--)if(i[s].type==="agent")return i[s].id;return}for(let s of i)if(s.type==="loop"){let a=r(s.steps);if(a!==void 0||s.steps.some(u=>u.id===t))return a}};return r(o.steps)}function wo(o){let t={...o.context};return o.subjectContext?.mode==="single"&&(t.subject=o.subjectContext.subject),o.worktreePath&&(t.worktreePath=o.worktreePath),o.branch&&(t.branch=o.branch),t}function yo(o){if(!o.worktreePath)throw new Error(`Job ${o.id} has no worktreePath; run create_worktree first`);return o.worktreePath}function mt(o,t){let e=o[t];if(typeof e!="string"||e.length===0)throw new Error(`Missing required string param '${t}'`);return e}function jl(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 Ri(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 fl,ml,G,yl,gl,it,go=p(()=>{"use strict";ee();oe();eo();to();po();Zo();Be();Le();Fe();nr();ir();vr();D();wi();gi();ji();Ii();vi();Pr();fl=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},ml=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},G=function(o,t){return function(e,r){t(e,r,o)}},yl=wl(bl),gl=["user","organization","project"],it=class{workflows;jobs;batches;views;events;tickets;repo;documentation;agent;notifications;knowledge;git;childTerminalLocks=new Set;batchTerminalLocks=new Set;constructor(t,e,r,i,n,s,a,u,c,f,m,j){this.workflows=t,this.jobs=e,this.batches=r,this.views=i,this.events=n,this.tickets=s,this.repo=a,this.documentation=u,this.agent=c,this.notifications=f,this.knowledge=m,this.git=j,this.events.subscribe(g=>{let R=g;(R.type==="job_completed"||R.type==="job_failed")&&this.onChildTerminal(R.jobId)})}async start(t){let e=await this.createJob(t);return this.emit({type:"job_started",jobId:e.id,timestamp:new Date().toISOString()}),this.runJob(e.id)}async launch(t){let e=await this.requireWorkflow(t.workflowId);if(e.cardinality==="single")throw new b("launch() does not support cardinality 'single'; use start() with a subjectId");if(e.cardinality!=="batch"&&e.cardinality!=="aggregate")throw new b(`Unsupported cardinality: ${e.cardinality}`);Ri(e.inputSchema,t.inputValues);let r=await this.resolveSelection(t.selection);if(e.cardinality==="aggregate"){let a=await this.createJob({workflowId:e.id,subjectContext:{mode:"collection",subjects:r},selection:t.selection,inputValues:t.inputValues});return this.emit({type:"job_started",jobId:a.id,timestamp:new Date().toISOString()}),this.runJob(a.id)}let i=new Date().toISOString(),n=await this.batches.create({id:kr(),workflowId:e.id,selection:t.selection,resolvedSubjects:r,status:"running",triggeredBy:t.triggeredBy,...t.notificationOverride?{notificationOverride:t.notificationOverride}:{},notificationSent:!1,createdAt:i}),s=[];for(let a=0;a<r.length;a++){let u=r[a],c=await this.createJob({workflowId:e.id,subjectContext:{mode:"single",subject:u},selection:t.selection,batchId:n.id,fanOutIndex:a,inputValues:t.inputValues});s.push(c)}for(let a of s)this.emit({type:"job_started",jobId:a.id,timestamp:new Date().toISOString()}),await this.runJob(a.id);return await this.batches.get(n.id)}async createJob(t){let e=await this.workflows.get(t.workflowId);if(!e)throw new h(`Workflow not found: ${t.workflowId}`);if(!t.subjectContext&&e.cardinality!=="single")throw new b(`Workflow Runner only supports cardinality 'single' at start() without an explicit subjectContext (got '${e.cardinality}')`);Ri(e.inputSchema,t.inputValues);let r=t.subjectContext??await this.resolveSubjectContext(e,t.subjectId),i=new Date().toISOString();return this.jobs.create({id:kr(),workflowId:e.id,status:"pending",...r?{subjectContext:r}:{},...t.selection?{selection:t.selection}:{},...t.batchId?{batchId:t.batchId}:{},...t.parentJobId?{parentJobId:t.parentJobId}:{},...t.parentStepExecutionId?{parentStepExecutionId:t.parentStepExecutionId}:{},...t.fanOutIndex!=null?{fanOutIndex:t.fanOutIndex}:{},...t.retryOf?{retryOf:t.retryOf}:{},context:{...t.inputValues},stepHistory:[],createdAt:i,updatedAt:i})}async runJob(t){let e=await this.jobs.get(t);if(!e)throw new h(`Job not found: ${t}`);let r=await this.requireWorkflow(e.workflowId);e.status==="pending"&&(e=await this.persistJob({...e,status:"planning",updatedAt:new Date().toISOString()}));let i=await this.executeStepSequence(e,r,r.steps,void 0,void 0,0);return i.outcome==="paused"||i.outcome==="failed"?i.job:this.completeJob(i.job,r)}async resume(t,e){let r=await this.jobs.get(t);if(!r)throw new h(`Job not found: ${t}`);if(r.status!=="waiting_for_human")throw new Xt(`Job ${t} is not waiting for human input (status: ${r.status})`);let i=await this.requireWorkflow(r.workflowId),n=r.currentStepExecutionId;if(!n)throw new Error(`Job ${t} is waiting_for_human but has no currentStepExecutionId`);let s=ie(r.stepHistory,n);if(!s)throw new Error(`Paused execution ${n} not found on job ${t}`);if(s.type==="loop")return this.resumeAskHuman(r,i,s,e);if(s.type!=="interaction")throw new Error(`Paused execution ${n} has type '${s.type}'; expected interaction or loop`);let a=new Date().toISOString(),u=F(r.stepHistory,n,R=>({...R,status:"completed",completedAt:a,output:e})),c=e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{response:e};r=await this.persistJob({...r,status:"planning",context:{...r.context,[s.stepDefinitionId]:e},stepHistory:u,currentStepId:void 0,currentStepExecutionId:void 0,updatedAt:a}),this.emit({type:"human_answered",jobId:r.id,answers:c,timestamp:a});let f=ve(r.stepHistory,n);if(!f)throw new Error(`Could not locate frame for execution ${n}`);let m=this.sequenceForFrameOnJob(r,i,f),j=f.index+1,g=await this.executeStepSequence(r,i,m,f.parentLoopExecutionId,f.iterationIndex,j);return g.outcome==="paused"||g.outcome==="failed"?g.job:f.parentLoopExecutionId!=null&&f.iterationIndex!=null?this.continueLoopAfterBody(g.job,i,f.parentLoopExecutionId,f.iterationIndex):this.completeJob(g.job,i)}async retryFailedJob(t){let e=await this.jobs.get(t);if(!e)throw new h(`Job not found: ${t}`);if(e.status!=="failed")throw new Xt(`Job ${t} is not failed (status: ${e.status})`);let r=e.parentJobId!=null&&e.parentStepExecutionId!=null&&e.fanOutIndex!=null,i=e.batchId!=null&&e.fanOutIndex!=null;if(!r&&!i)throw new b(`Job ${t} is not a retryable sub_workflow child or batch member`);if(r){let a=await this.jobs.get(e.parentJobId);if(!a)throw new h(`Parent job not found: ${e.parentJobId}`);let u=await this.createJob({workflowId:e.workflowId,subjectContext:e.subjectContext,inputValues:{},parentJobId:e.parentJobId,parentStepExecutionId:e.parentStepExecutionId,fanOutIndex:e.fanOutIndex,retryOf:e.id}),c=F(a.stepHistory,e.parentStepExecutionId,f=>({...f,status:"waiting_for_children",error:void 0,completedAt:void 0,childJobIds:[...f.childJobIds??[],u.id]}));return a=await this.persistJob({...a,status:"waiting_for_children",stepHistory:c,completedAt:void 0,updatedAt:new Date().toISOString()}),this.emit({type:"job_started",jobId:u.id,timestamp:new Date().toISOString()}),this.emit({type:"job_retried",jobId:u.id,retryOf:e.id,timestamp:new Date().toISOString()}),this.runJob(u.id),u}let n=await this.batches.get(e.batchId);if(!n)throw new h(`JobBatch not found: ${e.batchId}`);n.status!=="running"&&await this.batches.update(n.id,{status:"running",completedAt:null,notificationSent:!1});let s=await this.createJob({workflowId:e.workflowId,subjectContext:e.subjectContext,selection:e.selection,batchId:e.batchId,fanOutIndex:e.fanOutIndex,inputValues:{},retryOf:e.id});return this.emit({type:"job_started",jobId:s.id,timestamp:new Date().toISOString()}),this.emit({type:"job_retried",jobId:s.id,retryOf:e.id,timestamp:new Date().toISOString()}),this.runJob(s.id),s}async executeStepSequence(t,e,r,i,n,s){let a=t;for(let u=s;u<r.length;u++){let c=r[u],f=new Date().toISOString(),m={id:kr(),stepDefinitionId:c.id,type:c.type,status:"running",startedAt:f},j=Rr(a.stepHistory,m,i,n);a=await this.persistJob({...a,status:a.status==="pending"?"planning":a.status,currentStepId:c.id,currentStepExecutionId:m.id,stepHistory:j,updatedAt:f}),this.emit({type:"step_started",jobId:a.id,stepDefinitionId:c.id,timestamp:f});try{let g=await this.dispatchStep(a,e,c,m.id,i,n);if(a=g.job,g.outcome==="paused"||g.outcome==="failed")return g}catch(g){return{outcome:"failed",job:await this.failJob(a,e,m.id,c.id,g)}}}return i!=null&&n!=null&&(a=await this.persistJob({...a,stepHistory:Si(a.stepHistory,i,n),updatedAt:new Date().toISOString()})),{outcome:"completed",job:a}}async dispatchStep(t,e,r,i,n,s){switch(r.type){case"agent":return{outcome:"completed",job:await this.executeAgentStep(t,r,i)};case"interaction":return{outcome:"paused",job:await this.pauseForInteraction(t,e,r,i)};case"git":return{outcome:"completed",job:await this.executeGitStep(t,r,i)};case"provider_action":return{outcome:"completed",job:await this.executeProviderActionStep(t,r,i)};case"shell":return{outcome:"completed",job:await this.executeShellStep(t,r,i)};case"loop":return this.runLoopStep(t,e,r,i,n,s);case"sub_workflow":return this.runSubWorkflowStep(t,r,i);default:{let a=r;throw new b(`Step type '${a.type}' not yet supported by the Workflow Runner`)}}}async runLoopStep(t,e,r,i,n,s,a=0,u=r.maxIterations){let c=t,f=a;for(;;){if(f>=u)switch(r.onMaxIterations.action){case"fail":return c=await this.failExecution(c,e,i,r.id,`Loop '${r.id}' exceeded maxIterations (${u})`),{outcome:"failed",job:c};case"continue":return c=await this.finishExecution(c,i,r.id,{iterations:f,exitedOnMaxIterations:!0}),{outcome:"completed",job:c};case"ask_human":{let j={maxIterationsCheckpoint:!0,nextIteration:f,effectiveMaxIterations:u},g=new Date().toISOString(),R=F(c.stepHistory,i,k=>({...k,status:"pending",output:j}));return c=await this.persistJob({...c,status:"waiting_for_human",currentStepId:r.id,currentStepExecutionId:i,stepHistory:R,updatedAt:g}),this.emit({type:"waiting_for_human",jobId:c.id,stepDefinitionId:r.id,interaction:"confirmation",data:j,questions:[`Loop '${r.id}' reached maxIterations (${u}). Extend, continue, or cancel?`],timestamp:g}),e.notificationPolicy.triggers.includes("on_needs_input")&&await this.notifications.send({title:`Input needed: ${e.name}`,body:`Job ${c.id} hit max iterations on loop '${r.id}'`,jobId:c.id}),{outcome:"paused",job:c}}default:{let j=r.onMaxIterations;throw new Error(`Unknown onMaxIterations action: ${JSON.stringify(j)}`)}}let m=await this.executeStepSequence(c,e,r.steps,i,f,0);if(c=m.job,m.outcome==="paused")return m;if(m.outcome==="failed")return c=await this.failExecution(c,e,i,r.id,"Loop body failed"),{outcome:"failed",job:c};if(Ti(r.until,c.context))return c=await this.finishExecution(c,i,r.id,{iterations:f+1}),{outcome:"completed",job:c};f+=1}}async resumeAskHuman(t,e,r,i){let n=i,s=r.output;if(!s?.maxIterationsCheckpoint)throw new Error(`Loop execution ${r.id} is not at an ask_human checkpoint`);let a=Te(e.steps,r.stepDefinitionId);if(!a||a.type!=="loop")throw new Error(`Loop step definition '${r.stepDefinitionId}' not found`);let u=ve(t.stepHistory,r.id),c=new Date().toISOString();if(n.action==="cancel")return await this.failExecution({...t,status:"planning",currentStepId:void 0,currentStepExecutionId:void 0,updatedAt:c},e,r.id,a.id,"Loop cancelled by human at maxIterations checkpoint");if(n.action==="continue"){let R=await this.persistJob({...t,status:"planning",currentStepId:void 0,currentStepExecutionId:void 0,stepHistory:F(t.stepHistory,r.id,k=>({...k,status:"completed",completedAt:c,output:{iterations:s.nextIteration,exitedOnMaxIterations:!0,humanAction:"continue"}})),updatedAt:c});return this.emit({type:"human_answered",jobId:R.id,answers:n,timestamp:c}),this.emit({type:"step_completed",jobId:R.id,stepDefinitionId:a.id,timestamp:c}),u?.parentLoopExecutionId!=null&&u.iterationIndex!=null?this.continueLoopAfterBody(R,e,u.parentLoopExecutionId,u.iterationIndex):this.continueTopLevelAfter(R,e,a.id)}let f=typeof n.additionalIterations=="number"?n.additionalIterations:0,m=s.effectiveMaxIterations+f,j=await this.persistJob({...t,status:"planning",currentStepId:void 0,currentStepExecutionId:void 0,stepHistory:F(t.stepHistory,r.id,R=>({...R,status:"running",output:void 0})),updatedAt:c});this.emit({type:"human_answered",jobId:j.id,answers:n,timestamp:c});let g=await this.runLoopStep(j,e,a,r.id,u?.parentLoopExecutionId,u?.iterationIndex,s.nextIteration,m);return g.outcome==="paused"||g.outcome==="failed"?g.job:u?.parentLoopExecutionId!=null&&u.iterationIndex!=null?this.continueLoopAfterBody(g.job,e,u.parentLoopExecutionId,u.iterationIndex):this.continueTopLevelAfter(g.job,e,a.id)}async continueLoopAfterBody(t,e,r,i){let n=ie(t.stepHistory,r);if(!n)throw new Error(`Loop execution ${r} not found`);let s=Te(e.steps,n.stepDefinitionId);if(!s||s.type!=="loop")throw new Error(`Loop step '${n.stepDefinitionId}' not found`);let a=ve(t.stepHistory,r),u=n.output?.effectiveMaxIterations??s.maxIterations,c=t;if(Ti(s.until,c.context))c=await this.finishExecution(c,r,s.id,{iterations:i+1});else{let f=i+1,m=await this.runLoopStep(c,e,s,r,a?.parentLoopExecutionId,a?.iterationIndex,f,u);if(m.outcome==="paused"||m.outcome==="failed")return m.job;c=m.job}return a?.parentLoopExecutionId!=null&&a.iterationIndex!=null?this.continueLoopAfterBody(c,e,a.parentLoopExecutionId,a.iterationIndex):this.continueTopLevelAfter(c,e,s.id)}async continueTopLevelAfter(t,e,r){let i=e.steps.findIndex(s=>s.id===r),n=await this.executeStepSequence(t,e,e.steps,void 0,void 0,i+1);return n.outcome==="paused"||n.outcome==="failed"?n.job:this.completeJob(n.job,e)}sequenceForFrameOnJob(t,e,r){if(r.parentLoopExecutionId==null)return e.steps;let i=ie(t.stepHistory,r.parentLoopExecutionId);if(!i)throw new Error(`Parent loop execution ${r.parentLoopExecutionId} not found`);let n=Te(e.steps,i.stepDefinitionId);if(!n||n.type!=="loop")throw new Error(`Parent loop step '${i.stepDefinitionId}' not found`);return n.steps}async runSubWorkflowStep(t,e,r){if(!t.subjectContext||t.subjectContext.mode!=="collection")throw new b(`sub_workflow steps require subjectContext.mode === 'collection' (job ${t.id})`);let i=t.subjectContext.subjects,n=[];for(let f=0;f<i.length;f++){let m=i[f],j=await this.createJob({workflowId:e.workflowId,subjectContext:{mode:"single",subject:m},inputValues:{},parentJobId:t.id,parentStepExecutionId:r,fanOutIndex:f});n.push(j)}let s=n.map(f=>f.id),a=new Date().toISOString(),u=F(t.stepHistory,r,f=>({...f,status:"waiting_for_children",childJobIds:s})),c=await this.persistJob({...t,status:"waiting_for_children",currentStepId:e.id,currentStepExecutionId:r,stepHistory:u,updatedAt:a});for(let f of n)this.emit({type:"job_started",jobId:f.id,timestamp:a}),this.runJob(f.id);return{outcome:"paused",job:c}}async onChildTerminal(t){let e=await this.jobs.get(t);if(!e?.parentJobId||!e.parentStepExecutionId)return;let r=`${e.parentJobId}:${e.parentStepExecutionId}`;if(!this.childTerminalLocks.has(r)){this.childTerminalLocks.add(r);try{let i=(await this.jobs.list({parentJobId:e.parentJobId,parentStepExecutionId:e.parentStepExecutionId})).filter(k=>k.parentStepExecutionId===e.parentStepExecutionId),n=Or(i,k=>k.fanOutIndex);if(!n?.allTerminal)return;let{activeJobs:s}=n,a=await this.jobs.get(e.parentJobId);if(!a||a.status!=="waiting_for_children"&&a.status!=="failed")return;let u=await this.requireWorkflow(a.workflowId),c=e.parentStepExecutionId,f=ie(a.stepHistory,c);if(!f||f.type!=="sub_workflow")return;if(s.some(k=>k.status==="failed")){await this.failExecution(a,u,c,f.stepDefinitionId,"One or more child jobs failed");return}let j=s.slice().sort((k,Sa)=>(k.fanOutIndex??0)-(Sa.fanOutIndex??0)).map(k=>({fanOutIndex:k.fanOutIndex,jobId:k.id,output:k.context})),g=new Date().toISOString();a=await this.persistJob({...a,status:"planning",context:{...a.context,[f.stepDefinitionId]:j},currentStepId:void 0,currentStepExecutionId:void 0,stepHistory:F(a.stepHistory,c,k=>({...k,status:"completed",completedAt:g,output:j})),completedAt:void 0,updatedAt:g}),this.emit({type:"step_completed",jobId:a.id,stepDefinitionId:f.stepDefinitionId,timestamp:g});let R=await this.continueTopLevelAfter(a,u,f.stepDefinitionId)}finally{this.childTerminalLocks.delete(r)}}}async onBatchMemberTerminal(t){let e=await this.jobs.get(t);if(!e?.batchId)return;let r=e.batchId;if(!this.batchTerminalLocks.has(r)){this.batchTerminalLocks.add(r);try{let i=await this.batches.get(e.batchId);if(!i||i.status!=="running")return;let n=await this.jobs.list({batchId:i.id}),s=Or(n,m=>m.fanOutIndex);if(!s||s.groupCount!==i.resolvedSubjects.length||!s.allTerminal)return;let{activeJobs:a}=s,u=Ei(a),c=new Date().toISOString(),f=await this.batches.update(i.id,{status:u,completedAt:c});if(!f)return;if(this.emit({type:"batch_completed",batchId:f.id,summary:a.map(m=>({jobId:m.id,status:m.status})),timestamp:c}),!f.notificationSent){let m=await this.requireWorkflow(f.workflowId),j=f.notificationOverride??m.notificationPolicy,g=u==="completed"?"on_complete":"on_fail";j.triggers.includes(g)&&await this.notifications.send({title:`Batch ${u}: ${m.name}`,body:`JobBatch ${f.id} finished with status '${u}' (${a.length} members)`,batchId:f.id}),await this.batches.update(f.id,{notificationSent:!0})}}finally{this.batchTerminalLocks.delete(r)}}}async resolveSelection(t){if(t.mode==="view")return bo(t.viewId,this.views,{tickets:this.tickets,repo:this.repo,documentation:this.documentation});let e=[];for(let r of t.subjectIds)if(t.subjectType==="ticket"){let i=await this.tickets.get(r);e.push({subjectType:"ticket",...i})}else if(t.subjectType==="pull_request"){let i=await this.repo.get(r);e.push({subjectType:"pull_request",...i})}else if(t.subjectType==="documentation"){let i=await this.documentation.get(r);e.push({subjectType:"documentation",...i})}else throw new b(`Unsupported subjectType: ${t.subjectType}`);return e}async executeAgentStep(t,e,r){let i=e.knowledgeScope?.length?e.knowledgeScope:gl,n=await this.resolveKnowledge(i),s=wo(t),a=ho(e.objective,s),u=await this.agent.run({objective:a,outputFormat:e.outputFormat,knowledge:n,context:{...s,stepId:e.id},...t.worktreePath?{cwd:t.worktreePath}:{}}),c=_i(e.outputFormat,u.parsed);return this.finishExecution(t,r,e.id,c)}async executeGitStep(t,e,r){let i=Ee(e.params,wo(t));switch(e.operation){case"create_worktree":{let n=await this.git.createWorktree(t.id,{repoPath:mt(i,"repoPath"),baseBranch:mt(i,"baseBranch"),branchName:mt(i,"branchName"),...typeof i.worktreePath=="string"?{worktreePath:i.worktreePath}:{}});return this.finishExecution(t,r,e.id,n,{worktreePath:n.worktreePath,branch:n.branch})}case"create_branch":{let n=yo(t),s=mt(i,"branchName");return await this.git.createBranch(n,{branchName:s,...typeof i.baseBranch=="string"?{baseBranch:i.baseBranch}:{}}),this.finishExecution(t,r,e.id,{branch:s},{branch:s})}case"checkout":{let n=yo(t),s=mt(i,"branch");return await this.git.checkout(n,{branch:s}),this.finishExecution(t,r,e.id,{branch:s},{branch:s})}case"commit":{let n=yo(t),s=await this.git.commit(n,{message:mt(i,"message"),addAll:i.addAll!==!1});return this.finishExecution(t,r,e.id,s)}case"push":{let n=yo(t);return await this.git.push(n,{...typeof i.remote=="string"?{remote:i.remote}:{},...typeof i.branch=="string"?{branch:i.branch}:{}}),this.finishExecution(t,r,e.id,{remote:typeof i.remote=="string"?i.remote:"origin",branch:typeof i.branch=="string"?i.branch:t.branch})}default:{let n=e.operation;throw new Error(`Unknown git operation: ${n}`)}}}async executeProviderActionStep(t,e,r){if(!t.subjectContext||t.subjectContext.mode!=="single")throw new b(`provider_action steps require subjectContext.mode === 'single' (job ${t.id})`);let i=t.subjectContext.subject,n=i.id,s=Ee(e.params??{},wo(t))??{},a;if(i.subjectType==="documentation")switch(e.action){case"get_subject":a=await this.documentation.get(n);break;case"get_content":a=await this.documentation.getContent(n);break;case"get_comments":a=await this.documentation.getComments(n);break;case"post_comment":await this.documentation.postComment(n,mt(s,"body")),a={posted:!0};break;case"update_status":throw new Error(`Provider action '${e.action}' is not valid for subject type 'documentation'`);default:{let u=e.action;throw new Error(`Unknown provider action: ${u}`)}}else{let u=i.subjectType==="ticket"?this.tickets:i.subjectType==="pull_request"?this.repo:null;if(!u)throw new Error(`Unsupported subjectType for provider_action: ${i.subjectType}`);switch(e.action){case"get_subject":a=await u.get(n);break;case"get_comments":a=await u.getComments(n);break;case"post_comment":await u.postComment(n,mt(s,"body")),a={posted:!0};break;case"update_status":await u.updateStatus(n,mt(s,"status")),a={status:mt(s,"status")};break;case"get_content":throw new Error(`Provider action 'get_content' is not valid for subject type '${i.subjectType}'`);default:{let c=e.action;throw new Error(`Unknown provider action: ${c}`)}}}return this.finishExecution(t,r,e.id,a)}async executeShellStep(t,e,r){let i=ho(e.command,wo(t)),n=t.worktreePath??process.cwd();try{let s=await yl(i,{cwd:n,windowsHide:!0});return this.finishExecution(t,r,e.id,{exitCode:0,stdout:String(s.stdout??""),stderr:String(s.stderr??"")})}catch(s){let a=s,u=a.stderr??"",c=a.stdout??"",f=typeof a.code=="number"?a.code:Number.parseInt(String(a.code??"1"),10)||1;throw new Error(`shell command failed (exit ${f}, cwd=${n}): ${u||c||a.message||i}`)}}async pauseForInteraction(t,e,r,i){let n=new Date().toISOString(),s=Sl(e,r.id),a=s!=null?t.context[s]:void 0,u=F(t.stepHistory,i,j=>({...j,status:"pending"})),c=await this.persistJob({...t,status:"waiting_for_human",currentStepId:r.id,currentStepExecutionId:i,stepHistory:u,updatedAt:n}),f=yi(r.interaction,a);return this.emit({type:"waiting_for_human",jobId:c.id,stepDefinitionId:r.id,interaction:r.interaction,data:a,questions:f,timestamp:n}),e.notificationPolicy.triggers.includes("on_needs_input")&&r.notify!==!1&&await this.notifications.send({title:`Input needed: ${e.name}`,body:`Job ${c.id} is waiting for human input on step '${r.id}'`,jobId:c.id}),c}async finishExecution(t,e,r,i,n={}){let s=new Date().toISOString(),a=F(t.stepHistory,e,c=>({...c,status:"completed",completedAt:s,output:i})),u=await this.persistJob({...t,...n,context:{...t.context,[r]:i},stepHistory:a,updatedAt:s});return this.emit({type:"step_completed",jobId:u.id,stepDefinitionId:r,timestamp:s}),u}async failExecution(t,e,r,i,n){return this.failJob(t,e,r,i,new Error(n))}async completeJob(t,e){let r=new Date().toISOString(),i=await this.persistJob({...t,status:"completed",currentStepId:void 0,currentStepExecutionId:void 0,completedAt:r,updatedAt:r});return this.emit({type:"job_completed",jobId:i.id,timestamp:r}),await this.onBatchMemberTerminal(i.id),!i.batchId&&e.notificationPolicy.triggers.includes("on_complete")&&await this.notifications.send({title:`Job completed: ${e.name}`,body:`Job ${i.id} completed successfully`,jobId:i.id}),i}async failJob(t,e,r,i,n){let s=n instanceof Error?n.message:String(n),a=new Date().toISOString(),u=F(t.stepHistory,r,f=>({...f,status:"failed",completedAt:a,error:s})),c=await this.persistJob({...t,status:"failed",stepHistory:u,completedAt:a,updatedAt:a});return this.emit({type:"step_failed",jobId:c.id,stepDefinitionId:i,error:s,timestamp:a}),this.emit({type:"job_failed",jobId:c.id,error:s,timestamp:a}),await this.onBatchMemberTerminal(c.id),!c.batchId&&e.notificationPolicy.triggers.includes("on_fail")&&await this.notifications.send({title:`Job failed: ${e.name}`,body:`Job ${c.id} failed on step '${i}': ${s}`,jobId:c.id}),c}async resolveSubjectContext(t,e){if(t.appliesTo==="none")return;let r=jl(t.appliesTo);if(!e)throw new Error(`Workflow '${t.id}' applies to '${r}' but no subjectId was provided`);if(r==="ticket")return{mode:"single",subject:{subjectType:"ticket",...await this.tickets.get(e)}};if(r==="pull_request")return{mode:"single",subject:{subjectType:"pull_request",...await this.repo.get(e)}};if(r==="documentation")return{mode:"single",subject:{subjectType:"documentation",...await this.documentation.get(e)}};throw new Error(`Unsupported subjectType for workflow subject resolution: ${r}`)}async resolveKnowledge(t){let e=[];for(let r of t)e.push(...await this.knowledge.resolve(r));return e}async requireWorkflow(t){let e=await this.workflows.get(t);if(!e)throw new h(`Workflow not found: ${t}`);return e}async persistJob(t){let e=await this.jobs.update(t.id,{status:t.status,context:t.context,currentStepId:t.currentStepId,currentStepExecutionId:t.currentStepExecutionId,stepHistory:t.stepHistory,worktreePath:t.worktreePath,branch:t.branch,updatedAt:t.updatedAt,completedAt:t.completedAt});if(!e)throw new Error(`Failed to persist job ${t.id}`);return e}emit(t){this.events.emit(t)}};it=fl([hl(),G(0,z(O)),G(1,z(P)),G(2,z(K)),G(3,z(X)),G(4,z(nt)),G(5,z(Jt)),G(6,z(Ft)),G(7,z(Ut)),G(8,z(me)),G(9,z(we)),G(10,z(ye)),G(11,z(It)),ml("design:paramtypes",[O,P,K,X,nt,Object,Object,Object,Object,Object,Object,It])],it)});import{Module as Il}from"@nestjs/common";var _l,se,Ar=p(()=>{"use strict";xe();uo();fo();bi();go();_l=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},se=class{};se=_l([Il({imports:[ft,Nt,qt,mo],providers:[it],exports:[it]})],se)});import{Catch as El}from"@nestjs/common";var xl,So,Oi=p(()=>{"use strict";D();xl=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},So=class{catch(t,e){e.switchToHttp().getResponse().status(t.httpStatus).json({error:t.message})}};So=xl([El(Wt)],So)});import{z as _}from"zod";var vl,Pi,Nr,jo,ki,qr=p(()=>{"use strict";vl=_.object({name:_.string().min(1),label:_.string().min(1),type:_.enum(["string","select"]),options:_.array(_.string()).optional(),required:_.boolean()}),Pi=_.object({id:_.string().min(1),label:_.string().min(1),params:_.array(vl)}),Nr=_.object({templateId:_.string().min(1),params:_.record(_.string(),_.unknown())}),jo=_.object({params:_.record(_.string(),_.unknown())}),ki=_.object({query:_.record(_.string(),_.unknown())})});import{z as U}from"zod";var ht,_o,Io,xo,Eo,Cr=p(()=>{"use strict";qr();ht=U.enum(["ticket","pull_request","documentation"]),_o=U.object({id:U.string().min(1),name:U.string().min(1),subjectType:ht,workflowId:U.string().min(1),query:U.record(U.string(),U.unknown()),description:U.string().optional(),queryTemplate:Nr.optional(),order:U.number().int().nonnegative()}),Io=_o.omit({order:!0}),xo=_o.partial().omit({id:!0,order:!0}).extend({queryTemplate:Nr.nullable().optional()}),Eo=U.object({viewIds:U.array(U.string().min(1)).min(1)})});var Ai=p(()=>{"use strict";Cr()});var Ni=p(()=>{"use strict";qr()});function Tl(o){let t=o.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"");return t.length>0?t:"step"}function qi(o,t){let e=Tl(o);if(!t.has(e))return e;let r=2;for(;t.has(`${e}-${r}`);)r+=1;return`${e}-${r}`}function Ci(o,t){for(let e of o)e.id&&t.push(e.id),e.type==="loop"&&Array.isArray(e.steps)&&Ci(e.steps,t)}function Di(o){let t=[];Ci(o,t);let e=new Map;for(let r of t)e.set(r,(e.get(r)??0)+1);return[...e.entries()].filter(([,r])=>r>1).map(([r])=>r)}function Bi(o){let t=new Set,e=r=>{for(let i of r)i.id&&t.add(i.id),i.type==="loop"&&Array.isArray(i.steps)&&e(i.steps)};return e(o),t}var Dr=p(()=>{"use strict"});import{z as d}from"zod";var Rl,Re,Ol,Ct,$i,Li,Ji,Fi,Ui,Mi,Vi,Wi,Pl,Xi,Ki,Oe,kl,Al,Nl,ql,Cl,Dl,Bl,Hi,ae,Gi=p(()=>{"use strict";Cr();Dr();Rl=d.enum(["on_fail","on_complete","on_needs_input"]),Re=d.object({triggers:d.array(Rl),messageTemplate:d.string().optional()}),Ol=d.object({name:d.string().min(1),label:d.string().min(1),type:d.enum(["string","number","boolean","select"]),options:d.array(d.string()).optional(),required:d.boolean(),defaultValue:d.unknown().optional()}),Ct=d.string().min(1),$i=d.object({type:d.literal("agent"),id:d.string().min(1),name:Ct,objective:d.string().min(1),knowledgeScope:d.array(d.enum(["user","organization","project"])).optional(),outputFormat:d.enum(["questionnaire","confirmation","comment_suggestions","free_text"])}),Li=d.object({type:d.literal("interaction"),id:d.string().min(1),name:Ct,interaction:d.union([d.literal("questionnaire"),d.literal("confirmation"),d.literal("conversation")]),notify:d.boolean().optional()}),Ji=d.object({type:d.literal("shell"),id:d.string().min(1),name:Ct,command:d.string().min(1)}),Fi=d.object({type:d.literal("git"),id:d.string().min(1),name:Ct,operation:d.enum(["create_worktree","checkout","create_branch","commit","push"]),params:d.record(d.string(),d.unknown())}),Ui=d.object({type:d.literal("provider_action"),id:d.string().min(1),name:Ct,action:d.enum(["get_subject","get_comments","post_comment","update_status","get_content"]),params:d.record(d.string(),d.unknown()).optional()}),Mi=d.object({type:d.literal("sub_workflow"),id:d.string().min(1),name:Ct,workflowId:d.string().min(1),forEach:d.literal("selection")}),Vi=d.discriminatedUnion("type",[d.object({type:d.literal("field_empty"),stepId:d.string().min(1),field:d.string().min(1)}),d.object({type:d.literal("field_equals"),stepId:d.string().min(1),field:d.string().min(1),value:d.unknown()})]),Wi=d.discriminatedUnion("action",[d.object({action:d.literal("fail")}),d.object({action:d.literal("continue")}),d.object({action:d.literal("ask_human")})]),Pl=d.object({type:d.literal("loop"),id:d.string().min(1),name:Ct,steps:d.array(d.lazy(()=>Xi)),until:Vi,maxIterations:d.number().int().nonnegative(),onMaxIterations:Wi}),Xi=d.lazy(()=>d.discriminatedUnion("type",[Fi,Ui,Ji,$i,Li,Mi,Pl])),Ki=d.object({id:d.string().min(1),name:d.string().min(1),description:d.string().optional(),appliesTo:d.union([ht,d.array(ht),d.literal("none")]),cardinality:d.enum(["single","batch","aggregate"]),inputSchema:d.array(Ol),steps:d.array(Xi),notificationPolicy:Re}),Oe=Ki.superRefine((o,t)=>{let e=Di(o.steps);e.length!==0&&t.addIssue({code:"custom",path:["steps"],message:`Duplicate step id(s): ${e.join(", ")}`})}),kl=$i.extend({id:d.string().min(1).optional()}),Al=Li.extend({id:d.string().min(1).optional()}),Nl=Ji.extend({id:d.string().min(1).optional()}),ql=Fi.extend({id:d.string().min(1).optional()}),Cl=Ui.extend({id:d.string().min(1).optional()}),Dl=Mi.extend({id:d.string().min(1).optional()}),Bl=d.object({type:d.literal("loop"),id:d.string().min(1).optional(),name:Ct,steps:d.array(d.lazy(()=>Hi)),until:Vi,maxIterations:d.number().int().nonnegative(),onMaxIterations:Wi}),Hi=d.lazy(()=>d.discriminatedUnion("type",[ql,Cl,Nl,kl,Al,Dl,Bl])),ae=Ki.omit({id:!0,steps:!0}).extend({id:d.string().min(1).optional(),steps:d.array(Hi)})});function $l(o){return o==="none"?[]:Array.isArray(o)?o:[o]}function zi(o,t){return $l(o).includes(t)}var Qi=p(()=>{"use strict"});var Yi=p(()=>{"use strict";Gi();Dr();Qi()});var Zi=p(()=>{"use strict"});var ts=p(()=>{"use strict";Zi()});var es=p(()=>{"use strict"});var os=p(()=>{"use strict";es()});var rs=p(()=>{"use strict"});var ns=p(()=>{"use strict";rs()});import{z as $}from"zod";var ce,is=p(()=>{"use strict";ce=$.object({id:$.string().min(1),viewId:$.string().min(1),trigger:$.object({type:$.literal("cron"),cadence:$.string().min(1)}),notificationOverride:$.object({triggers:$.array($.enum(["on_fail","on_complete","on_needs_input"])),messageTemplate:$.string().optional()}).optional(),missedFirePolicy:$.enum(["skip","catch_up"]),enabled:$.boolean(),lastFiredAt:$.string().optional(),createdAt:$.string()})});var ss=p(()=>{"use strict";is()});import{z as Q}from"zod";var vo,To,Ro,Oo,as=p(()=>{"use strict";vo=Q.object({id:Q.string().min(1),name:Q.string().min(1),workflowId:Q.string().min(1),inputValues:Q.record(Q.string(),Q.unknown()),lastJobId:Q.string().min(1).optional(),order:Q.number().int().nonnegative()}),To=vo.omit({order:!0}),Ro=vo.partial().omit({id:!0,order:!0}),Oo=Q.object({shortcutIds:Q.array(Q.string().min(1)).min(1)})});var cs=p(()=>{"use strict";as()});import{z as Y}from"zod";var us,ls,ps,ds,Br,Po,fs=p(()=>{"use strict";us=Y.string().min(1).refine(o=>{try{let t=new URL(o);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}},{message:"Must be an http(s) URL"}).optional(),ls=Y.object({ticket:Y.enum(["jira","manual"]).optional(),repo:Y.enum(["bitbucket","manual"]).optional(),agent:Y.enum(["claude","cursor"]).optional()}),ps=Y.object({baseUrl:us,email:Y.string().min(1).optional()}),ds=Y.object({baseUrl:us,email:Y.string().min(1).optional(),workspace:Y.string().min(1).optional()}),Br=Y.object({activeProviders:ls.optional(),jira:ps.optional(),bitbucket:ds.optional()}),Po=Y.object({activeProviders:ls.optional(),jira:ps.partial().optional(),bitbucket:ds.partial().optional()})});var ms=p(()=>{"use strict";fs()});var hs=p(()=>{"use strict"});var bs=p(()=>{"use strict";hs()});var Z=p(()=>{"use strict";Ai();Ni();Yi();ts();os();ns();ss();cs();ms();bs()});var S,bt=p(()=>{"use strict";D();S=class{schema;constructor(t){this.schema=t}transform(t){let e=this.schema.safeParse(t);if(!e.success){let r=e.error.issues.map(i=>`${i.path.join(".")||"(root)"}: ${i.message}`).join("; ");throw new b(`Validation failed: ${r}`)}return e.data}}});import{randomUUID as Ll}from"node:crypto";function Jl(){return Ll()}function $r(o){let t=o.id??Jl(),e=Bi(o.steps),r=ws(o.steps,e);return{...o,id:t,steps:r}}function ws(o,t){return o.map(e=>{let r=e.id;return r||(r=qi(e.name,t),t.add(r)),e.type==="loop"?{...e,id:r,steps:ws(e.steps,t)}:{...e,id:r}})}var ys=p(()=>{"use strict";Z()});import{Body as Ss,Controller as Fl,Delete as Ul,Get as js,HttpCode as Ml,Inject as gs,Param as Lr,Patch as Vl,Post as Wl,Query as Xl}from"@nestjs/common";var ue,q,Dt,Kl,xt,_s=p(()=>{"use strict";Z();ee();oe();D();bt();ys();ue=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},q=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},Dt=function(o,t){return function(e,r){t(e,r,o)}},Kl=new Set(["completed","failed","cancelled"]),xt=class{workflows;jobs;constructor(t,e){this.workflows=t,this.jobs=e}async list(t){if(t!=null&&t!==""&&t!=="single"&&t!=="batch"&&t!=="aggregate")throw new b(`Invalid cardinality filter: ${t}`);return this.workflows.list(t?{cardinality:t}:{})}async get(t){let e=await this.workflows.get(t);if(!e)throw new h(`Workflow not found: ${t}`);return e}async create(t){let e=$r(t),r=Oe.safeParse(e);if(!r.success){let i=r.error.issues.map(n=>`${n.path.join(".")||"(root)"}: ${n.message}`).join("; ");throw new b(`Validation failed: ${i}`)}return this.workflows.create(r.data)}async update(t,e){let r=$r({...e,id:t}),i=Oe.safeParse(r);if(!i.success){let u=i.error.issues.map(c=>`${c.path.join(".")||"(root)"}: ${c.message}`).join("; ");throw new b(`Validation failed: ${u}`)}let{id:n,...s}=i.data,a=await this.workflows.update(t,s);if(!a)throw new h(`Workflow not found: ${t}`);return a}async remove(t){if(!await this.workflows.get(t))throw new h(`Workflow not found: ${t}`);let i=(await this.jobs.list({workflowId:t})).filter(s=>!Kl.has(s.status));if(i.length>0){let s=i.length===1?"Job":"Jobs";throw new Xt(`Cannot delete workflow ${t}: ${i.length} non-terminal ${s} still reference it`)}if(!await this.workflows.delete(t))throw new h(`Workflow not found: ${t}`)}};ue([js(),Dt(0,Xl("cardinality")),q("design:type",Function),q("design:paramtypes",[String]),q("design:returntype",Promise)],xt.prototype,"list",null);ue([js(":id"),Dt(0,Lr("id")),q("design:type",Function),q("design:paramtypes",[String]),q("design:returntype",Promise)],xt.prototype,"get",null);ue([Wl(),Dt(0,Ss(new S(ae))),q("design:type",Function),q("design:paramtypes",[Object]),q("design:returntype",Promise)],xt.prototype,"create",null);ue([Vl(":id"),Dt(0,Lr("id")),Dt(1,Ss(new S(ae))),q("design:type",Function),q("design:paramtypes",[String,Object]),q("design:returntype",Promise)],xt.prototype,"update",null);ue([Ul(":id"),Ml(204),Dt(0,Lr("id")),q("design:type",Function),q("design:paramtypes",[String]),q("design:returntype",Promise)],xt.prototype,"remove",null);xt=ue([Fl("workflows"),Dt(0,gs(O)),Dt(1,gs(P)),q("design:paramtypes",[O,P])],xt)});function Is(o,t,e){if(!o)throw new h(`Workflow not found: ${t}`);if(o.appliesTo==="none")throw new b(`Cannot bind a View to workflow '${t}' because appliesTo is 'none'`);if(!zi(o.appliesTo,e))throw new b(`subjectType '${e}' is not included in workflow '${t}' appliesTo`);return o}function xs(o,t){if(!o)throw new h(`Workflow not found: ${t}`);if(o.appliesTo!=="none")throw new b(`WorkflowShortcut requires appliesTo 'none', got '${String(o.appliesTo)}'`);if(o.cardinality!=="single")throw new b(`WorkflowShortcut requires cardinality 'single', got '${o.cardinality}'`);return o}var Jr=p(()=>{"use strict";Z();D()});import{Body as Fr,Controller as Hl,Delete as Gl,Get as Ur,HttpCode as zl,Inject as Pe,Param as ko,Patch as Es,Post as Ql,Query as Yl}from"@nestjs/common";var Bt,I,M,st,vs=p(()=>{"use strict";Z();to();ee();D();bt();Jr();Be();Le();Fe();Pr();Bt=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},I=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},M=function(o,t){return function(e,r){t(e,r,o)}},st=class{views;workflows;tickets;repo;documentation;constructor(t,e,r,i,n){this.views=t,this.workflows=e,this.tickets=r,this.repo=i,this.documentation=n}async list(t){if(t!=null&&t!==""){let e=ht.safeParse(t);if(!e.success)throw new b(`Invalid subjectType filter: ${t}`);return this.views.list({subjectType:e.data})}return this.views.list({})}async reorder(t){let e=[];for(let n of t.viewIds){let s=await this.views.get(n);if(!s)throw new b(`Unknown view id in reorder: ${n}`);e.push(s)}if(new Set(e.map(n=>n.subjectType)).size!==1)throw new b("All viewIds in a reorder request must share the same subjectType");return await this.views.reorder(t.viewIds)}async listSubjects(t){return bo(t,this.views,{tickets:this.tickets,repo:this.repo,documentation:this.documentation})}async get(t){let e=await this.views.get(t);if(!e)throw new h(`SubjectView not found: ${t}`);return e}async create(t){return await this.assertBinding(t.workflowId,t.subjectType),this.views.create(t)}async update(t,e){let r=await this.views.get(t);if(!r)throw new h(`SubjectView not found: ${t}`);await this.assertBinding(e.workflowId??r.workflowId,e.subjectType??r.subjectType);let i=await this.views.update(t,e);if(!i)throw new h(`SubjectView not found: ${t}`);return i}async remove(t){if(!await this.views.delete(t))throw new h(`SubjectView not found: ${t}`)}async assertBinding(t,e){let r=await this.workflows.get(t);Is(r,t,e)}};Bt([Ur(),M(0,Yl("subjectType")),I("design:type",Function),I("design:paramtypes",[String]),I("design:returntype",Promise)],st.prototype,"list",null);Bt([Es("reorder"),M(0,Fr(new S(Eo))),I("design:type",Function),I("design:paramtypes",[Object]),I("design:returntype",Promise)],st.prototype,"reorder",null);Bt([Ur(":id/subjects"),M(0,ko("id")),I("design:type",Function),I("design:paramtypes",[String]),I("design:returntype",Promise)],st.prototype,"listSubjects",null);Bt([Ur(":id"),M(0,ko("id")),I("design:type",Function),I("design:paramtypes",[String]),I("design:returntype",Promise)],st.prototype,"get",null);Bt([Ql(),M(0,Fr(new S(Io))),I("design:type",Function),I("design:paramtypes",[Object]),I("design:returntype",Promise)],st.prototype,"create",null);Bt([Es(":id"),M(0,ko("id")),M(1,Fr(new S(xo))),I("design:type",Function),I("design:paramtypes",[String,Object]),I("design:returntype",Promise)],st.prototype,"update",null);Bt([Gl(":id"),zl(204),M(0,ko("id")),I("design:type",Function),I("design:paramtypes",[String]),I("design:returntype",Promise)],st.prototype,"remove",null);st=Bt([Hl("views"),M(0,Pe(X)),M(1,Pe(O)),M(2,Pe(Jt)),M(3,Pe(Ft)),M(4,Pe(Ut)),I("design:paramtypes",[X,O,Object,Object,Object])],st)});import{Body as Mr,Controller as Zl,Delete as tp,Get as Rs,HttpCode as ep,Inject as Ts,Param as Vr,Patch as Os,Post as op}from"@nestjs/common";var Kt,E,$t,wt,Ps=p(()=>{"use strict";Z();wr();ee();D();bt();Jr();Kt=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},E=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},$t=function(o,t){return function(e,r){t(e,r,o)}},wt=class{shortcuts;workflows;constructor(t,e){this.shortcuts=t,this.workflows=e}async list(){return this.shortcuts.list()}async reorder(t){for(let e of t.shortcutIds)if(!await this.shortcuts.get(e))throw new b(`Unknown shortcut id in reorder: ${e}`);return this.shortcuts.reorder(t.shortcutIds)}async get(t){let e=await this.shortcuts.get(t);if(!e)throw new h(`WorkflowShortcut not found: ${t}`);return e}async create(t){return await this.assertBinding(t.workflowId),this.shortcuts.create(t)}async update(t,e){let r=await this.shortcuts.get(t);if(!r)throw new h(`WorkflowShortcut not found: ${t}`);await this.assertBinding(e.workflowId??r.workflowId);let i=await this.shortcuts.update(t,e);if(!i)throw new h(`WorkflowShortcut not found: ${t}`);return i}async remove(t){if(!await this.shortcuts.delete(t))throw new h(`WorkflowShortcut not found: ${t}`)}async assertBinding(t){let e=await this.workflows.get(t);xs(e,t)}};Kt([Rs(),E("design:type",Function),E("design:paramtypes",[]),E("design:returntype",Promise)],wt.prototype,"list",null);Kt([Os("reorder"),$t(0,Mr(new S(Oo))),E("design:type",Function),E("design:paramtypes",[Object]),E("design:returntype",Promise)],wt.prototype,"reorder",null);Kt([Rs(":id"),$t(0,Vr("id")),E("design:type",Function),E("design:paramtypes",[String]),E("design:returntype",Promise)],wt.prototype,"get",null);Kt([op(),$t(0,Mr(new S(To))),E("design:type",Function),E("design:paramtypes",[Object]),E("design:returntype",Promise)],wt.prototype,"create",null);Kt([Os(":id"),$t(0,Vr("id")),$t(1,Mr(new S(Ro))),E("design:type",Function),E("design:paramtypes",[String,Object]),E("design:returntype",Promise)],wt.prototype,"update",null);Kt([tp(":id"),ep(204),$t(0,Vr("id")),E("design:type",Function),E("design:paramtypes",[String]),E("design:returntype",Promise)],wt.prototype,"remove",null);wt=Kt([Zl("workflow-shortcuts"),$t(0,Ts(_t)),$t(1,Ts(O)),E("design:paramtypes",[_t,O])],wt)});function Ao(o,t,e=50){let r=o!=null&&o!==""?Number(o):e,i=t!=null&&t!==""?Number(t):0;return!Number.isFinite(r)||r<1?{limit:e,offset:Math.max(0,i||0)}:!Number.isFinite(i)||i<0?{limit:r,offset:0}:{limit:Math.floor(r),offset:Math.floor(i)}}function No(o,t,e){return o.slice(e,e+t)}var Wr=p(()=>{"use strict"});import{z as tt}from"zod";var qo,Co,Do,Xr=p(()=>{"use strict";qo=tt.object({workflowId:tt.string().min(1),subjectId:tt.string().min(1).optional(),inputValues:tt.record(tt.string(),tt.unknown())}),Co=tt.object({response:tt.unknown()}),Do=tt.object({workflowId:tt.string().min(1),subjectIds:tt.array(tt.string().min(1))})});import{Body as Kr,Controller as rp,Get as As,HttpCode as np,Inject as ks,Param as Hr,Post as Bo,Query as Ht}from"@nestjs/common";import"zod";var Gt,v,B,ip,yt,Ns=p(()=>{"use strict";go();oe();D();bt();Wr();Xr();Gt=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},v=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},B=function(o,t){return function(e,r){t(e,r,o)}},ip=["pending","planning","waiting_for_human","waiting_for_children","implementing","testing","completed","failed","cancelled"],yt=class{jobs;runner;constructor(t,e){this.jobs=t,this.runner=e}async list(t,e,r,i,n,s,a){if(e!=null&&e!==""&&!ip.includes(e))throw new b(`Invalid status filter: ${e}`);if(n!=null&&n!==""&&n!=="true"&&n!=="false")throw new b(`Invalid topLevelOnly filter: ${n}`);let{limit:u,offset:c}=Ao(s,a),f=await this.jobs.list({...t?{workflowId:t}:{},...e?{status:e}:{},...r?{batchId:r}:{},...i?{parentJobId:i}:{},...n==="true"?{topLevelOnly:!0}:{}});return No(f,u,c)}async latestBySubject(t){return this.jobs.latestBySubject(t.workflowId,t.subjectIds)}async get(t){let e=await this.jobs.get(t);if(!e)throw new h(`Job not found: ${t}`);return e}async create(t){return this.runner.start({workflowId:t.workflowId,...t.subjectId?{subjectId:t.subjectId}:{},inputValues:t.inputValues})}async resume(t,e){return this.runner.resume(t,e.response)}async retry(t){return this.runner.retryFailedJob(t)}};Gt([As(),B(0,Ht("workflowId")),B(1,Ht("status")),B(2,Ht("batchId")),B(3,Ht("parentJobId")),B(4,Ht("topLevelOnly")),B(5,Ht("limit")),B(6,Ht("offset")),v("design:type",Function),v("design:paramtypes",[String,String,String,String,String,String,String]),v("design:returntype",Promise)],yt.prototype,"list",null);Gt([Bo("latest-by-subject"),np(200),B(0,Kr(new S(Do))),v("design:type",Function),v("design:paramtypes",[Object]),v("design:returntype",Promise)],yt.prototype,"latestBySubject",null);Gt([As(":id"),B(0,Hr("id")),v("design:type",Function),v("design:paramtypes",[String]),v("design:returntype",Promise)],yt.prototype,"get",null);Gt([Bo(),B(0,Kr(new S(qo))),v("design:type",Function),v("design:paramtypes",[Object]),v("design:returntype",Promise)],yt.prototype,"create",null);Gt([Bo(":id/resume"),B(0,Hr("id")),B(1,Kr(new S(Co))),v("design:type",Function),v("design:paramtypes",[String,Object]),v("design:returntype",Promise)],yt.prototype,"resume",null);Gt([Bo(":id/retry"),B(0,Hr("id")),v("design:type",Function),v("design:paramtypes",[String]),v("design:returntype",Promise)],yt.prototype,"retry",null);yt=Gt([rp("jobs"),B(0,ks(P)),B(1,ks(it)),v("design:paramtypes",[P,it])],yt)});import{z as L}from"zod";var $o,Lo,Gr=p(()=>{"use strict";Z();$o=L.discriminatedUnion("mode",[L.object({mode:L.literal("view"),viewId:L.string().min(1)}),L.object({mode:L.literal("manual"),subjectType:ht,subjectIds:L.array(L.string().min(1))})]),Lo=L.object({workflowId:L.string().min(1),selection:$o,triggeredBy:L.enum(["schedule","view_bulk","multiselect"]),notificationOverride:Re.optional(),inputValues:L.record(L.string(),L.unknown())})});import{Body as sp,Controller as ap,Get as Yr,Inject as zr,Param as qs,Post as cp,Query as Qr}from"@nestjs/common";import"zod";var ke,V,Et,Lt,Cs=p(()=>{"use strict";go();eo();oe();D();bt();Wr();Gr();ke=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},V=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},Et=function(o,t){return function(e,r){t(e,r,o)}},Lt=class{batches;jobs;runner;constructor(t,e,r){this.batches=t,this.jobs=e,this.runner=r}async list(t,e,r){let{limit:i,offset:n}=Ao(e,r),s=await this.batches.list(t?{workflowId:t}:{});return No(s,i,n)}async get(t){let e=await this.batches.get(t);if(!e)throw new h(`JobBatch not found: ${t}`);return e}async listJobs(t){if(!await this.batches.get(t))throw new h(`JobBatch not found: ${t}`);return this.jobs.list({batchId:t})}async launch(t){let e=await this.runner.launch({workflowId:t.workflowId,selection:t.selection,triggeredBy:t.triggeredBy,...t.notificationOverride?{notificationOverride:t.notificationOverride}:{},inputValues:t.inputValues});return"resolvedSubjects"in e&&"jobIds"in e?{kind:"batch",batch:e}:{kind:"job",job:e}}};ke([Yr(),Et(0,Qr("workflowId")),Et(1,Qr("limit")),Et(2,Qr("offset")),V("design:type",Function),V("design:paramtypes",[String,String,String]),V("design:returntype",Promise)],Lt.prototype,"list",null);ke([Yr(":id"),Et(0,qs("id")),V("design:type",Function),V("design:paramtypes",[String]),V("design:returntype",Promise)],Lt.prototype,"get",null);ke([Yr(":id/jobs"),Et(0,qs("id")),V("design:type",Function),V("design:paramtypes",[String]),V("design:returntype",Promise)],Lt.prototype,"listJobs",null);ke([cp(),Et(0,sp(new S(Lo))),V("design:type",Function),V("design:paramtypes",[Object]),V("design:returntype",Promise)],Lt.prototype,"launch",null);Lt=ke([ap("batches"),Et(0,zr(K)),Et(1,zr(P)),Et(2,zr(it)),V("design:paramtypes",[K,P,it])],Lt)});import{Body as Ds,Controller as up,Delete as lp,Get as Bs,HttpCode as pp,Inject as dp,Param as Zr,Patch as fp,Post as mp,Query as hp}from"@nestjs/common";var le,C,zt,vt,$s=p(()=>{"use strict";Z();hr();D();bt();le=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},C=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},zt=function(o,t){return function(e,r){t(e,r,o)}},vt=class{schedules;constructor(t){this.schedules=t}async list(t){if(t==null||t==="")return this.schedules.list();if(t!=="true"&&t!=="false")throw new b(`Invalid enabled filter: ${t}`);return this.schedules.list({enabled:t==="true"})}async get(t){let e=await this.schedules.get(t);if(!e)throw new h(`Schedule not found: ${t}`);return e}async create(t){return this.schedules.create(t)}async update(t,e){let r=await this.schedules.update(t,e);if(!r)throw new h(`Schedule not found: ${t}`);return r}async remove(t){if(!await this.schedules.delete(t))throw new h(`Schedule not found: ${t}`)}};le([Bs(),zt(0,hp("enabled")),C("design:type",Function),C("design:paramtypes",[String]),C("design:returntype",Promise)],vt.prototype,"list",null);le([Bs(":id"),zt(0,Zr("id")),C("design:type",Function),C("design:paramtypes",[String]),C("design:returntype",Promise)],vt.prototype,"get",null);le([mp(),zt(0,Ds(new S(ce))),C("design:type",Function),C("design:paramtypes",[Object]),C("design:returntype",Promise)],vt.prototype,"create",null);le([fp(":id"),zt(0,Zr("id")),zt(1,Ds(new S(ce.partial().omit({id:!0})))),C("design:type",Function),C("design:paramtypes",[String,Object]),C("design:returntype",Promise)],vt.prototype,"update",null);le([lp(":id"),pp(204),zt(0,Zr("id")),C("design:type",Function),C("design:paramtypes",[String]),C("design:returntype",Promise)],vt.prototype,"remove",null);vt=le([up("schedules"),zt(0,dp(jt)),C("design:paramtypes",[jt])],vt)});import{Controller as bp,Inject as wp,Query as Ls,Sse as yp}from"@nestjs/common";import{Observable as Fs}from"rxjs";var Js,Jo,tn,Ae,Us=p(()=>{"use strict";po();Js=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},Jo=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},tn=function(o,t){return function(e,r){t(e,r,o)}},Ae=class{events;constructor(t){this.events=t}stream(t,e){return new Fs(r=>{let i=this.events.subscribe(n=>{let s=n;t!=null&&t!==""&&(!("jobId"in s)||s.jobId!==t)||e!=null&&e!==""&&(!("batchId"in s)||s.batchId!==e)||r.next({data:s})});return()=>{i()}})}};Js([yp(),tn(0,Ls("jobId")),tn(1,Ls("batchId")),Jo("design:type",Function),Jo("design:paramtypes",[String,String]),Jo("design:returntype",Fs)],Ae.prototype,"stream",null);Ae=Js([bp("events"),tn(0,wp(nt)),Jo("design:paramtypes",[nt])],Ae)});import{extendZodWithOpenApi as gp}from"@asteasolutions/zod-to-openapi";import{z as Sp}from"zod";var Ms=p(()=>{"use strict";gp(Sp)});import{z as Vs}from"zod";var Fo,en=p(()=>{"use strict";Fo=Vs.object({value:Vs.string().min(1)})});import{z as l}from"zod";function $p(o){let t=l.toJSONSchema(o),{$schema:e,...r}=t;return r}function Xs(o){let t=(e,r)=>o.registerComponent("schemas",e,$p(r)).ref;return{WorkflowDefinition:t("WorkflowDefinition",Oe),WorkflowDefinitionInput:t("WorkflowDefinitionInput",ae),UpdateWorkflowBody:t("UpdateWorkflowBody",Ap),SubjectView:t("SubjectView",_o),CreateSubjectViewBody:t("CreateSubjectViewBody",Io),ReorderViewsBody:t("ReorderViewsBody",Eo),UpdateViewBody:t("UpdateViewBody",Np),WorkflowShortcut:t("WorkflowShortcut",vo),CreateWorkflowShortcutBody:t("CreateWorkflowShortcutBody",To),UpdateWorkflowShortcutBody:t("UpdateWorkflowShortcutBody",Ro),ReorderShortcutsBody:t("ReorderShortcutsBody",Oo),Schedule:t("Schedule",ce),UpdateScheduleBody:t("UpdateScheduleBody",qp),EngineSettings:t("EngineSettings",Br),UpdateSettingsBody:t("UpdateSettingsBody",Dp),SettingsPatchResponse:t("SettingsPatchResponse",Bp),SetSecretBody:t("SetSecretBody",Fo),CreateJobBody:t("CreateJobBody",qo),ResumeJobBody:t("ResumeJobBody",Co),LatestBySubjectBody:t("LatestBySubjectBody",Do),LatestBySubjectResponse:t("LatestBySubjectResponse",Cp),LaunchBody:t("LaunchBody",Lo),Job:t("Job",on),JobBatch:t("JobBatch",Ws),LaunchResponse:t("LaunchResponse",Tp),HealthResponse:t("HealthResponse",Rp),ProviderStatus:t("ProviderStatus",Op),QueryTemplate:t("QueryTemplate",Pi),ResolveQueryTemplateBody:t("ResolveQueryTemplateBody",jo),ResolveQueryTemplateResponse:t("ResolveQueryTemplateResponse",ki),ErrorResponse:t("ErrorResponse",Pp),EngineEvent:t("EngineEvent",kp),Subject:t("Subject",Uo)}}var jp,_p,Ip,xp,Uo,Ep,vp,on,Ws,Tp,Rp,Op,Pp,kp,Ap,Np,qp,Cp,Dp,Bp,T,rn,nn=p(()=>{"use strict";Ms();Z();Xr();Gr();en();jp=l.enum(["pending","planning","waiting_for_human","waiting_for_children","implementing","testing","completed","failed","cancelled"]),_p=l.object({subjectType:l.literal("ticket"),id:l.string(),source:l.enum(["jira","azure-devops","manual"]),title:l.string(),description:l.string().optional(),status:l.string(),assignee:l.string().optional(),url:l.string().optional(),raw:l.record(l.string(),l.unknown()).optional()}),Ip=l.object({subjectType:l.literal("pull_request"),id:l.string(),source:l.enum(["bitbucket","github","manual"]),title:l.string(),description:l.string().optional(),sourceBranch:l.string(),targetBranch:l.string(),author:l.string().optional(),url:l.string().optional(),raw:l.record(l.string(),l.unknown()).optional()}),xp=l.object({subjectType:l.literal("documentation"),id:l.string(),source:l.enum(["confluence","notion","github_wiki","gitlab_wiki","azure_wiki","web","manual"]),title:l.string(),url:l.string().optional(),raw:l.record(l.string(),l.unknown()).optional()}),Uo=l.discriminatedUnion("subjectType",[_p,Ip,xp]),Ep=l.discriminatedUnion("mode",[l.object({mode:l.literal("single"),subject:Uo}),l.object({mode:l.literal("collection"),subjects:l.array(Uo)})]),vp=l.object({id:l.string(),stepDefinitionId:l.string(),type:l.string(),status:l.enum(["pending","running","waiting_for_children","completed","failed","skipped"]),startedAt:l.string().optional(),completedAt:l.string().optional(),output:l.unknown().optional(),error:l.string().optional(),childJobIds:l.array(l.string()).optional(),iterations:l.array(l.object({index:l.number().int(),stepExecutions:l.array(l.record(l.string(),l.unknown())),startedAt:l.string(),completedAt:l.string().optional()})).optional()}),on=l.object({id:l.string(),workflowId:l.string(),status:jp,subjectContext:Ep.optional(),selection:$o.optional(),batchId:l.string().optional(),parentJobId:l.string().optional(),parentStepExecutionId:l.string().optional(),fanOutIndex:l.number().int().optional(),retryOf:l.string().optional(),context:l.record(l.string(),l.unknown()),worktreePath:l.string().optional(),branch:l.string().optional(),currentStepId:l.string().optional(),currentStepExecutionId:l.string().optional(),stepHistory:l.array(vp),createdAt:l.string(),updatedAt:l.string(),completedAt:l.string().optional()}),Ws=l.object({id:l.string(),workflowId:l.string(),selection:$o,resolvedSubjects:l.array(Uo),jobIds:l.array(l.string()),status:l.enum(["running","completed","completed_with_issues","failed"]),triggeredBy:l.enum(["schedule","view_bulk","multiselect"]),scheduleId:l.string().optional(),notificationOverride:Re.optional(),notificationSent:l.boolean(),createdAt:l.string(),completedAt:l.string().optional()}),Tp=l.discriminatedUnion("kind",[l.object({kind:l.literal("job"),job:on}),l.object({kind:l.literal("batch"),batch:Ws})]),Rp=l.object({ok:l.boolean(),service:l.string(),timestamp:l.string()}),Op=l.object({providerId:l.string(),secretKey:l.string(),configured:l.boolean()}),Pp=l.object({error:l.string()}),kp=l.object({type:l.string(),timestamp:l.string()}).passthrough(),Ap=ae,Np=xo,qp=ce.partial().omit({id:!0}),Cp=l.record(l.string(),on.nullable()),Dp=Po,Bp=l.object({settings:Br,restartRequired:l.boolean()}),T=l.object({id:l.string().min(1)}),rn=l.object({limit:l.string().optional().openapi({description:"Max items to return (default 50)"}),offset:l.string().optional().openapi({description:"Number of items to skip (default 0)"})})});import{z as x}from"zod";function w(o,t){return{description:t,content:{"application/json":{schema:o}}}}function et(o){return{type:"array",items:o}}function y(o,...t){let e={400:"Validation error",404:"Resource not found",409:"Conflict"};return Object.fromEntries(t.map(r=>[String(r),w(o.ErrorResponse,e[r]??"Error")]))}function Ks(o,t){o.registerPath({method:"get",path:"/health",tags:["Health"],summary:"Health check",responses:{200:w(t.HealthResponse,"Service is healthy")}}),o.registerPath({method:"get",path:"/workflows",tags:["Workflows"],summary:"List workflow definitions",request:{query:x.object({cardinality:x.enum(["single","batch","aggregate"]).optional()})},responses:{200:w(et(t.WorkflowDefinition),"Workflow definitions"),...y(t,400)}}),o.registerPath({method:"get",path:"/workflows/{id}",tags:["Workflows"],summary:"Get a workflow definition",request:{params:T},responses:{200:w(t.WorkflowDefinition,"Workflow definition"),...y(t,404)}}),o.registerPath({method:"post",path:"/workflows",tags:["Workflows"],summary:"Create a workflow definition",request:{body:{required:!0,content:{"application/json":{schema:t.WorkflowDefinitionInput}}}},responses:{201:w(t.WorkflowDefinition,"Created workflow definition"),...y(t,400)}}),o.registerPath({method:"patch",path:"/workflows/{id}",tags:["Workflows"],summary:"Update a workflow definition",request:{params:T,body:{required:!0,content:{"application/json":{schema:t.UpdateWorkflowBody}}}},responses:{200:w(t.WorkflowDefinition,"Updated workflow definition"),...y(t,400,404)}}),o.registerPath({method:"delete",path:"/workflows/{id}",tags:["Workflows"],summary:"Delete a workflow definition",description:"Rejected with 409 if any non-terminal Job still references the workflow. Terminal Jobs (completed, failed, cancelled) do not block deletion.",request:{params:T},responses:{204:{description:"Workflow deleted"},...y(t,404,409)}}),o.registerPath({method:"get",path:"/views",tags:["Views"],summary:"List subject views",request:{query:x.object({subjectType:ht.optional()})},responses:{200:w(et(t.SubjectView),"Subject views"),...y(t,400)}}),o.registerPath({method:"get",path:"/views/{id}",tags:["Views"],summary:"Get a subject view",request:{params:T},responses:{200:w(t.SubjectView,"Subject view"),...y(t,404)}}),o.registerPath({method:"get",path:"/views/{id}/subjects",tags:["Views"],summary:"Preview subjects matching a view",description:"Live provider query for the View's saved filter. Same resolution path as launch() for { mode: 'view' }. Does not create Jobs or snapshots.",request:{params:T},responses:{200:w(et(t.Subject),"Matching subjects"),...y(t,404,400)}}),o.registerPath({method:"patch",path:"/views/reorder",tags:["Views"],summary:"Reorder views within a subject type group",request:{body:{required:!0,content:{"application/json":{schema:t.ReorderViewsBody}}}},responses:{200:w(et(t.SubjectView),"Reordered views for the subject type"),...y(t,400)}}),o.registerPath({method:"post",path:"/views",tags:["Views"],summary:"Create a subject view",request:{body:{required:!0,content:{"application/json":{schema:t.CreateSubjectViewBody}}}},responses:{201:w(t.SubjectView,"Created subject view"),...y(t,400)}}),o.registerPath({method:"patch",path:"/views/{id}",tags:["Views"],summary:"Update a subject view",request:{params:T,body:{required:!0,content:{"application/json":{schema:t.UpdateViewBody}}}},responses:{200:w(t.SubjectView,"Updated subject view"),...y(t,400,404)}}),o.registerPath({method:"delete",path:"/views/{id}",tags:["Views"],summary:"Delete a subject view",request:{params:T},responses:{204:{description:"Subject view deleted"},...y(t,404)}}),o.registerPath({method:"get",path:"/jobs",tags:["Jobs"],summary:"List jobs",request:{query:rn.extend({workflowId:x.string().optional(),status:x.enum(["pending","planning","waiting_for_human","waiting_for_children","implementing","testing","completed","failed","cancelled"]).optional(),batchId:x.string().optional(),parentJobId:x.string().optional(),topLevelOnly:x.enum(["true","false"]).optional().openapi({description:"When true, exclude jobs that belong to a batch or a parent (sub_workflow) job"})})},responses:{200:w(et(t.Job),"Jobs"),...y(t,400)}}),o.registerPath({method:"get",path:"/jobs/{id}",tags:["Jobs"],summary:"Get a job",request:{params:T},responses:{200:w(t.Job,"Job"),...y(t,404)}}),o.registerPath({method:"post",path:"/jobs",tags:["Jobs"],summary:"Start a single job",request:{body:{required:!0,content:{"application/json":{schema:t.CreateJobBody}}}},responses:{201:w(t.Job,"Started job"),...y(t,400,404)}}),o.registerPath({method:"post",path:"/jobs/latest-by-subject",tags:["Jobs"],summary:"Latest job per subject for a workflow",request:{body:{required:!0,content:{"application/json":{schema:t.LatestBySubjectBody}}}},responses:{200:w(t.LatestBySubjectResponse,"Latest job keyed by subject id"),...y(t,400)}}),o.registerPath({method:"post",path:"/jobs/{id}/resume",tags:["Jobs"],summary:"Resume a job waiting for human input",request:{params:T,body:{required:!0,content:{"application/json":{schema:t.ResumeJobBody}}}},responses:{200:w(t.Job,"Resumed job"),...y(t,400,404,409)}}),o.registerPath({method:"post",path:"/jobs/{id}/retry",tags:["Jobs"],summary:"Retry a failed job",request:{params:T},responses:{200:w(t.Job,"Retry job"),...y(t,404,409)}}),o.registerPath({method:"get",path:"/batches",tags:["Batches"],summary:"List job batches",request:{query:rn.extend({workflowId:x.string().optional()})},responses:{200:w(et(t.JobBatch),"Job batches")}}),o.registerPath({method:"get",path:"/batches/{id}",tags:["Batches"],summary:"Get a job batch",request:{params:T},responses:{200:w(t.JobBatch,"Job batch"),...y(t,404)}}),o.registerPath({method:"get",path:"/batches/{id}/jobs",tags:["Batches"],summary:"List jobs in a batch",request:{params:T},responses:{200:w(et(t.Job),"Jobs in the batch"),...y(t,404)}}),o.registerPath({method:"post",path:"/batches",tags:["Batches"],summary:"Launch a batch or aggregate run",description:"Resolves subject selection and starts either a JobBatch (batch cardinality) or a single Job (aggregate cardinality).",request:{body:{required:!0,content:{"application/json":{schema:t.LaunchBody}}}},responses:{201:w(t.LaunchResponse,"Launch result"),...y(t,400,404)}}),o.registerPath({method:"get",path:"/workflow-shortcuts",tags:["Workflow shortcuts"],summary:"List workflow shortcuts",responses:{200:w(et(t.WorkflowShortcut),"Workflow shortcuts")}}),o.registerPath({method:"get",path:"/workflow-shortcuts/{id}",tags:["Workflow shortcuts"],summary:"Get a workflow shortcut",request:{params:T},responses:{200:w(t.WorkflowShortcut,"Workflow shortcut"),...y(t,404)}}),o.registerPath({method:"post",path:"/workflow-shortcuts",tags:["Workflow shortcuts"],summary:"Create a workflow shortcut",request:{body:{required:!0,content:{"application/json":{schema:t.CreateWorkflowShortcutBody}}}},responses:{201:w(t.WorkflowShortcut,"Created workflow shortcut"),...y(t,400,404)}}),o.registerPath({method:"patch",path:"/workflow-shortcuts/reorder",tags:["Workflow shortcuts"],summary:"Reorder workflow shortcuts",request:{body:{required:!0,content:{"application/json":{schema:t.ReorderShortcutsBody}}}},responses:{200:w(et(t.WorkflowShortcut),"Reordered workflow shortcuts"),...y(t,400)}}),o.registerPath({method:"patch",path:"/workflow-shortcuts/{id}",tags:["Workflow shortcuts"],summary:"Update a workflow shortcut",request:{params:T,body:{required:!0,content:{"application/json":{schema:t.UpdateWorkflowShortcutBody}}}},responses:{200:w(t.WorkflowShortcut,"Updated workflow shortcut"),...y(t,400,404)}}),o.registerPath({method:"delete",path:"/workflow-shortcuts/{id}",tags:["Workflow shortcuts"],summary:"Delete a workflow shortcut",request:{params:T},responses:{204:{description:"Workflow shortcut deleted"},...y(t,404)}}),o.registerPath({method:"get",path:"/schedules",tags:["Schedules"],summary:"List schedules",request:{query:x.object({enabled:x.enum(["true","false"]).optional()})},responses:{200:w(et(t.Schedule),"Schedules"),...y(t,400)}}),o.registerPath({method:"get",path:"/schedules/{id}",tags:["Schedules"],summary:"Get a schedule",request:{params:T},responses:{200:w(t.Schedule,"Schedule"),...y(t,404)}}),o.registerPath({method:"post",path:"/schedules",tags:["Schedules"],summary:"Create a schedule",description:"CRUD only \u2014 creating or enabling a schedule does not cause it to fire yet.",request:{body:{required:!0,content:{"application/json":{schema:t.Schedule}}}},responses:{201:w(t.Schedule,"Created schedule"),...y(t,400)}}),o.registerPath({method:"patch",path:"/schedules/{id}",tags:["Schedules"],summary:"Update a schedule",request:{params:T,body:{required:!0,content:{"application/json":{schema:t.UpdateScheduleBody}}}},responses:{200:w(t.Schedule,"Updated schedule"),...y(t,400,404)}}),o.registerPath({method:"delete",path:"/schedules/{id}",tags:["Schedules"],summary:"Delete a schedule",request:{params:T},responses:{204:{description:"Schedule deleted"},...y(t,404)}}),o.registerPath({method:"get",path:"/providers/status",tags:["Providers"],summary:"Provider secret configuration status",description:"Reports whether each known provider API key is set. Returns key *names* only \u2014 never secret values.",responses:{200:w(et(t.ProviderStatus),"Provider configuration status")}}),o.registerPath({method:"get",path:"/providers/{providerId}/query-templates",tags:["Providers"],summary:"List query templates for a provider",description:"Named, pre-built query templates owned by the provider. Providers with none yet (e.g. documentation) return an empty list. The client never constructs `query` itself \u2014 it submits templateId + params to the resolve endpoint.",request:{params:x.object({providerId:x.string().min(1)})},responses:{200:w(et(t.QueryTemplate),"Query templates")}}),o.registerPath({method:"post",path:"/providers/{providerId}/query-templates/{templateId}/resolve",tags:["Providers"],summary:"Resolve a query template to a concrete query",description:"Provider-specific query-shape knowledge stays server-side. Returns the `query` object to store on a SubjectView, along with template provenance the client attaches separately.",request:{params:x.object({providerId:x.string().min(1),templateId:x.string().min(1)}),body:{required:!0,content:{"application/json":{schema:t.ResolveQueryTemplateBody}}}},responses:{200:w(t.ResolveQueryTemplateResponse,"Resolved query"),...y(t,400,404)}}),o.registerPath({method:"get",path:"/settings",tags:["Settings"],summary:"Get engine settings",description:"Persisted provider configuration. Never includes secret values \u2014 those live in SecretStore.",responses:{200:w(t.EngineSettings,"Current engine settings")}}),o.registerPath({method:"patch",path:"/settings",tags:["Settings"],summary:"Update engine settings",description:"Partial merge. restartRequired is true only when activeProviders was in the patch (implementation binding is a boot-time decision). Jira/Bitbucket config fields take effect on the next provider call with no restart.",request:{body:{required:!0,content:{"application/json":{schema:t.UpdateSettingsBody}}}},responses:{200:w(t.SettingsPatchResponse,"Updated settings"),...y(t,400)}}),o.registerPath({method:"post",path:"/secrets/{key}",tags:["Settings"],summary:"Store a secret",description:"Writes to SecretStore. The response never includes the secret value.",request:{params:x.object({key:x.string().min(1)}),body:{required:!0,content:{"application/json":{schema:t.SetSecretBody}}}},responses:{204:{description:"Secret stored"},...y(t,400)}}),o.registerPath({method:"get",path:"/events",tags:["Events"],summary:"Subscribe to engine events (SSE)",description:"Server-Sent Events stream. Each event `data` field is a JSON EngineEvent. Optionally filter by jobId and/or batchId.",request:{query:x.object({jobId:x.string().optional(),batchId:x.string().optional()})},responses:{200:{description:"SSE stream of engine events",content:{"text/event-stream":{schema:t.EngineEvent}}}}})}var Hs=p(()=>{"use strict";Z();nn()});import{OpenAPIRegistry as Lp,OpenApiGeneratorV31 as Jp}from"@asteasolutions/zod-to-openapi";function Gs(){if(Mo)return Mo;let o=new Lp,t=Xs(o);return Ks(o,t),Mo=new Jp(o.definitions).generateDocument({openapi:"3.1.0",info:{title:"Kno Engine API",version:"0.1.0",description:"REST API for workflow definitions, jobs, batches, schedules, views, and live events."},servers:[{url:"/api"}]}),Mo}var Mo,zs=p(()=>{"use strict";nn();Hs()});import{Controller as Fp,Get as Up,Header as Mp}from"@nestjs/common";var Qs,sn,Ne,Ys=p(()=>{"use strict";zs();Qs=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},sn=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},Ne=class{getOpenApiDocument(){return Gs()}};Qs([Up("openapi.json"),Mp("Content-Type","application/json"),sn("design:type",Function),sn("design:paramtypes",[]),sn("design:returntype",void 0)],Ne.prototype,"getOpenApiDocument",null);Ne=Qs([Fp()],Ne)});import{Controller as Vp,Get as ta,Inject as Zs,Param as an,Post as Wp,Body as Xp,HttpCode as Kp}from"@nestjs/common";var Vo,gt,pe,Qt,ea=p(()=>{"use strict";Ir();xr();Z();bt();Vo=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},gt=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},pe=function(o,t){return function(e,r){t(e,r,o)}},Qt=class{providerStatus;queryTemplates;constructor(t,e){this.providerStatus=t,this.queryTemplates=e}async status(){return this.providerStatus.list()}listQueryTemplates(t){return this.queryTemplates.list(t)}resolveQueryTemplate(t,e,r){return{query:this.queryTemplates.resolve(t,e,r.params)}}};Vo([ta("status"),gt("design:type",Function),gt("design:paramtypes",[]),gt("design:returntype",Promise)],Qt.prototype,"status",null);Vo([ta(":providerId/query-templates"),pe(0,an("providerId")),gt("design:type",Function),gt("design:paramtypes",[String]),gt("design:returntype",Array)],Qt.prototype,"listQueryTemplates",null);Vo([Wp(":providerId/query-templates/:templateId/resolve"),Kp(200),pe(0,an("providerId")),pe(1,an("templateId")),pe(2,Xp(new S(jo))),gt("design:type",Function),gt("design:paramtypes",[String,String,Object]),gt("design:returntype",Object)],Qt.prototype,"resolveQueryTemplate",null);Qt=Vo([Vp("providers"),pe(0,Zs(kt)),pe(1,Zs(At)),gt("design:paramtypes",[kt,At])],Qt)});import{Body as Hp,Controller as Gp,Get as zp,Inject as Qp,Patch as Yp}from"@nestjs/common";var cn,Yt,oa,de,ra=p(()=>{"use strict";Z();oo();bt();cn=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},Yt=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},oa=function(o,t){return function(e,r){t(e,r,o)}},de=class{settings;constructor(t){this.settings=t}get(){return this.settings.get()}async update(t){return{settings:await this.settings.update(t),restartRequired:Gn(t)}}};cn([zp(),Yt("design:type",Function),Yt("design:paramtypes",[]),Yt("design:returntype",Promise)],de.prototype,"get",null);cn([Yp(),oa(0,Hp(new S(Po))),Yt("design:type",Function),Yt("design:paramtypes",[Object]),Yt("design:returntype",Promise)],de.prototype,"update",null);de=cn([Gp("settings"),oa(0,Qp(J)),Yt("design:paramtypes",[J])],de)});import{Body as Zp,Controller as td,HttpCode as ed,Inject as od,Param as rd,Post as nd}from"@nestjs/common";var na,Wo,un,qe,ia=p(()=>{"use strict";Tt();D();bt();en();na=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},Wo=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},un=function(o,t){return function(e,r){t(e,r,o)}},qe=class{secrets;constructor(t){this.secrets=t}async set(t,e){let r=t.trim();if(!r)throw new b("Secret key must not be empty");await this.secrets.set(r,e.value)}};na([nd(":key"),ed(204),un(0,rd("key")),un(1,Zp(new S(Fo))),Wo("design:type",Function),Wo("design:paramtypes",[String,Object]),Wo("design:returntype",Promise)],qe.prototype,"set",null);qe=na([td("secrets"),un(0,od(ot)),Wo("design:paramtypes",[Function])],qe)});import{Module as sd}from"@nestjs/common";import{APP_FILTER as ad}from"@nestjs/core";var id,Xo,sa=p(()=>{"use strict";xe();Ar();fo();Oi();_s();vs();Ps();Ns();Cs();$s();Us();Ys();ea();ra();ia();uo();sr();id=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},Xo=class{};Xo=id([sd({imports:[ft,se,qt,Nt,Zt],controllers:[xt,st,wt,yt,Lt,vt,Ae,Ne,Qt,de,qe],providers:[{provide:ad,useClass:So}]})],Xo)});import{Module as ud}from"@nestjs/common";var cd,Ko,aa=p(()=>{"use strict";dn();fn();mn();uo();pi();fo();xe();Ar();sa();cd=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},Ko=class{};Ko=cd([ud({imports:[Ce,De,Nt,lo,qt,ft,se,Xo],controllers:[fe]})],Ko)});import{apiReference as ld}from"@scalar/nestjs-api-reference";function ca(o){o.use("/api/docs",ld({url:"/api/openapi.json",pageTitle:"Kno Engine API"}))}var ua=p(()=>{"use strict"});import{createServer as pd}from"node:net";function la(o){return typeof o=="object"&&o!==null&&"code"in o&&o.code==="EADDRINUSE"}async function ln(o,t=20){for(let e=0;e<t;e+=1){let r=o+e;if(await dd(r))return r}throw new Error(`No free port found in ${o}\u2013${o+t-1}`)}function dd(o){return new Promise(t=>{let e=pd();e.once("error",()=>{t(!1)}),e.once("listening",()=>{e.close(()=>t(!0))}),e.listen(o)})}var pa=p(()=>{"use strict"});import{Catch as hd,HttpStatus as da,NotFoundException as bd}from"@nestjs/common";import{existsSync as wd}from"node:fs";import{extname as yd,join as gd}from"node:path";function fa(o){return(t,e,r)=>{if(!ma(t)){r();return}e.sendFile(o,i=>{i&&r(i)})}}function ma(o){if(o.method!=="GET"&&o.method!=="HEAD")return!1;let t=o.path??"";if(t.startsWith("/api"))return!1;let e=yd(t);return!(e&&e!==".html")}function ha(o){return gd(o,"index.html")}var fd,md,Ho,ba=p(()=>{"use strict";fd=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},md=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},Ho=class{indexHtml;constructor(t){this.indexHtml=t}catch(t,e){let r=e.switchToHttp(),i=r.getRequest(),n=r.getResponse();if(ma(i)&&wd(this.indexHtml)){n.sendFile(this.indexHtml,u=>{u&&!n.headersSent&&n.status(da.NOT_FOUND).json({statusCode:da.NOT_FOUND,message:"UI index.html could not be served"})});return}let s=t.getStatus(),a=t.getResponse();n.status(s).json(typeof a=="string"?{statusCode:s,message:a}:a)}};Ho=fd([hd(bd),md("design:paramtypes",[String])],Ho)});import{existsSync as Sd}from"node:fs";import{dirname as jd,join as Go}from"node:path";import{fileURLToPath as _d}from"node:url";function wa(){let o=jd(_d(import.meta.url)),t=[Go(o,"../static"),Go(o,"../../static"),Go(o,"static")];for(let e of t)if(Sd(Go(e,"index.html")))return e;return null}var ya=p(()=>{"use strict"});var Td={};import"reflect-metadata";import{existsSync as Id}from"node:fs";import{Logger as xd}from"@nestjs/common";import{NestFactory as Ed}from"@nestjs/core";async function vd(){let o=await Ed.create(Ko);o.enableCors(),o.setGlobalPrefix("api"),ca(o);let t=wa(),e=t?ha(t):null;t&&e&&Id(e)?(zo.log(`Serving UI from ${t}`),o.useStaticAssets(t,{index:!1,fallthrough:!0}),o.use(fa(e)),o.useGlobalFilters(new Ho(e))):zo.warn("No UI found (static/index.html missing). GET / will 404; /api still works. Rebuild with `npm run build:release` before publishing.");let r=Number(process.env.PORT??3e3);if(!Number.isInteger(r)||r<1||r>65535)throw new Error(`Invalid PORT: ${process.env.PORT}`);let i=await ln(r);for(let n=0;n<5;n+=1)try{await o.listen(i),i!==r?zo.warn(`Port ${r} is in use; listening on ${i} instead`):zo.log(`Listening on http://localhost:${i}`);return}catch(s){if(!la(s))throw s;i=await ln(i+1)}throw new Error(`Could not bind a free port starting at ${r}`)}var zo,ga=p(()=>{"use strict";aa();ua();pa();ba();ya();zo=new xd("Bootstrap");vd()});import{readFileSync as Rd}from"node:fs";function Od(){let o=Rd(new URL("../package.json",import.meta.url),"utf8");return JSON.parse(o).version}var Qo=process.argv.slice(2);Qo.includes("--version")||Qo.includes("-v")?console.log(Od()):Qo.includes("--help")||Qo.includes("-h")?console.log(["Usage: knoflows [options]","","Starts the knoflows engine (REST API + bundled web client).","","Options:"," -v, --version Print the engine version and exit"," -h, --help Print this message and exit","","Environment:"," PORT Preferred HTTP port (default 3000). If taken, the next free port is used."," KNO_SQLITE_PATH SQLite file path, or :memory: for an ephemeral database"].join(`
144
- `)):await Promise.resolve().then(()=>(ga(),Td));
140
+ `),Tc(o)}var Mn=p(()=>{"use strict"});import{Injectable as Pc}from"@nestjs/common";import{mkdirSync as kc}from"node:fs";import{dirname as Ac}from"node:path";import{fileURLToPath as Nc}from"node:url";import{DatabaseSync as Vn}from"node:sqlite";var Rc,Oc,W,Wn=p(()=>{"use strict";Jn();Mn();Rc=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},Oc=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},W=class{sqlite;db;constructor(){let e=process.env.KNO_SQLITE_PATH??Nc(new URL("../../data/kno.db",import.meta.url));e===":memory:"?this.sqlite=new Vn(":memory:"):(kc(Ac(e),{recursive:!0}),this.sqlite=new Vn(e)),this.db=Fn(this.sqlite),mr(this.sqlite)}async onModuleInit(){mr(this.sqlite)}getDb(){return this.db}getSqlite(){return this.sqlite}};W=Rc([Pc(),Oc("design:paramtypes",[])],W)});import{Injectable as Dc}from"@nestjs/common";import{eq as Xn}from"drizzle-orm";var qc,Cc,O,ee=p(()=>{"use strict";ze();qc=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},Cc=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},O=class{db;sqlite;constructor(t,e){this.db=t,this.sqlite=e}async create(t){let e=new Date().toISOString();return await this.db.insert(ct).values({id:t.id,name:t.name,description:t.description??null,appliesTo:t.appliesTo,cardinality:t.cardinality,inputSchema:t.inputSchema,steps:t.steps,notificationPolicy:t.notificationPolicy,createdAt:e,updatedAt:e}),await this.get(t.id)}async get(t){let e=await this.db.query.workflowDefinitions.findFirst({where:{id:t}});return e?this.toDomain(e):null}async update(t,e){let r=await this.get(t);return r?(await this.db.update(ct).set({name:e.name??r.name,description:e.description!==void 0?e.description??null:r.description??null,appliesTo:e.appliesTo??r.appliesTo,cardinality:e.cardinality??r.cardinality,inputSchema:e.inputSchema??r.inputSchema,steps:e.steps??r.steps,notificationPolicy:e.notificationPolicy??r.notificationPolicy,updatedAt:new Date().toISOString()}).where(Xn(ct.id,t)),this.get(t)):null}async list(t={}){return(t.cardinality?await this.db.query.workflowDefinitions.findMany({where:{cardinality:t.cardinality}}):await this.db.query.workflowDefinitions.findMany()).map(r=>this.toDomain(r))}async delete(t){if(!await this.get(t))return!1;try{this.sqlite?.exec("PRAGMA foreign_keys = OFF"),await this.db.delete(ct).where(Xn(ct.id,t))}finally{this.sqlite?.exec("PRAGMA foreign_keys = ON")}return!0}toDomain(t){return{id:t.id,name:t.name,...t.description!=null?{description:t.description}:{},appliesTo:t.appliesTo,cardinality:t.cardinality,inputSchema:t.inputSchema,steps:t.steps,notificationPolicy:t.notificationPolicy}}};O=qc([Dc(),Cc("design:paramtypes",[Object,Function])],O)});import{Injectable as Lc}from"@nestjs/common";import{eq as hr}from"drizzle-orm";var Bc,$c,Kn,X,to=p(()=>{"use strict";cr();Bc=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},$c=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},Kn=["ticket","pull_request","documentation"],X=class{db;constructor(t){this.db=t}async create(t){let e=await this.nextOrder(t.subjectType);return await this.db.insert(ut).values({id:t.id,name:t.name,subjectType:t.subjectType,workflowId:t.workflowId,query:t.query,description:t.description??null,queryTemplate:t.queryTemplate??null,order:e}),await this.get(t.id)}async get(t){let e=await this.db.query.subjectViews.findFirst({where:{id:t}});return e?this.toDomain(e):null}async update(t,e){let r=await this.get(t);if(!r)return null;let i=e.queryTemplate!==void 0?e.queryTemplate:e.query!==void 0?void 0:r.queryTemplate;return await this.db.update(ut).set({name:e.name??r.name,subjectType:e.subjectType??r.subjectType,workflowId:e.workflowId??r.workflowId,query:e.query??r.query,description:e.description!==void 0?e.description??null:r.description??null,queryTemplate:i??null}).where(hr(ut.id,t)),this.get(t)}async list(t={}){let e=t.subjectType?await this.db.query.subjectViews.findMany({where:{subjectType:t.subjectType}}):await this.db.query.subjectViews.findMany();return this.sortViews(e.map(r=>this.toDomain(r)))}async reorder(t){let e=[];for(let i of t){let n=await this.get(i);if(!n)return[];e.push(n)}let r=e[0].subjectType;if(!e.every(i=>i.subjectType===r))return[];for(let i=0;i<t.length;i+=1)await this.db.update(ut).set({order:i}).where(hr(ut.id,t[i]));return this.list({subjectType:r})}async delete(t){return await this.get(t)?(await this.db.delete(ut).where(hr(ut.id,t)),!0):!1}async nextOrder(t){let e=await this.db.query.subjectViews.findMany({where:{subjectType:t}});return e.length===0?0:Math.max(...e.map(r=>r.order))+1}sortViews(t){return[...t].sort((e,r)=>{let i=Kn.indexOf(e.subjectType)-Kn.indexOf(r.subjectType);return i!==0?i:e.order-r.order})}toDomain(t){return{id:t.id,name:t.name,subjectType:t.subjectType,workflowId:t.workflowId,query:t.query,order:t.order,...t.description!=null?{description:t.description}:{},...t.queryTemplate!=null?{queryTemplate:t.queryTemplate}:{}}}};X=Bc([Lc(),$c("design:paramtypes",[Object])],X)});import{Injectable as Jc}from"@nestjs/common";import{and as Mc,desc as Vc,eq as Ie,inArray as Wc}from"drizzle-orm";import{randomUUID as Xc}from"node:crypto";function Kc(o){return o?o.mode==="single"?[o.subject]:o.subjects:[]}function Hc(o){if(o.length!==0)return o.length===1?{mode:"single",subject:o[0]}:{mode:"collection",subjects:o}}function Gn(o,t,e=null,r=null){let i=[];for(let n of t)if(i.push({id:n.id,jobId:o,stepDefinitionId:n.stepDefinitionId,type:n.type,status:n.status,startedAt:n.startedAt??null,completedAt:n.completedAt??null,output:n.output??null,error:n.error??null,childJobIds:n.childJobIds??null,parentStepExecutionId:e,iterationIndex:r}),n.iterations)for(let s of n.iterations)i.push(...Gn(o,s.stepExecutions,n.id,s.index));return i}function Gc(o){let t=new Map;for(let i of o){let n=i.parentStepExecutionId,s=t.get(n)??[];s.push(i),t.set(n,s)}let e=i=>{let n=t.get(i)??[];if(n.length===0)return;let s=new Map;for(let a of n){if(a.iterationIndex==null)continue;let u=s.get(a.iterationIndex)??[];u.push(a),s.set(a.iterationIndex,u)}if(s.size!==0)return[...s.entries()].sort(([a],[u])=>a-u).map(([a,u])=>{let c=u.map(f=>Hn(f,e(f.id)));return{index:a,stepExecutions:c,startedAt:zc(c),...Yc(c)?{completedAt:Qc(c)}:{}}})};return(t.get(null)??[]).filter(i=>i.iterationIndex==null).map(i=>Hn(i,e(i.id)))}function Hn(o,t){return{id:o.id,stepDefinitionId:o.stepDefinitionId,type:o.type,status:o.status,...o.startedAt!=null?{startedAt:o.startedAt}:{},...o.completedAt!=null?{completedAt:o.completedAt}:{},...o.output!==null&&o.output!==void 0?{output:o.output}:{},...o.error!=null?{error:o.error}:{},...o.childJobIds!=null?{childJobIds:o.childJobIds}:{},...t&&t.length>0?{iterations:t}:{}}}function zc(o){let t=o.map(e=>e.startedAt).filter(e=>e!=null);return t.length===0?"":t.reduce((e,r)=>e<r?e:r)}function Qc(o){return o.map(e=>e.completedAt).filter(e=>e!=null).reduce((e,r)=>e>r?e:r)}function Yc(o){return o.length>0&&o.every(t=>t.completedAt!=null)}var Uc,Fc,P,oe=p(()=>{"use strict";ge();ur();lr();Uc=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},Fc=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},P=class{db;constructor(t){this.db=t}async create(t){return await this.db.insert(N).values(this.jobToRow(t)),await this.replaceSubjects(t.id,t.subjectContext),await this.replaceStepExecutions(t.id,t.stepHistory),await this.get(t.id)}async get(t){let e=await this.db.query.jobs.findFirst({where:{id:t},with:{subjects:!0,stepExecutions:!0}});return e?this.toDomain(e,e.subjects,e.stepExecutions):null}async update(t,e){let r=await this.get(t);if(!r)return null;let i={...r,...e,id:t,context:e.context??r.context,stepHistory:e.stepHistory??r.stepHistory,updatedAt:e.updatedAt??new Date().toISOString()};return await this.db.update(N).set({workflowId:i.workflowId,status:i.status,selection:i.selection??null,batchId:i.batchId??null,parentJobId:i.parentJobId??null,parentStepExecutionId:i.parentStepExecutionId??null,fanOutIndex:i.fanOutIndex??null,retryOf:i.retryOf??null,context:i.context,worktreePath:i.worktreePath??null,branch:i.branch??null,currentStepId:i.currentStepId??null,currentStepExecutionId:i.currentStepExecutionId??null,createdAt:i.createdAt,updatedAt:i.updatedAt,completedAt:i.completedAt??null}).where(Ie(N.id,t)),e.subjectContext!==void 0&&await this.replaceSubjects(t,e.subjectContext),e.stepHistory!==void 0&&await this.replaceStepExecutions(t,e.stepHistory),this.get(t)}async list(t={}){let e={};t.workflowId!==void 0&&(e.workflowId=t.workflowId),t.status!==void 0&&(e.status=t.status),t.batchId!==void 0&&(e.batchId=t.batchId),t.parentJobId!==void 0&&(e.parentJobId=t.parentJobId),t.parentStepExecutionId!==void 0&&(e.parentStepExecutionId=t.parentStepExecutionId);let i=(Object.keys(e).length>0?await this.db.query.jobs.findMany({where:e,with:{subjects:!0,stepExecutions:!0}}):await this.db.query.jobs.findMany({with:{subjects:!0,stepExecutions:!0}})).map(n=>this.toDomain(n,n.subjects,n.stepExecutions));return t.topLevelOnly?i.filter(n=>n.batchId==null&&n.parentJobId==null):i}async latestBySubject(t,e){let r={};for(let c of e)r[c]=null;if(e.length===0)return r;let i=await this.db.select({subjectId:pt.subjectId,jobId:N.id,createdAt:N.createdAt}).from(pt).innerJoin(N,Ie(pt.jobId,N.id)).where(Mc(Ie(N.workflowId,t),Wc(pt.subjectId,e))).orderBy(Vc(N.createdAt)),n=new Map;for(let c of i)n.has(c.subjectId)||n.set(c.subjectId,c.jobId);let s=[...new Set(n.values())],a=await Promise.all(s.map(c=>this.get(c))),u=new Map(a.filter(c=>c!=null).map(c=>[c.id,c]));for(let[c,f]of n)r[c]=u.get(f)??null;return r}jobToRow(t){return{id:t.id,workflowId:t.workflowId,status:t.status,selection:t.selection??null,batchId:t.batchId??null,parentJobId:t.parentJobId??null,parentStepExecutionId:t.parentStepExecutionId??null,fanOutIndex:t.fanOutIndex??null,retryOf:t.retryOf??null,context:t.context,worktreePath:t.worktreePath??null,branch:t.branch??null,currentStepId:t.currentStepId??null,currentStepExecutionId:t.currentStepExecutionId??null,createdAt:t.createdAt,updatedAt:t.updatedAt,completedAt:t.completedAt??null}}async replaceSubjects(t,e){await this.db.delete(pt).where(Ie(pt.jobId,t));let r=Kc(e);r.length!==0&&await this.db.insert(pt).values(r.map(i=>({id:Xc(),jobId:t,subjectType:i.subjectType,subjectId:i.id,snapshot:i})))}async replaceStepExecutions(t,e){await this.db.delete(Vt).where(Ie(Vt.jobId,t));let r=Gn(t,e);r.length!==0&&await this.db.insert(Vt).values(r)}toDomain(t,e,r){let i=Hc(e.map(s=>s.snapshot)),n=Gc(r);return{id:t.id,workflowId:t.workflowId,status:t.status,...i?{subjectContext:i}:{},...t.selection!=null?{selection:t.selection}:{},...t.batchId!=null?{batchId:t.batchId}:{},...t.parentJobId!=null?{parentJobId:t.parentJobId}:{},...t.parentStepExecutionId!=null?{parentStepExecutionId:t.parentStepExecutionId}:{},...t.fanOutIndex!=null?{fanOutIndex:t.fanOutIndex}:{},...t.retryOf!=null?{retryOf:t.retryOf}:{},context:t.context,...t.worktreePath!=null?{worktreePath:t.worktreePath}:{},...t.branch!=null?{branch:t.branch}:{},...t.currentStepId!=null?{currentStepId:t.currentStepId}:{},...t.currentStepExecutionId!=null?{currentStepExecutionId:t.currentStepExecutionId}:{},stepHistory:n,createdAt:t.createdAt,updatedAt:t.updatedAt,...t.completedAt!=null?{completedAt:t.completedAt}:{}}}};P=Uc([Jc(),Fc("design:paramtypes",[Object])],P)});import{Injectable as eu}from"@nestjs/common";import{eq as ou}from"drizzle-orm";var Zc,tu,K,eo=p(()=>{"use strict";Qe();Zc=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},tu=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},K=class{db;constructor(t){this.db=t}async create(t){return await this.db.insert(Rt).values({id:t.id,workflowId:t.workflowId,selection:t.selection,resolvedSubjects:t.resolvedSubjects,status:t.status,triggeredBy:t.triggeredBy,scheduleId:t.scheduleId??null,notificationOverride:t.notificationOverride??null,notificationSent:t.notificationSent,createdAt:t.createdAt,completedAt:t.completedAt??null}),await this.get(t.id)}async get(t){let e=await this.db.query.jobBatches.findFirst({where:{id:t},with:{jobs:!0}});return e?this.toDomain(e,e.jobs.map(r=>r.id)):null}async update(t,e){let r=await this.get(t);return r?(await this.db.update(Rt).set({workflowId:e.workflowId??r.workflowId,selection:e.selection??r.selection,resolvedSubjects:e.resolvedSubjects??r.resolvedSubjects,status:e.status??r.status,triggeredBy:e.triggeredBy??r.triggeredBy,scheduleId:e.scheduleId!==void 0?e.scheduleId??null:r.scheduleId??null,notificationOverride:e.notificationOverride!==void 0?e.notificationOverride??null:r.notificationOverride??null,notificationSent:e.notificationSent??r.notificationSent,createdAt:e.createdAt??r.createdAt,completedAt:e.completedAt!==void 0?e.completedAt??null:r.completedAt??null}).where(ou(Rt.id,t)),this.get(t)):null}async list(t={}){return(t.workflowId?await this.db.query.jobBatches.findMany({where:{workflowId:t.workflowId},with:{jobs:!0}}):await this.db.query.jobBatches.findMany({with:{jobs:!0}})).map(r=>this.toDomain(r,r.jobs.map(i=>i.id)))}toDomain(t,e){return{id:t.id,workflowId:t.workflowId,selection:t.selection,resolvedSubjects:t.resolvedSubjects,jobIds:e,status:t.status,triggeredBy:t.triggeredBy,...t.scheduleId!=null?{scheduleId:t.scheduleId}:{},...t.notificationOverride!=null?{notificationOverride:t.notificationOverride}:{},notificationSent:t.notificationSent,createdAt:t.createdAt,...t.completedAt!=null?{completedAt:t.completedAt}:{}}}};K=Zc([eu(),tu("design:paramtypes",[Object])],K)});import{Injectable as iu}from"@nestjs/common";import{eq as zn}from"drizzle-orm";var ru,nu,jt,br=p(()=>{"use strict";pr();ru=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},nu=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},jt=class{db;constructor(t){this.db=t}async create(t){return await this.db.insert(Pt).values({id:t.id,viewId:t.viewId,triggerType:t.trigger.type,cadence:t.trigger.cadence,notificationOverride:t.notificationOverride??null,missedFirePolicy:t.missedFirePolicy,enabled:t.enabled,lastFiredAt:t.lastFiredAt??null,createdAt:t.createdAt}),await this.get(t.id)}async get(t){let e=await this.db.query.schedules.findFirst({where:{id:t}});return e?this.toDomain(e):null}async update(t,e){let r=await this.get(t);if(!r)return null;let i=e.trigger??r.trigger;return await this.db.update(Pt).set({viewId:e.viewId??r.viewId,triggerType:i.type,cadence:i.cadence,notificationOverride:e.notificationOverride!==void 0?e.notificationOverride??null:r.notificationOverride??null,missedFirePolicy:e.missedFirePolicy??r.missedFirePolicy,enabled:e.enabled??r.enabled,lastFiredAt:e.lastFiredAt!==void 0?e.lastFiredAt??null:r.lastFiredAt??null,createdAt:e.createdAt??r.createdAt}).where(zn(Pt.id,t)),this.get(t)}async list(t={}){return(t.enabled!==void 0?await this.db.query.schedules.findMany({where:{enabled:t.enabled}}):await this.db.query.schedules.findMany()).map(r=>this.toDomain(r))}async delete(t){return await this.get(t)?(await this.db.delete(Pt).where(zn(Pt.id,t)),!0):!1}async findDue(t){return(await this.list({enabled:!0})).filter(r=>r.lastFiredAt==null||r.lastFiredAt<t)}toDomain(t){return{id:t.id,viewId:t.viewId,trigger:{type:"cron",cadence:t.cadence},...t.notificationOverride!=null?{notificationOverride:t.notificationOverride}:{},missedFirePolicy:t.missedFirePolicy,enabled:t.enabled,...t.lastFiredAt!=null?{lastFiredAt:t.lastFiredAt}:{},createdAt:t.createdAt}}};jt=ru([iu(),nu("design:paramtypes",[Object])],jt)});import{Injectable as cu}from"@nestjs/common";import{eq as wr}from"drizzle-orm";var su,au,_t,yr=p(()=>{"use strict";dr();su=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},au=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},_t=class{db;constructor(t){this.db=t}async create(t){let e=await this.nextOrder();return await this.db.insert(dt).values({id:t.id,name:t.name,workflowId:t.workflowId,inputValues:t.inputValues,lastJobId:t.lastJobId??null,order:e}),await this.get(t.id)}async get(t){let e=await this.db.query.workflowShortcuts.findFirst({where:{id:t}});return e?this.toDomain(e):null}async update(t,e){let r=await this.get(t);return r?(await this.db.update(dt).set({name:e.name??r.name,workflowId:e.workflowId??r.workflowId,inputValues:e.inputValues??r.inputValues,lastJobId:e.lastJobId!==void 0?e.lastJobId??null:r.lastJobId??null}).where(wr(dt.id,t)),this.get(t)):null}async list(){return(await this.db.query.workflowShortcuts.findMany()).map(e=>this.toDomain(e)).sort((e,r)=>e.order-r.order)}async reorder(t){let e=[];for(let r of t){let i=await this.get(r);if(!i)return[];e.push(i)}for(let r=0;r<t.length;r+=1)await this.db.update(dt).set({order:r}).where(wr(dt.id,t[r]));return this.list()}async delete(t){return await this.get(t)?(await this.db.delete(dt).where(wr(dt.id,t)),!0):!1}async nextOrder(){let t=await this.db.query.workflowShortcuts.findMany();return t.length===0?0:Math.max(...t.map(e=>e.order))+1}toDomain(t){return{id:t.id,name:t.name,workflowId:t.workflowId,inputValues:t.inputValues,order:t.order,...t.lastJobId!=null?{lastJobId:t.lastJobId}:{}}}};_t=su([cu(),au("design:paramtypes",[Object])],_t)});import{Injectable as pu}from"@nestjs/common";import{eq as du}from"drizzle-orm";function fu(o,t){let e={...o.activeProviders,...t.activeProviders},r=t.jira!==void 0?{...o.jira,...t.jira}:o.jira,i=t.bitbucket!==void 0?{...o.bitbucket,...t.bitbucket}:o.bitbucket;return gr({activeProviders:e,...r&&Object.keys(r).length>0?{jira:r}:{},...i&&Object.keys(i).length>0?{bitbucket:i}:{}})}function gr(o){return{...o,activeProviders:{ticket:o.activeProviders?.ticket??"manual",repo:o.activeProviders?.repo??"manual",agent:o.activeProviders?.agent??"claude"},...o.jira?{jira:o.jira}:{},...o.bitbucket?{bitbucket:o.bitbucket}:{}}}function Qn(o){return Object.prototype.hasOwnProperty.call(o,"activeProviders")}var uu,lu,U,oo=p(()=>{"use strict";fr();uu=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},lu=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},U=class{db;constructor(t){this.db=t}async get(){let t=await this.db.query.settings.findFirst({where:{id:_e}});return gr(t?t.data:{})}async update(t){let e=fu(await this.get(),t);return await this.db.query.settings.findFirst({where:{id:_e}})?await this.db.update(te).set({data:e}).where(du(te.id,_e)):await this.db.insert(te).values({id:_e,data:e}),e}};U=uu([pu(),lu("design:paramtypes",[Object])],U)});import{Module as hu}from"@nestjs/common";var mu,bu,ft,xe=p(()=>{"use strict";Wn();ee();to();oe();eo();br();yr();oo();mu=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},bu=[O,X,P,K,jt,_t,U],ft=class{};ft=mu([hu({providers:[W,{provide:O,useFactory:o=>new O(o.getDb(),o.getSqlite()),inject:[W]},{provide:X,useFactory:o=>new X(o.getDb()),inject:[W]},{provide:P,useFactory:o=>new P(o.getDb()),inject:[W]},{provide:K,useFactory:o=>new K(o.getDb()),inject:[W]},{provide:jt,useFactory:o=>new jt(o.getDb()),inject:[W]},{provide:_t,useFactory:o=>new _t(o.getDb()),inject:[W]},{provide:U,useFactory:o=>new U(o.getDb()),inject:[W]}],exports:[W,...bu]})],ft)});function Sr(o){return o==null?"":typeof o=="string"?o:Zn(o).replace(/\n+$/,"")}function Yn(o){return{version:1,type:"doc",content:o.split(`
141
+ `).map(e=>({type:"paragraph",content:e.length===0?[]:[{type:"text",text:e}]}))}}function Zn(o){if(o==null||typeof o!="object")return"";let t=o;if(t.type==="text")return t.text??"";if(t.type==="hardBreak")return`
142
+ `;let e=(t.content??[]).map(Zn).join("");return t.type==="paragraph"||t.type==="heading"||t.type==="blockquote"||t.type==="listItem"?`${e}
143
+ `:e}var ti=p(()=>{"use strict"});function gu(o){if(typeof o.jql=="string"&&o.jql.trim().length>0)return o.jql;let t=[];if(no(o.project)&&t.push(`project = ${io(o.project)}`),no(o.status)&&t.push(`status = ${io(o.status)}`),no(o.assignee)&&t.push(`assignee = ${io(o.assignee)}`),no(o.sprintId)){let e=o.sprintId;t.push(typeof e=="number"||/^\d+$/.test(String(e))?`sprint = ${Number(e)}`:`sprint = ${io(e)}`)}if(t.length===0)throw new Error("Jira query requires jql or at least one of project, status, assignee, sprintId");return t.join(" AND ")}function no(o){return o!=null&&o!==""}function io(o){return`"${String(o).replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function ei(o,t){let e=String(o.key??o.id??""),r=o.fields??{},i=Sr(r.description);return{id:e,source:"jira",title:String(r.summary??""),...i?{description:i}:{},status:String(r.status?.name??""),...r.assignee?.displayName?{assignee:String(r.assignee.displayName)}:{},url:`${t.replace(/\/$/,"")}/browse/${e}`,raw:o}}var re,wu,yu,ro,so,jr=p(()=>{"use strict";ti();re="kno.jira.apiToken",wu=50,yu=10,ro=500,so=class{secrets;settings;fetchFn;constructor(t,e,r=fetch){this.secrets=t,this.settings=e,this.fetchFn=r}async get(t){let{baseUrl:e}=await this.requireConfig(),r=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(t)}`);return ei(r,e)}async query(t){let{baseUrl:e}=await this.requireConfig(),r=gu(t),i=[],n,s=new Set;for(let a=0;a<yu&&i.length<ro;a++){let u={jql:r,maxResults:Math.min(wu,ro-i.length),fields:["summary","description","status","assignee"]};n&&(u.nextPageToken=n);let c=await this.request("POST","/rest/api/3/search/jql",{body:u}),f=Array.isArray(c.issues)?c.issues:[];for(let j of f){if(i.length>=ro)break;i.push(ei(j,e))}let m=typeof c.nextPageToken=="string"?c.nextPageToken:void 0;if(c.isLast===!0||!m||f.length===0||m===n||s.has(m))break;s.add(m),n=m}return i}async getComments(t){let e=[],r=0,i=100,n=ro;for(;e.length<n;){let s=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(t)}/comment?startAt=${r}&maxResults=${i}`),a=Array.isArray(s.comments)?s.comments:[];for(let u of a)e.push({id:String(u.id??""),subjectId:t,body:Sr(u.body),...u.author?.displayName?{author:u.author.displayName}:{},createdAt:u.created??"",raw:u});if(r+=a.length,a.length===0||typeof s.total=="number"&&r>=s.total||a.length<i)break}return e}async postComment(t,e){await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(t)}/comment`,{body:{body:Yn(e)}})}async updateStatus(t,e){let r=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(t)}/transitions`),i=Array.isArray(r.transitions)?r.transitions:[],n=e.trim().toLowerCase(),s=i.find(a=>(a.to?.name??"").trim().toLowerCase()===n);if(!s?.id){let a=i.map(c=>c.to?.name).filter(c=>typeof c=="string"&&c.length>0),u=a.length>0?a.join(", "):"(none)";throw new Error(`No Jira transition to status '${e}' from the current state. Available: ${u}`)}await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(t)}/transitions`,{body:{transition:{id:s.id}}})}async requireConfig(){let t=(await this.settings.get()).jira,e=t?.baseUrl?.trim(),r=t?.email?.trim(),i=await this.secrets.get(re),n=[];if(e||n.push("settings.jira.baseUrl"),r||n.push("settings.jira.email"),i||n.push(`SecretStore '${re}'`),n.length>0)throw new Error(`Jira is not configured \u2014 missing ${n.join(", ")}. Set jira.baseUrl and jira.email via PATCH /api/settings, and store the API token with: POST /api/secrets/${re} or npm --workspace apps/engine run set-secret -- ${re} <value>`);return{baseUrl:e,email:r,token:i}}async request(t,e,r={}){let{baseUrl:i,email:n,token:s}=await this.requireConfig(),a=`${i.replace(/\/$/,"")}${e}`,u={Authorization:`Basic ${Buffer.from(`${n}:${s}`).toString("base64")}`,Accept:"application/json"};r.body!==void 0&&(u["Content-Type"]="application/json");let c=await this.fetchFn(a,{method:t,headers:u,...r.body!==void 0?{body:JSON.stringify(r.body)}:{}});if(!c.ok){let m=await c.text().catch(()=>"");throw new Error(`Jira ${t} ${e} failed (${c.status}): ${m||c.statusText}`)}if(c.status===204)return;let f=await c.text();if(f)return JSON.parse(f)}}});function ao(o){let t=o.trim(),e=t.lastIndexOf("#");if(e<=0||e===t.length-1)throw new Error(`Bitbucket pull request id must be '{repoSlug}#{prNumber}' (e.g. 'kno-engine#42'), got '${o}'`);let r=t.slice(0,e),i=t.slice(e+1);if(!/^\d+$/.test(i))throw new Error(`Bitbucket pull request id must be '{repoSlug}#{prNumber}' with a numeric PR number, got '${o}'`);return{repoSlug:r,prNumber:i}}function ju(o,t){return`${o}#${t}`}function _u(o){let t=o.repoSlug;if(typeof t!="string"||t.trim().length===0)throw new Error("Bitbucket query requires filter.repoSlug or filter.role \u2014 repo-scoped listing needs repoSlug; workspace-wide listing needs role (author|reviewer)");return t.trim()}function Iu(o){if(typeof o.repoSlug=="string"&&o.repoSlug.trim().length>0||!ni(o.role))return;let t=String(o.role).trim().toLowerCase();if(t!=="author"&&t!=="reviewer")throw new Error(`Bitbucket query filter.role must be 'author' or 'reviewer', got '${String(o.role)}'`);return t}function ri(o){if(!ni(o))return;let t=String(o).trim().toUpperCase();if(t!=="OPEN"&&t!=="MERGED"&&t!=="DECLINED")throw new Error(`Bitbucket query filter.state must be OPEN, MERGED, or DECLINED, got '${String(o)}'`);return t}function xu(o){if(typeof o.q=="string"&&o.q.trim().length>0)return o.q;let t=ri(o.state);if(t)return`state="${t}"`}function Eu(o){let t=o.destination?.repository?.name;if(typeof t=="string"&&t.trim().length>0)return t.trim();let e=o.destination?.repository?.full_name;if(typeof e=="string"&&e.includes("/"))return e.slice(e.lastIndexOf("/")+1);throw new Error("Bitbucket workspace pull request is missing destination.repository slug")}function vu(o){let t=o.trim().toLowerCase();if(t==="approved")return"approve";if(t==="declined"||t==="rejected")return"decline";if(t==="merged")return"merge";throw new Error(`No Bitbucket action for status '${o}'. Accepted: approved, declined/rejected, merged`)}function ni(o){return o!=null&&o!==""}function oi(o,t){let e=String(o.id??""),r=typeof o.description=="string"?o.description:"";return{id:ju(t,e),source:"bitbucket",title:String(o.title??""),...r?{description:r}:{},sourceBranch:String(o.source?.branch?.name??""),targetBranch:String(o.destination?.branch?.name??""),...o.author?.display_name?{author:o.author.display_name}:{},...o.links?.html?.href?{url:o.links.html.href}:{},raw:o}}function Tu(o,t){let e=o.user?.display_name??o.author?.display_name;return{id:String(o.id??""),subjectId:t,body:o.content?.raw??"",...e?{author:e}:{},createdAt:o.created_on??"",raw:o}}var ne,Su,co,_r=p(()=>{"use strict";ne="kno.bitbucket.apiToken",Su="https://api.bitbucket.org/2.0",co=class{secrets;settings;fetchFn;constructor(t,e,r=fetch){this.secrets=t,this.settings=e,this.fetchFn=r}async get(t){let{repoSlug:e,prNumber:r}=ao(t),{workspace:i}=await this.requireConfig(),n=await this.request("GET",this.prPath(i,e,r));return oi(n,e)}async query(t){let e=Iu(t);if(e)return this.queryWorkspacePullRequests(e,t);let r=_u(t),{baseUrl:i,workspace:n}=await this.requireConfig(),s=xu(t),a=new URLSearchParams({pagelen:String(50)});s&&a.set("q",s);let u=`${i.replace(/\/$/,"")}/repositories/${encodeURIComponent(n)}/${encodeURIComponent(r)}/pullrequests?${a.toString()}`;return this.collectPullRequests(u,r)}async queryWorkspacePullRequests(t,e){let{baseUrl:r,workspace:i,email:n}=await this.requireConfig(),s=new URLSearchParams({pagelen:String(50)}),a=ri(e.state);a&&s.set("state",a),t==="reviewer"&&s.set("role","REVIEWER");let u=`${r.replace(/\/$/,"")}/workspaces/${encodeURIComponent(i)}/pullrequests/${encodeURIComponent(n)}?${s.toString()}`;return this.collectPullRequests(u)}async collectPullRequests(t,e){let r=[],i=new Set,n=t;for(let s=0;s<10&&r.length<500&&!(!n||i.has(n));s++){i.add(n);let a=await this.request("GET",n),u=Array.isArray(a.values)?a.values:[];for(let f of u){if(r.length>=500)break;r.push(oi(f,e??Eu(f)))}let c=typeof a.next=="string"&&a.next.length>0?a.next:void 0;if(!c||u.length===0)break;n=c}return r}async getComments(t){let{repoSlug:e,prNumber:r}=ao(t),{workspace:i}=await this.requireConfig(),n=[],s=new Set,a=`${this.prPath(i,e,r)}/comments?pagelen=50`;for(let u=0;u<10&&n.length<500&&!(!a||s.has(a));u++){s.add(a);let c=await this.request("GET",a),f=Array.isArray(c.values)?c.values:[];for(let j of f)n.push(Tu(j,t));let m=typeof c.next=="string"&&c.next.length>0?c.next:void 0;if(!m||f.length===0)break;a=m}return n}async postComment(t,e){let{repoSlug:r,prNumber:i}=ao(t),{workspace:n}=await this.requireConfig();await this.request("POST",`${this.prPath(n,r,i)}/comments`,{body:{content:{raw:e}}})}async updateStatus(t,e){let{repoSlug:r,prNumber:i}=ao(t),{workspace:n}=await this.requireConfig(),s=vu(e);await this.request("POST",`${this.prPath(n,r,i)}/${s}`)}prPath(t,e,r){return`/repositories/${encodeURIComponent(t)}/${encodeURIComponent(e)}/pullrequests/${encodeURIComponent(r)}`}async requireConfig(){let t=(await this.settings.get()).bitbucket,e=(t?.baseUrl?.trim()||Su).replace(/\/$/,""),r=t?.email?.trim(),i=t?.workspace?.trim(),n=await this.secrets.get(ne),s=[];if(r||s.push("settings.bitbucket.email"),i||s.push("settings.bitbucket.workspace"),n||s.push(`SecretStore '${ne}'`),s.length>0)throw new Error(`Bitbucket is not configured \u2014 missing ${s.join(", ")}. Set bitbucket.email and bitbucket.workspace via PATCH /api/settings, and store the API token with: POST /api/secrets/${ne} or npm --workspace apps/engine run set-secret -- ${ne} <value>`);return{baseUrl:e,email:r,workspace:i,token:n}}async request(t,e,r={}){let{baseUrl:i,email:n,token:s}=await this.requireConfig(),a=e.startsWith("http://")||e.startsWith("https://")?e:`${i}${e.startsWith("/")?e:`/${e}`}`,u={Authorization:`Basic ${Buffer.from(`${n}:${s}`).toString("base64")}`,Accept:"application/json"};r.body!==void 0&&(u["Content-Type"]="application/json");let c=await this.fetchFn(a,{method:t,headers:u,...r.body!==void 0?{body:JSON.stringify(r.body)}:{}});if(!c.ok){let m=await c.text().catch(()=>"");throw new Error(`Bitbucket ${t} ${e} failed (${c.status}): ${m||c.statusText}`)}if(c.status===204)return;let f=await c.text();if(f)return JSON.parse(f)}}});import{Injectable as ku,Logger as Au,Inject as Nu}from"@nestjs/common";async function ii(o){let t=[];for(let e of qu){let r=await o.get(e.secretKey);t.push({providerId:e.providerId,secretKey:e.secretKey,configured:typeof r=="string"&&r.length>0})}return t}async function Cu(o,t){let e=await ii(o);for(let r of e)r.configured||t(`${r.providerId} API key not configured (looked up as '${r.secretKey}'). GET /api/providers/status lists what's missing; store a key with: POST /api/secrets/${r.secretKey} or npm --workspace apps/engine run set-secret -- ${r.secretKey} <value>`)}function si(o={}){let t=o.activeProviders?.agent;if(t==null)return"claude";if(t==="claude"||t==="cursor")return t;throw new Error(`Invalid activeProviders.agent '${String(t)}'. Expected 'claude' or 'cursor'.`)}function ai(o={}){let t=o.activeProviders?.ticket;if(t==null||t==="manual")return"manual";if(t==="jira")return"jira";throw new Error(`Invalid activeProviders.ticket '${String(t)}'. Expected 'jira' or 'manual'.`)}function ci(o={}){let t=o.activeProviders?.repo;if(t==null||t==="manual")return"manual";if(t==="bitbucket")return"bitbucket";throw new Error(`Invalid activeProviders.repo '${String(t)}'. Expected 'bitbucket' or 'manual'.`)}var Ru,Ou,Pu,Ir,qu,kt,xr=p(()=>{"use strict";Tt();jr();_r();Ru=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},Ou=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},Pu=function(o,t){return function(e,r){t(e,r,o)}},qu=[{providerId:"anthropic",secretKey:St("anthropic")},{providerId:"cursor",secretKey:St("cursor")},{providerId:"jira",secretKey:re},{providerId:"bitbucket",secretKey:ne}];kt=Ir=class{secrets;logger=new Au(Ir.name);constructor(t){this.secrets=t}async onModuleInit(){await Cu(this.secrets,t=>this.logger.warn(t))}list(){return ii(this.secrets)}};kt=Ir=Ru([ku(),Pu(0,Nu(ot)),Ou("design:paramtypes",[Function])],kt)});var Wt,h,b,Xt,D=p(()=>{"use strict";Wt=class extends Error{constructor(t){super(t),this.name=this.constructor.name}},h=class extends Wt{httpStatus=404},b=class extends Wt{httpStatus=400},Xt=class extends Wt{httpStatus=409}});function li(o,t){switch(o){case"my-open-prs":return{role:"author",state:"OPEN"};case"reviewing":return{role:"reviewer",state:"OPEN"};case"repo-open-prs":{let e=typeof t.repoSlug=="string"?t.repoSlug.trim():"";if(!e)throw new b("Bitbucket template 'repo-open-prs' requires params.repoSlug");return{repoSlug:e,state:"OPEN"}}default:throw new h(`Unknown Bitbucket query template: ${o}`)}}var ui,pi=p(()=>{"use strict";D();ui=[{id:"my-open-prs",label:"My open pull requests",params:[]},{id:"reviewing",label:"Pull requests I'm reviewing",params:[]},{id:"repo-open-prs",label:"Open pull requests in a repository",params:[{name:"repoSlug",label:"Repository",type:"string",required:!0}]}]});import{Injectable as Bu}from"@nestjs/common";var Du,di,At,Er=p(()=>{"use strict";D();pi();Du=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},di={bitbucket:{list:()=>ui,resolve:li}},At=class{list(t){return di[t]?.list()??[]}resolve(t,e,r){let i=di[t];if(!i)throw new h(`No query templates for provider '${t}'`);let n=i.list().find(s=>s.id===e);if(!n)throw new h(`Unknown query template '${e}' for provider '${t}'`);for(let s of n.params){if(!s.required)continue;let a=r[s.name];if(a==null||typeof a=="string"&&a.trim()==="")throw new b(`Template '${e}' requires params.${s.name}`)}return i.resolve(e,r)}};At=Du([Bu()],At)});import{Module as Lu}from"@nestjs/common";import{fileURLToPath as Uu}from"node:url";import{dirname as Fu,join as Ju}from"node:path";var $u,Mu,Nt,uo=p(()=>{"use strict";Be();wn();Le();yn();Fe();gn();tr();Rn();On();ir();Pn();sr();An();ar();Tt();xe();oo();xr();jr();_r();Er();$u=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},Mu=Ju(Fu(Uu(import.meta.url)),"../../../knowledge"),Nt=class{};Nt=$u([Lu({imports:[Zt,ft],providers:[{provide:Ut,useFactory:async(o,t)=>ai(await t.get())==="jira"?new so(o,t):new $e([]),inject:[ot,U]},{provide:Ft,useFactory:async(o,t)=>ci(await t.get())==="bitbucket"?new co(o,t):new Ue([]),inject:[ot,U]},{provide:Jt,useFactory:()=>new Je([])},{provide:me,useFactory:async(o,t)=>si(await t.get())==="cursor"?new Ke(o):new Xe(o),inject:[ot,U]},{provide:we,useClass:He},{provide:ye,useFactory:()=>new Ge(Mu)},kt,At],exports:[Ut,Ft,Jt,me,we,ye,kt,At]})],Nt)});import{Module as Wu}from"@nestjs/common";var Vu,lo,fi=p(()=>{"use strict";Vu=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},lo=class{};lo=Vu([Wu({})],lo)});import{Injectable as Ku}from"@nestjs/common";var Xu,nt,po=p(()=>{"use strict";Xu=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},nt=class{listeners=new Set;emit(t){for(let e of this.listeners)e(t)}subscribe(t){return this.listeners.add(t),()=>this.listeners.delete(t)}};nt=Xu([Ku()],nt)});import{Global as Gu,Module as zu}from"@nestjs/common";var Hu,qt,fo=p(()=>{"use strict";po();Hu=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},qt=class{};qt=Hu([Gu(),zu({providers:[nt],exports:[nt]})],qt)});import{Injectable as Zu}from"@nestjs/common";import{execFile as tl}from"node:child_process";import{mkdirSync as mi}from"node:fs";import{join as vr}from"node:path";import{promisify as el}from"node:util";function hi(o){return o==null?"":typeof o=="string"?o:o.toString("utf8")}function bi(o){return vr(o,"worktrees")}var Qu,Yu,ol,It,Tr=p(()=>{"use strict";Qu=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},Yu=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},ol=el(tl),It=class{worktreesRoot;constructor(t){this.worktreesRoot=t,mi(this.worktreesRoot,{recursive:!0})}async createWorktree(t,e){let r=e.worktreePath??vr(this.worktreesRoot,t);return mi(vr(r,".."),{recursive:!0}),await this.git(e.repoPath,["worktree","add","-b",e.branchName,r,e.baseBranch]),{worktreePath:r,branch:e.branchName}}async checkout(t,e){await this.git(t,["checkout",e.branch])}async createBranch(t,e){e.baseBranch?await this.git(t,["checkout","-b",e.branchName,e.baseBranch]):await this.git(t,["checkout","-b",e.branchName])}async commit(t,e){return e.addAll!==!1&&await this.git(t,["add","-A"]),await this.git(t,["commit","-m",e.message]),{sha:(await this.git(t,["rev-parse","HEAD"])).stdout.trim()}}async push(t,e={}){let r=e.remote??"origin";e.branch?await this.git(t,["push",r,e.branch]):await this.git(t,["push",r,"HEAD"])}async git(t,e){try{let r=await ol("git",e,{cwd:t,encoding:"utf8",windowsHide:!0});return{stdout:r.stdout??"",stderr:r.stderr??""}}catch(r){let i=r,n=hi(i.stderr),s=hi(i.stdout),a=n||s||i.message||"unknown git error";throw new Error(`git ${e.join(" ")} failed (cwd=${t}, code=${String(i.code??"?")}): ${a}`)}}};It=Qu([Zu(),Yu("design:paramtypes",[String])],It)});import{Module as nl}from"@nestjs/common";import{mkdirSync as il}from"node:fs";import{dirname as sl,join as al}from"node:path";import{fileURLToPath as cl}from"node:url";var rl,wi,mo,yi=p(()=>{"use strict";Tr();rl=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},wi=al(sl(cl(import.meta.url)),"../../data");il(wi,{recursive:!0});mo=class{};mo=rl([nl({providers:[{provide:It,useFactory:()=>new It(bi(wi))}],exports:[It]})],mo)});function ho(o,t){return o.replace(/\{\{\s*([^}]+?)\s*\}\}/g,(e,r)=>{let i=ul(t,r.trim());return i==null?"":typeof i=="string"?i:JSON.stringify(i)})}function ul(o,t){let e=t.split(".").filter(Boolean),r=o;for(let i of e){if(r==null||typeof r!="object")return;r=r[i]}return r}function Ee(o,t){return typeof o=="string"?ho(o,t):Array.isArray(o)?o.map(e=>Ee(e,t)):o&&typeof o=="object"?Object.fromEntries(Object.entries(o).map(([e,r])=>[e,Ee(r,t)])):o}var gi=p(()=>{"use strict"});function Si(o,t){switch(o){case"questionnaire":return Rr(t);case"confirmation":return ll(t);case"conversation":return pl(t);default:return o}}function Rr(o){if(typeof o=="string"&&o.trim())return[o.trim()];if(!o||typeof o!="object")return[];let t=o.questions;return Array.isArray(t)?t.map(e=>typeof e=="string"?e.trim():e&&typeof e=="object"&&"prompt"in e?String(e.prompt).trim():"").filter(Boolean):[]}function ll(o){if(typeof o=="string"&&o.trim())return[o.trim()];if(!o||typeof o!="object")return[];let t=o;for(let e of["prompt","message","summary","question"]){let r=t[e];if(typeof r=="string"&&r.trim())return[r.trim()]}return"approved"in t&&!("questions"in t)?[]:Rr(o)}function pl(o){if(typeof o=="string"&&o.trim())return[o.trim()];if(!o||typeof o!="object")return[];let t=o;for(let e of["prompt","message","text"]){let r=t[e];if(typeof r=="string"&&r.trim())return[r.trim()]}return"suggestions"in t?[]:"questions"in t?Rr(o):[]}var ji=p(()=>{"use strict"});function ie(o,t){for(let e of o){if(e.id===t)return e;if(e.iterations)for(let r of e.iterations){let i=ie(r.stepExecutions,t);if(i)return i}}}function ve(o,t,e,r){for(let i=0;i<o.length;i++){let n=o[i];if(n.id===t)return{execution:n,siblings:o,index:i,parentLoopExecutionId:e,iterationIndex:r};if(n.iterations)for(let s of n.iterations){let a=ve(s.stepExecutions,t,n.id,s.index);if(a)return a}}}function F(o,t,e){return o.map(r=>r.id===t?e(r):r.iterations?{...r,iterations:r.iterations.map(i=>({...i,stepExecutions:F(i.stepExecutions,t,e)}))}:r)}function Or(o,t,e,r){return e==null?[...o,t]:o.map(i=>{if(i.id===e){let n=[...i.iterations??[]],s=n.find(a=>a.index===r);if(s){let a={...s,stepExecutions:[...s.stepExecutions,t]},u=n.findIndex(c=>c.index===r);n[u]=a}else{let a={index:r,stepExecutions:[t],startedAt:t.startedAt??new Date().toISOString()};n.push(a),n.sort((u,c)=>u.index-c.index)}return{...i,iterations:n}}return i.iterations?{...i,iterations:i.iterations.map(n=>({...n,stepExecutions:Or(n.stepExecutions,t,e,r)}))}:i})}function Te(o,t){for(let e of o){if(e.id===t)return e;if(e.type==="loop"){let r=Te(e.steps,t);if(r)return r}}}function _i(o,t,e){return F(o,t,r=>{let i=(r.iterations??[]).map(n=>{if(n.index!==e)return n;let s=n.stepExecutions.every(a=>a.completedAt)?n.stepExecutions.map(a=>a.completedAt).reduce((a,u)=>a>u?a:u):void 0;return{...n,...s?{completedAt:s}:{}}});return{...r,iterations:i}})}var Ii=p(()=>{"use strict"});import{z as H}from"zod";function xi(o,t){let e=bl[o].safeParse(t);if(!e.success){let r=e.error.issues.map(i=>`${i.path.length?i.path.join("."):"(root)"}: ${i.message}`).join("; ");throw new Error(`Agent output failed validation for format '${o}': ${r}`)}return e.data}var dl,fl,ml,hl,bl,Ei=p(()=>{"use strict";dl=H.object({questions:H.array(H.object({id:H.string(),prompt:H.string()}))}),fl=H.object({approved:H.boolean()}),ml=H.object({suggestions:H.array(H.object({body:H.string()}))}),hl=H.string(),bl={questionnaire:dl,confirmation:fl,comment_suggestions:ml,free_text:hl}});function vi(o){return o==="completed"||o==="failed"||o==="cancelled"}function Pr(o,t){let e=new Map;for(let i of o){let n=t(i);if(n==null)continue;let s=e.get(n)??[];s.push(i),e.set(n,s)}if(e.size===0)return null;let r=[];for(let i of e.values()){let n=new Set(i.map(a=>a.retryOf).filter(a=>a!=null)),s=i.find(a=>!n.has(a.id));if(!s)return null;r.push(s)}return{activeJobs:r,allTerminal:r.every(i=>vi(i.status)),groupCount:e.size}}function Ti(o){let t=o.every(r=>r.status==="completed"),e=o.every(r=>r.status==="failed"||r.status==="cancelled");return t?"completed":e?"failed":"completed_with_issues"}var Ri=p(()=>{"use strict"});async function bo(o,t,e){let r=await t.get(o);if(!r)throw new h(`SubjectView not found: ${o}`);if(r.subjectType==="ticket")return(await e.tickets.query(r.query)).map(n=>({subjectType:"ticket",...n}));if(r.subjectType==="pull_request")return(await e.repo.query(r.query)).map(n=>({subjectType:"pull_request",...n}));if(r.subjectType==="documentation")return(await e.documentation.query(r.query)).map(n=>({subjectType:"documentation",...n}));throw new b(`Unsupported subjectType on view: ${r.subjectType}`)}var kr=p(()=>{"use strict";D()});import{Inject as z,Injectable as gl}from"@nestjs/common";import{randomUUID as Ar}from"node:crypto";import{exec as Sl}from"node:child_process";import{promisify as jl}from"node:util";function Oi(o,t){let e=t[o.stepId];if(e==null||typeof e!="object")return o.type==="field_empty";let r=e[o.field];return o.type==="field_empty"?r==null?!0:typeof r=="string"||Array.isArray(r)?r.length===0:!1:r===o.value}function xl(o,t){let e=i=>{let n=[];for(let s of i)n.push(s),s.type==="loop"&&n.push(...e(s.steps));return n},r=i=>{let n=i.findIndex(s=>s.id===t);if(n>=0){for(let s=n-1;s>=0;s--)if(i[s].type==="agent")return i[s].id;return}for(let s of i)if(s.type==="loop"){let a=r(s.steps);if(a!==void 0||s.steps.some(u=>u.id===t))return a}};return r(o.steps)}function wo(o){let t={...o.context};return o.subjectContext?.mode==="single"&&(t.subject=o.subjectContext.subject),o.worktreePath&&(t.worktreePath=o.worktreePath),o.branch&&(t.branch=o.branch),t}function yo(o){if(!o.worktreePath)throw new Error(`Job ${o.id} has no worktreePath; run create_worktree first`);return o.worktreePath}function mt(o,t){let e=o[t];if(typeof e!="string"||e.length===0)throw new Error(`Missing required string param '${t}'`);return e}function El(o){if(o==="none")throw new Error("normalizeAppliesTo called with none");if(Array.isArray(o)){if(o.length!==1)throw new Error(`Workflow Runner requires appliesTo to be a single SubjectType (got ${JSON.stringify(o)})`);return o[0]}return o}function Pi(o,t){for(let e of o)if(e.required&&(t[e.name]===void 0||t[e.name]===null))throw new b(`Missing required input: ${e.name}`)}var wl,yl,G,_l,Il,it,go=p(()=>{"use strict";ee();oe();eo();to();po();tr();Be();Le();Fe();ir();sr();Tr();D();gi();ji();Ii();Ei();Ri();kr();wl=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},yl=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},G=function(o,t){return function(e,r){t(e,r,o)}},_l=jl(Sl),Il=["user","organization","project"],it=class{workflows;jobs;batches;views;events;tickets;repo;documentation;agent;notifications;knowledge;git;childTerminalLocks=new Set;batchTerminalLocks=new Set;constructor(t,e,r,i,n,s,a,u,c,f,m,j){this.workflows=t,this.jobs=e,this.batches=r,this.views=i,this.events=n,this.tickets=s,this.repo=a,this.documentation=u,this.agent=c,this.notifications=f,this.knowledge=m,this.git=j,this.events.subscribe(g=>{let R=g;(R.type==="job_completed"||R.type==="job_failed")&&this.onChildTerminal(R.jobId)})}async start(t){let e=await this.createJob(t);return this.emit({type:"job_started",jobId:e.id,timestamp:new Date().toISOString()}),this.runJob(e.id)}async launch(t){let e=await this.requireWorkflow(t.workflowId);if(e.cardinality==="single")throw new b("launch() does not support cardinality 'single'; use start() with a subjectId");if(e.cardinality!=="batch"&&e.cardinality!=="aggregate")throw new b(`Unsupported cardinality: ${e.cardinality}`);Pi(e.inputSchema,t.inputValues);let r=await this.resolveSelection(t.selection);if(e.cardinality==="aggregate"){let a=await this.createJob({workflowId:e.id,subjectContext:{mode:"collection",subjects:r},selection:t.selection,inputValues:t.inputValues});return this.emit({type:"job_started",jobId:a.id,timestamp:new Date().toISOString()}),this.runJob(a.id)}let i=new Date().toISOString(),n=await this.batches.create({id:Ar(),workflowId:e.id,selection:t.selection,resolvedSubjects:r,status:"running",triggeredBy:t.triggeredBy,...t.notificationOverride?{notificationOverride:t.notificationOverride}:{},notificationSent:!1,createdAt:i}),s=[];for(let a=0;a<r.length;a++){let u=r[a],c=await this.createJob({workflowId:e.id,subjectContext:{mode:"single",subject:u},selection:t.selection,batchId:n.id,fanOutIndex:a,inputValues:t.inputValues});s.push(c)}for(let a of s)this.emit({type:"job_started",jobId:a.id,timestamp:new Date().toISOString()}),await this.runJob(a.id);return await this.batches.get(n.id)}async createJob(t){let e=await this.workflows.get(t.workflowId);if(!e)throw new h(`Workflow not found: ${t.workflowId}`);if(!t.subjectContext&&e.cardinality!=="single")throw new b(`Workflow Runner only supports cardinality 'single' at start() without an explicit subjectContext (got '${e.cardinality}')`);Pi(e.inputSchema,t.inputValues);let r=t.subjectContext??await this.resolveSubjectContext(e,t.subjectId),i=new Date().toISOString();return this.jobs.create({id:Ar(),workflowId:e.id,status:"pending",...r?{subjectContext:r}:{},...t.selection?{selection:t.selection}:{},...t.batchId?{batchId:t.batchId}:{},...t.parentJobId?{parentJobId:t.parentJobId}:{},...t.parentStepExecutionId?{parentStepExecutionId:t.parentStepExecutionId}:{},...t.fanOutIndex!=null?{fanOutIndex:t.fanOutIndex}:{},...t.retryOf?{retryOf:t.retryOf}:{},context:{...t.inputValues},stepHistory:[],createdAt:i,updatedAt:i})}async runJob(t){let e=await this.jobs.get(t);if(!e)throw new h(`Job not found: ${t}`);let r=await this.requireWorkflow(e.workflowId);e.status==="pending"&&(e=await this.persistJob({...e,status:"planning",updatedAt:new Date().toISOString()}));let i=await this.executeStepSequence(e,r,r.steps,void 0,void 0,0);return i.outcome==="paused"||i.outcome==="failed"?i.job:this.completeJob(i.job,r)}async resume(t,e){let r=await this.jobs.get(t);if(!r)throw new h(`Job not found: ${t}`);if(r.status!=="waiting_for_human")throw new Xt(`Job ${t} is not waiting for human input (status: ${r.status})`);let i=await this.requireWorkflow(r.workflowId),n=r.currentStepExecutionId;if(!n)throw new Error(`Job ${t} is waiting_for_human but has no currentStepExecutionId`);let s=ie(r.stepHistory,n);if(!s)throw new Error(`Paused execution ${n} not found on job ${t}`);if(s.type==="loop")return this.resumeAskHuman(r,i,s,e);if(s.type!=="interaction")throw new Error(`Paused execution ${n} has type '${s.type}'; expected interaction or loop`);let a=new Date().toISOString(),u=F(r.stepHistory,n,R=>({...R,status:"completed",completedAt:a,output:e})),c=e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{response:e};r=await this.persistJob({...r,status:"planning",context:{...r.context,[s.stepDefinitionId]:e},stepHistory:u,currentStepId:void 0,currentStepExecutionId:void 0,updatedAt:a}),this.emit({type:"human_answered",jobId:r.id,answers:c,timestamp:a});let f=ve(r.stepHistory,n);if(!f)throw new Error(`Could not locate frame for execution ${n}`);let m=this.sequenceForFrameOnJob(r,i,f),j=f.index+1,g=await this.executeStepSequence(r,i,m,f.parentLoopExecutionId,f.iterationIndex,j);return g.outcome==="paused"||g.outcome==="failed"?g.job:f.parentLoopExecutionId!=null&&f.iterationIndex!=null?this.continueLoopAfterBody(g.job,i,f.parentLoopExecutionId,f.iterationIndex):this.completeJob(g.job,i)}async retryFailedJob(t){let e=await this.jobs.get(t);if(!e)throw new h(`Job not found: ${t}`);if(e.status!=="failed")throw new Xt(`Job ${t} is not failed (status: ${e.status})`);let r=e.parentJobId!=null&&e.parentStepExecutionId!=null&&e.fanOutIndex!=null,i=e.batchId!=null&&e.fanOutIndex!=null;if(!r&&!i)throw new b(`Job ${t} is not a retryable sub_workflow child or batch member`);if(r){let a=await this.jobs.get(e.parentJobId);if(!a)throw new h(`Parent job not found: ${e.parentJobId}`);let u=await this.createJob({workflowId:e.workflowId,subjectContext:e.subjectContext,inputValues:{},parentJobId:e.parentJobId,parentStepExecutionId:e.parentStepExecutionId,fanOutIndex:e.fanOutIndex,retryOf:e.id}),c=F(a.stepHistory,e.parentStepExecutionId,f=>({...f,status:"waiting_for_children",error:void 0,completedAt:void 0,childJobIds:[...f.childJobIds??[],u.id]}));return a=await this.persistJob({...a,status:"waiting_for_children",stepHistory:c,completedAt:void 0,updatedAt:new Date().toISOString()}),this.emit({type:"job_started",jobId:u.id,timestamp:new Date().toISOString()}),this.emit({type:"job_retried",jobId:u.id,retryOf:e.id,timestamp:new Date().toISOString()}),this.runJob(u.id),u}let n=await this.batches.get(e.batchId);if(!n)throw new h(`JobBatch not found: ${e.batchId}`);n.status!=="running"&&await this.batches.update(n.id,{status:"running",completedAt:null,notificationSent:!1});let s=await this.createJob({workflowId:e.workflowId,subjectContext:e.subjectContext,selection:e.selection,batchId:e.batchId,fanOutIndex:e.fanOutIndex,inputValues:{},retryOf:e.id});return this.emit({type:"job_started",jobId:s.id,timestamp:new Date().toISOString()}),this.emit({type:"job_retried",jobId:s.id,retryOf:e.id,timestamp:new Date().toISOString()}),this.runJob(s.id),s}async executeStepSequence(t,e,r,i,n,s){let a=t;for(let u=s;u<r.length;u++){let c=r[u],f=new Date().toISOString(),m={id:Ar(),stepDefinitionId:c.id,type:c.type,status:"running",startedAt:f},j=Or(a.stepHistory,m,i,n);a=await this.persistJob({...a,status:a.status==="pending"?"planning":a.status,currentStepId:c.id,currentStepExecutionId:m.id,stepHistory:j,updatedAt:f}),this.emit({type:"step_started",jobId:a.id,stepDefinitionId:c.id,timestamp:f});try{let g=await this.dispatchStep(a,e,c,m.id,i,n);if(a=g.job,g.outcome==="paused"||g.outcome==="failed")return g}catch(g){return{outcome:"failed",job:await this.failJob(a,e,m.id,c.id,g)}}}return i!=null&&n!=null&&(a=await this.persistJob({...a,stepHistory:_i(a.stepHistory,i,n),updatedAt:new Date().toISOString()})),{outcome:"completed",job:a}}async dispatchStep(t,e,r,i,n,s){switch(r.type){case"agent":return{outcome:"completed",job:await this.executeAgentStep(t,r,i)};case"interaction":return{outcome:"paused",job:await this.pauseForInteraction(t,e,r,i)};case"git":return{outcome:"completed",job:await this.executeGitStep(t,r,i)};case"provider_action":return{outcome:"completed",job:await this.executeProviderActionStep(t,r,i)};case"shell":return{outcome:"completed",job:await this.executeShellStep(t,r,i)};case"loop":return this.runLoopStep(t,e,r,i,n,s);case"sub_workflow":return this.runSubWorkflowStep(t,r,i);default:{let a=r;throw new b(`Step type '${a.type}' not yet supported by the Workflow Runner`)}}}async runLoopStep(t,e,r,i,n,s,a=0,u=r.maxIterations){let c=t,f=a;for(;;){if(f>=u)switch(r.onMaxIterations.action){case"fail":return c=await this.failExecution(c,e,i,r.id,`Loop '${r.id}' exceeded maxIterations (${u})`),{outcome:"failed",job:c};case"continue":return c=await this.finishExecution(c,i,r.id,{iterations:f,exitedOnMaxIterations:!0}),{outcome:"completed",job:c};case"ask_human":{let j={maxIterationsCheckpoint:!0,nextIteration:f,effectiveMaxIterations:u},g=new Date().toISOString(),R=F(c.stepHistory,i,k=>({...k,status:"pending",output:j}));return c=await this.persistJob({...c,status:"waiting_for_human",currentStepId:r.id,currentStepExecutionId:i,stepHistory:R,updatedAt:g}),this.emit({type:"waiting_for_human",jobId:c.id,stepDefinitionId:r.id,interaction:"confirmation",data:j,questions:[`Loop '${r.id}' reached maxIterations (${u}). Extend, continue, or cancel?`],timestamp:g}),e.notificationPolicy.triggers.includes("on_needs_input")&&await this.notifications.send({title:`Input needed: ${e.name}`,body:`Job ${c.id} hit max iterations on loop '${r.id}'`,jobId:c.id}),{outcome:"paused",job:c}}default:{let j=r.onMaxIterations;throw new Error(`Unknown onMaxIterations action: ${JSON.stringify(j)}`)}}let m=await this.executeStepSequence(c,e,r.steps,i,f,0);if(c=m.job,m.outcome==="paused")return m;if(m.outcome==="failed")return c=await this.failExecution(c,e,i,r.id,"Loop body failed"),{outcome:"failed",job:c};if(Oi(r.until,c.context))return c=await this.finishExecution(c,i,r.id,{iterations:f+1}),{outcome:"completed",job:c};f+=1}}async resumeAskHuman(t,e,r,i){let n=i,s=r.output;if(!s?.maxIterationsCheckpoint)throw new Error(`Loop execution ${r.id} is not at an ask_human checkpoint`);let a=Te(e.steps,r.stepDefinitionId);if(!a||a.type!=="loop")throw new Error(`Loop step definition '${r.stepDefinitionId}' not found`);let u=ve(t.stepHistory,r.id),c=new Date().toISOString();if(n.action==="cancel")return await this.failExecution({...t,status:"planning",currentStepId:void 0,currentStepExecutionId:void 0,updatedAt:c},e,r.id,a.id,"Loop cancelled by human at maxIterations checkpoint");if(n.action==="continue"){let R=await this.persistJob({...t,status:"planning",currentStepId:void 0,currentStepExecutionId:void 0,stepHistory:F(t.stepHistory,r.id,k=>({...k,status:"completed",completedAt:c,output:{iterations:s.nextIteration,exitedOnMaxIterations:!0,humanAction:"continue"}})),updatedAt:c});return this.emit({type:"human_answered",jobId:R.id,answers:n,timestamp:c}),this.emit({type:"step_completed",jobId:R.id,stepDefinitionId:a.id,timestamp:c}),u?.parentLoopExecutionId!=null&&u.iterationIndex!=null?this.continueLoopAfterBody(R,e,u.parentLoopExecutionId,u.iterationIndex):this.continueTopLevelAfter(R,e,a.id)}let f=typeof n.additionalIterations=="number"?n.additionalIterations:0,m=s.effectiveMaxIterations+f,j=await this.persistJob({...t,status:"planning",currentStepId:void 0,currentStepExecutionId:void 0,stepHistory:F(t.stepHistory,r.id,R=>({...R,status:"running",output:void 0})),updatedAt:c});this.emit({type:"human_answered",jobId:j.id,answers:n,timestamp:c});let g=await this.runLoopStep(j,e,a,r.id,u?.parentLoopExecutionId,u?.iterationIndex,s.nextIteration,m);return g.outcome==="paused"||g.outcome==="failed"?g.job:u?.parentLoopExecutionId!=null&&u.iterationIndex!=null?this.continueLoopAfterBody(g.job,e,u.parentLoopExecutionId,u.iterationIndex):this.continueTopLevelAfter(g.job,e,a.id)}async continueLoopAfterBody(t,e,r,i){let n=ie(t.stepHistory,r);if(!n)throw new Error(`Loop execution ${r} not found`);let s=Te(e.steps,n.stepDefinitionId);if(!s||s.type!=="loop")throw new Error(`Loop step '${n.stepDefinitionId}' not found`);let a=ve(t.stepHistory,r),u=n.output?.effectiveMaxIterations??s.maxIterations,c=t;if(Oi(s.until,c.context))c=await this.finishExecution(c,r,s.id,{iterations:i+1});else{let f=i+1,m=await this.runLoopStep(c,e,s,r,a?.parentLoopExecutionId,a?.iterationIndex,f,u);if(m.outcome==="paused"||m.outcome==="failed")return m.job;c=m.job}return a?.parentLoopExecutionId!=null&&a.iterationIndex!=null?this.continueLoopAfterBody(c,e,a.parentLoopExecutionId,a.iterationIndex):this.continueTopLevelAfter(c,e,s.id)}async continueTopLevelAfter(t,e,r){let i=e.steps.findIndex(s=>s.id===r),n=await this.executeStepSequence(t,e,e.steps,void 0,void 0,i+1);return n.outcome==="paused"||n.outcome==="failed"?n.job:this.completeJob(n.job,e)}sequenceForFrameOnJob(t,e,r){if(r.parentLoopExecutionId==null)return e.steps;let i=ie(t.stepHistory,r.parentLoopExecutionId);if(!i)throw new Error(`Parent loop execution ${r.parentLoopExecutionId} not found`);let n=Te(e.steps,i.stepDefinitionId);if(!n||n.type!=="loop")throw new Error(`Parent loop step '${i.stepDefinitionId}' not found`);return n.steps}async runSubWorkflowStep(t,e,r){if(!t.subjectContext||t.subjectContext.mode!=="collection")throw new b(`sub_workflow steps require subjectContext.mode === 'collection' (job ${t.id})`);let i=t.subjectContext.subjects,n=[];for(let f=0;f<i.length;f++){let m=i[f],j=await this.createJob({workflowId:e.workflowId,subjectContext:{mode:"single",subject:m},inputValues:{},parentJobId:t.id,parentStepExecutionId:r,fanOutIndex:f});n.push(j)}let s=n.map(f=>f.id),a=new Date().toISOString(),u=F(t.stepHistory,r,f=>({...f,status:"waiting_for_children",childJobIds:s})),c=await this.persistJob({...t,status:"waiting_for_children",currentStepId:e.id,currentStepExecutionId:r,stepHistory:u,updatedAt:a});for(let f of n)this.emit({type:"job_started",jobId:f.id,timestamp:a}),this.runJob(f.id);return{outcome:"paused",job:c}}async onChildTerminal(t){let e=await this.jobs.get(t);if(!e?.parentJobId||!e.parentStepExecutionId)return;let r=`${e.parentJobId}:${e.parentStepExecutionId}`;if(!this.childTerminalLocks.has(r)){this.childTerminalLocks.add(r);try{let i=(await this.jobs.list({parentJobId:e.parentJobId,parentStepExecutionId:e.parentStepExecutionId})).filter(k=>k.parentStepExecutionId===e.parentStepExecutionId),n=Pr(i,k=>k.fanOutIndex);if(!n?.allTerminal)return;let{activeJobs:s}=n,a=await this.jobs.get(e.parentJobId);if(!a||a.status!=="waiting_for_children"&&a.status!=="failed")return;let u=await this.requireWorkflow(a.workflowId),c=e.parentStepExecutionId,f=ie(a.stepHistory,c);if(!f||f.type!=="sub_workflow")return;if(s.some(k=>k.status==="failed")){await this.failExecution(a,u,c,f.stepDefinitionId,"One or more child jobs failed");return}let j=s.slice().sort((k,xa)=>(k.fanOutIndex??0)-(xa.fanOutIndex??0)).map(k=>({fanOutIndex:k.fanOutIndex,jobId:k.id,output:k.context})),g=new Date().toISOString();a=await this.persistJob({...a,status:"planning",context:{...a.context,[f.stepDefinitionId]:j},currentStepId:void 0,currentStepExecutionId:void 0,stepHistory:F(a.stepHistory,c,k=>({...k,status:"completed",completedAt:g,output:j})),completedAt:void 0,updatedAt:g}),this.emit({type:"step_completed",jobId:a.id,stepDefinitionId:f.stepDefinitionId,timestamp:g});let R=await this.continueTopLevelAfter(a,u,f.stepDefinitionId)}finally{this.childTerminalLocks.delete(r)}}}async onBatchMemberTerminal(t){let e=await this.jobs.get(t);if(!e?.batchId)return;let r=e.batchId;if(!this.batchTerminalLocks.has(r)){this.batchTerminalLocks.add(r);try{let i=await this.batches.get(e.batchId);if(!i||i.status!=="running")return;let n=await this.jobs.list({batchId:i.id}),s=Pr(n,m=>m.fanOutIndex);if(!s||s.groupCount!==i.resolvedSubjects.length||!s.allTerminal)return;let{activeJobs:a}=s,u=Ti(a),c=new Date().toISOString(),f=await this.batches.update(i.id,{status:u,completedAt:c});if(!f)return;if(this.emit({type:"batch_completed",batchId:f.id,summary:a.map(m=>({jobId:m.id,status:m.status})),timestamp:c}),!f.notificationSent){let m=await this.requireWorkflow(f.workflowId),j=f.notificationOverride??m.notificationPolicy,g=u==="completed"?"on_complete":"on_fail";j.triggers.includes(g)&&await this.notifications.send({title:`Batch ${u}: ${m.name}`,body:`JobBatch ${f.id} finished with status '${u}' (${a.length} members)`,batchId:f.id}),await this.batches.update(f.id,{notificationSent:!0})}}finally{this.batchTerminalLocks.delete(r)}}}async resolveSelection(t){if(t.mode==="view")return bo(t.viewId,this.views,{tickets:this.tickets,repo:this.repo,documentation:this.documentation});let e=[];for(let r of t.subjectIds)if(t.subjectType==="ticket"){let i=await this.tickets.get(r);e.push({subjectType:"ticket",...i})}else if(t.subjectType==="pull_request"){let i=await this.repo.get(r);e.push({subjectType:"pull_request",...i})}else if(t.subjectType==="documentation"){let i=await this.documentation.get(r);e.push({subjectType:"documentation",...i})}else throw new b(`Unsupported subjectType: ${t.subjectType}`);return e}async executeAgentStep(t,e,r){let i=e.knowledgeScope?.length?e.knowledgeScope:Il,n=await this.resolveKnowledge(i),s=wo(t),a=ho(e.objective,s),u=await this.agent.run({objective:a,outputFormat:e.outputFormat,knowledge:n,context:{...s,stepId:e.id},...t.worktreePath?{cwd:t.worktreePath}:{}}),c=xi(e.outputFormat,u.parsed);return this.finishExecution(t,r,e.id,c)}async executeGitStep(t,e,r){let i=Ee(e.params,wo(t));switch(e.operation){case"create_worktree":{let n=await this.git.createWorktree(t.id,{repoPath:mt(i,"repoPath"),baseBranch:mt(i,"baseBranch"),branchName:mt(i,"branchName"),...typeof i.worktreePath=="string"?{worktreePath:i.worktreePath}:{}});return this.finishExecution(t,r,e.id,n,{worktreePath:n.worktreePath,branch:n.branch})}case"create_branch":{let n=yo(t),s=mt(i,"branchName");return await this.git.createBranch(n,{branchName:s,...typeof i.baseBranch=="string"?{baseBranch:i.baseBranch}:{}}),this.finishExecution(t,r,e.id,{branch:s},{branch:s})}case"checkout":{let n=yo(t),s=mt(i,"branch");return await this.git.checkout(n,{branch:s}),this.finishExecution(t,r,e.id,{branch:s},{branch:s})}case"commit":{let n=yo(t),s=await this.git.commit(n,{message:mt(i,"message"),addAll:i.addAll!==!1});return this.finishExecution(t,r,e.id,s)}case"push":{let n=yo(t);return await this.git.push(n,{...typeof i.remote=="string"?{remote:i.remote}:{},...typeof i.branch=="string"?{branch:i.branch}:{}}),this.finishExecution(t,r,e.id,{remote:typeof i.remote=="string"?i.remote:"origin",branch:typeof i.branch=="string"?i.branch:t.branch})}default:{let n=e.operation;throw new Error(`Unknown git operation: ${n}`)}}}async executeProviderActionStep(t,e,r){if(!t.subjectContext||t.subjectContext.mode!=="single")throw new b(`provider_action steps require subjectContext.mode === 'single' (job ${t.id})`);let i=t.subjectContext.subject,n=i.id,s=Ee(e.params??{},wo(t))??{},a;if(i.subjectType==="documentation")switch(e.action){case"get_subject":a=await this.documentation.get(n);break;case"get_content":a=await this.documentation.getContent(n);break;case"get_comments":a=await this.documentation.getComments(n);break;case"post_comment":await this.documentation.postComment(n,mt(s,"body")),a={posted:!0};break;case"update_status":throw new Error(`Provider action '${e.action}' is not valid for subject type 'documentation'`);default:{let u=e.action;throw new Error(`Unknown provider action: ${u}`)}}else{let u=i.subjectType==="ticket"?this.tickets:i.subjectType==="pull_request"?this.repo:null;if(!u)throw new Error(`Unsupported subjectType for provider_action: ${i.subjectType}`);switch(e.action){case"get_subject":a=await u.get(n);break;case"get_comments":a=await u.getComments(n);break;case"post_comment":await u.postComment(n,mt(s,"body")),a={posted:!0};break;case"update_status":await u.updateStatus(n,mt(s,"status")),a={status:mt(s,"status")};break;case"get_content":throw new Error(`Provider action 'get_content' is not valid for subject type '${i.subjectType}'`);default:{let c=e.action;throw new Error(`Unknown provider action: ${c}`)}}}return this.finishExecution(t,r,e.id,a)}async executeShellStep(t,e,r){let i=ho(e.command,wo(t)),n=t.worktreePath??process.cwd();try{let s=await _l(i,{cwd:n,windowsHide:!0});return this.finishExecution(t,r,e.id,{exitCode:0,stdout:String(s.stdout??""),stderr:String(s.stderr??"")})}catch(s){let a=s,u=a.stderr??"",c=a.stdout??"",f=typeof a.code=="number"?a.code:Number.parseInt(String(a.code??"1"),10)||1;throw new Error(`shell command failed (exit ${f}, cwd=${n}): ${u||c||a.message||i}`)}}async pauseForInteraction(t,e,r,i){let n=new Date().toISOString(),s=xl(e,r.id),a=s!=null?t.context[s]:void 0,u=F(t.stepHistory,i,j=>({...j,status:"pending"})),c=await this.persistJob({...t,status:"waiting_for_human",currentStepId:r.id,currentStepExecutionId:i,stepHistory:u,updatedAt:n}),f=Si(r.interaction,a);return this.emit({type:"waiting_for_human",jobId:c.id,stepDefinitionId:r.id,interaction:r.interaction,data:a,questions:f,timestamp:n}),e.notificationPolicy.triggers.includes("on_needs_input")&&r.notify!==!1&&await this.notifications.send({title:`Input needed: ${e.name}`,body:`Job ${c.id} is waiting for human input on step '${r.id}'`,jobId:c.id}),c}async finishExecution(t,e,r,i,n={}){let s=new Date().toISOString(),a=F(t.stepHistory,e,c=>({...c,status:"completed",completedAt:s,output:i})),u=await this.persistJob({...t,...n,context:{...t.context,[r]:i},stepHistory:a,updatedAt:s});return this.emit({type:"step_completed",jobId:u.id,stepDefinitionId:r,timestamp:s}),u}async failExecution(t,e,r,i,n){return this.failJob(t,e,r,i,new Error(n))}async completeJob(t,e){let r=new Date().toISOString(),i=await this.persistJob({...t,status:"completed",currentStepId:void 0,currentStepExecutionId:void 0,completedAt:r,updatedAt:r});return this.emit({type:"job_completed",jobId:i.id,timestamp:r}),await this.onBatchMemberTerminal(i.id),!i.batchId&&e.notificationPolicy.triggers.includes("on_complete")&&await this.notifications.send({title:`Job completed: ${e.name}`,body:`Job ${i.id} completed successfully`,jobId:i.id}),i}async failJob(t,e,r,i,n){let s=n instanceof Error?n.message:String(n),a=new Date().toISOString(),u=F(t.stepHistory,r,f=>({...f,status:"failed",completedAt:a,error:s})),c=await this.persistJob({...t,status:"failed",stepHistory:u,completedAt:a,updatedAt:a});return this.emit({type:"step_failed",jobId:c.id,stepDefinitionId:i,error:s,timestamp:a}),this.emit({type:"job_failed",jobId:c.id,error:s,timestamp:a}),await this.onBatchMemberTerminal(c.id),!c.batchId&&e.notificationPolicy.triggers.includes("on_fail")&&await this.notifications.send({title:`Job failed: ${e.name}`,body:`Job ${c.id} failed on step '${i}': ${s}`,jobId:c.id}),c}async resolveSubjectContext(t,e){if(t.appliesTo==="none")return;let r=El(t.appliesTo);if(!e)throw new Error(`Workflow '${t.id}' applies to '${r}' but no subjectId was provided`);if(r==="ticket")return{mode:"single",subject:{subjectType:"ticket",...await this.tickets.get(e)}};if(r==="pull_request")return{mode:"single",subject:{subjectType:"pull_request",...await this.repo.get(e)}};if(r==="documentation")return{mode:"single",subject:{subjectType:"documentation",...await this.documentation.get(e)}};throw new Error(`Unsupported subjectType for workflow subject resolution: ${r}`)}async resolveKnowledge(t){let e=[];for(let r of t)e.push(...await this.knowledge.resolve(r));return e}async requireWorkflow(t){let e=await this.workflows.get(t);if(!e)throw new h(`Workflow not found: ${t}`);return e}async persistJob(t){let e=await this.jobs.update(t.id,{status:t.status,context:t.context,currentStepId:t.currentStepId,currentStepExecutionId:t.currentStepExecutionId,stepHistory:t.stepHistory,worktreePath:t.worktreePath,branch:t.branch,updatedAt:t.updatedAt,completedAt:t.completedAt});if(!e)throw new Error(`Failed to persist job ${t.id}`);return e}emit(t){this.events.emit(t)}};it=wl([gl(),G(0,z(O)),G(1,z(P)),G(2,z(K)),G(3,z(X)),G(4,z(nt)),G(5,z(Ut)),G(6,z(Ft)),G(7,z(Jt)),G(8,z(me)),G(9,z(we)),G(10,z(ye)),G(11,z(It)),yl("design:paramtypes",[O,P,K,X,nt,Object,Object,Object,Object,Object,Object,It])],it)});import{Module as Tl}from"@nestjs/common";var vl,se,Nr=p(()=>{"use strict";xe();uo();fo();yi();go();vl=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},se=class{};se=vl([Tl({imports:[ft,Nt,qt,mo],providers:[it],exports:[it]})],se)});import{Catch as Ol}from"@nestjs/common";var Rl,So,ki=p(()=>{"use strict";D();Rl=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},So=class{catch(t,e){e.switchToHttp().getResponse().status(t.httpStatus).json({error:t.message})}};So=Rl([Ol(Wt)],So)});import{z as _}from"zod";var Pl,Ai,qr,jo,Ni,Cr=p(()=>{"use strict";Pl=_.object({name:_.string().min(1),label:_.string().min(1),type:_.enum(["string","select"]),options:_.array(_.string()).optional(),required:_.boolean()}),Ai=_.object({id:_.string().min(1),label:_.string().min(1),params:_.array(Pl)}),qr=_.object({templateId:_.string().min(1),params:_.record(_.string(),_.unknown())}),jo=_.object({params:_.record(_.string(),_.unknown())}),Ni=_.object({query:_.record(_.string(),_.unknown())})});import{z as J}from"zod";var ht,_o,Io,xo,Eo,Dr=p(()=>{"use strict";Cr();ht=J.enum(["ticket","pull_request","documentation"]),_o=J.object({id:J.string().min(1),name:J.string().min(1),subjectType:ht,workflowId:J.string().min(1),query:J.record(J.string(),J.unknown()),description:J.string().optional(),queryTemplate:qr.optional(),order:J.number().int().nonnegative()}),Io=_o.omit({order:!0}),xo=_o.partial().omit({id:!0,order:!0}).extend({queryTemplate:qr.nullable().optional()}),Eo=J.object({viewIds:J.array(J.string().min(1)).min(1)})});var qi=p(()=>{"use strict";Dr()});var Ci=p(()=>{"use strict";Cr()});function kl(o){let t=o.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"");return t.length>0?t:"step"}function Di(o,t){let e=kl(o);if(!t.has(e))return e;let r=2;for(;t.has(`${e}-${r}`);)r+=1;return`${e}-${r}`}function Bi(o,t){for(let e of o)e.id&&t.push(e.id),e.type==="loop"&&Array.isArray(e.steps)&&Bi(e.steps,t)}function $i(o){let t=[];Bi(o,t);let e=new Map;for(let r of t)e.set(r,(e.get(r)??0)+1);return[...e.entries()].filter(([,r])=>r>1).map(([r])=>r)}function Li(o){let t=new Set,e=r=>{for(let i of r)i.id&&t.add(i.id),i.type==="loop"&&Array.isArray(i.steps)&&e(i.steps)};return e(o),t}var Br=p(()=>{"use strict"});import{z as d}from"zod";var Al,Re,Nl,Ct,Ui,Fi,Ji,Mi,Vi,Wi,Xi,Ki,ql,Hi,Gi,Oe,Cl,Dl,Bl,$l,Ll,Ul,Fl,zi,ae,Qi=p(()=>{"use strict";Dr();Br();Al=d.enum(["on_fail","on_complete","on_needs_input"]),Re=d.object({triggers:d.array(Al),messageTemplate:d.string().optional()}),Nl=d.object({name:d.string().min(1),label:d.string().min(1),type:d.enum(["string","number","boolean","select"]),options:d.array(d.string()).optional(),required:d.boolean(),defaultValue:d.unknown().optional()}),Ct=d.string().min(1),Ui=d.object({type:d.literal("agent"),id:d.string().min(1),name:Ct,objective:d.string().min(1),knowledgeScope:d.array(d.enum(["user","organization","project"])).optional(),outputFormat:d.enum(["questionnaire","confirmation","comment_suggestions","free_text"])}),Fi=d.object({type:d.literal("interaction"),id:d.string().min(1),name:Ct,interaction:d.union([d.literal("questionnaire"),d.literal("confirmation"),d.literal("conversation")]),notify:d.boolean().optional()}),Ji=d.object({type:d.literal("shell"),id:d.string().min(1),name:Ct,command:d.string().min(1)}),Mi=d.object({type:d.literal("git"),id:d.string().min(1),name:Ct,operation:d.enum(["create_worktree","checkout","create_branch","commit","push"]),params:d.record(d.string(),d.unknown())}),Vi=d.object({type:d.literal("provider_action"),id:d.string().min(1),name:Ct,action:d.enum(["get_subject","get_comments","post_comment","update_status","get_content"]),params:d.record(d.string(),d.unknown()).optional()}),Wi=d.object({type:d.literal("sub_workflow"),id:d.string().min(1),name:Ct,workflowId:d.string().min(1),forEach:d.literal("selection")}),Xi=d.discriminatedUnion("type",[d.object({type:d.literal("field_empty"),stepId:d.string().min(1),field:d.string().min(1)}),d.object({type:d.literal("field_equals"),stepId:d.string().min(1),field:d.string().min(1),value:d.unknown()})]),Ki=d.discriminatedUnion("action",[d.object({action:d.literal("fail")}),d.object({action:d.literal("continue")}),d.object({action:d.literal("ask_human")})]),ql=d.object({type:d.literal("loop"),id:d.string().min(1),name:Ct,steps:d.array(d.lazy(()=>Hi)),until:Xi,maxIterations:d.number().int().nonnegative(),onMaxIterations:Ki}),Hi=d.lazy(()=>d.discriminatedUnion("type",[Mi,Vi,Ji,Ui,Fi,Wi,ql])),Gi=d.object({id:d.string().min(1),name:d.string().min(1),description:d.string().optional(),appliesTo:d.union([ht,d.array(ht),d.literal("none")]),cardinality:d.enum(["single","batch","aggregate"]),inputSchema:d.array(Nl),steps:d.array(Hi),notificationPolicy:Re}),Oe=Gi.superRefine((o,t)=>{let e=$i(o.steps);e.length!==0&&t.addIssue({code:"custom",path:["steps"],message:`Duplicate step id(s): ${e.join(", ")}`})}),Cl=Ui.extend({id:d.string().min(1).optional()}),Dl=Fi.extend({id:d.string().min(1).optional()}),Bl=Ji.extend({id:d.string().min(1).optional()}),$l=Mi.extend({id:d.string().min(1).optional()}),Ll=Vi.extend({id:d.string().min(1).optional()}),Ul=Wi.extend({id:d.string().min(1).optional()}),Fl=d.object({type:d.literal("loop"),id:d.string().min(1).optional(),name:Ct,steps:d.array(d.lazy(()=>zi)),until:Xi,maxIterations:d.number().int().nonnegative(),onMaxIterations:Ki}),zi=d.lazy(()=>d.discriminatedUnion("type",[$l,Ll,Bl,Cl,Dl,Ul,Fl])),ae=Gi.omit({id:!0,steps:!0}).extend({id:d.string().min(1).optional(),steps:d.array(zi)})});function Jl(o){return o==="none"?[]:Array.isArray(o)?o:[o]}function Yi(o,t){return Jl(o).includes(t)}var Zi=p(()=>{"use strict"});var ts=p(()=>{"use strict";Qi();Br();Zi()});var es=p(()=>{"use strict"});var os=p(()=>{"use strict";es()});var rs=p(()=>{"use strict"});var ns=p(()=>{"use strict";rs()});var is=p(()=>{"use strict"});var ss=p(()=>{"use strict";is()});import{z as $}from"zod";var ce,as=p(()=>{"use strict";ce=$.object({id:$.string().min(1),viewId:$.string().min(1),trigger:$.object({type:$.literal("cron"),cadence:$.string().min(1)}),notificationOverride:$.object({triggers:$.array($.enum(["on_fail","on_complete","on_needs_input"])),messageTemplate:$.string().optional()}).optional(),missedFirePolicy:$.enum(["skip","catch_up"]),enabled:$.boolean(),lastFiredAt:$.string().optional(),createdAt:$.string()})});var cs=p(()=>{"use strict";as()});import{z as Q}from"zod";var vo,To,Ro,Oo,us=p(()=>{"use strict";vo=Q.object({id:Q.string().min(1),name:Q.string().min(1),workflowId:Q.string().min(1),inputValues:Q.record(Q.string(),Q.unknown()),lastJobId:Q.string().min(1).optional(),order:Q.number().int().nonnegative()}),To=vo.omit({order:!0}),Ro=vo.partial().omit({id:!0,order:!0}),Oo=Q.object({shortcutIds:Q.array(Q.string().min(1)).min(1)})});var ls=p(()=>{"use strict";us()});import{z as Y}from"zod";var ps,ds,fs,ms,$r,Po,hs=p(()=>{"use strict";ps=Y.string().min(1).refine(o=>{try{let t=new URL(o);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}},{message:"Must be an http(s) URL"}).optional(),ds=Y.object({ticket:Y.enum(["jira","manual"]).optional(),repo:Y.enum(["bitbucket","manual"]).optional(),agent:Y.enum(["claude","cursor"]).optional()}),fs=Y.object({baseUrl:ps,email:Y.string().min(1).optional()}),ms=Y.object({baseUrl:ps,email:Y.string().min(1).optional(),workspace:Y.string().min(1).optional()}),$r=Y.object({activeProviders:ds.optional(),jira:fs.optional(),bitbucket:ms.optional()}),Po=Y.object({activeProviders:ds.optional(),jira:fs.partial().optional(),bitbucket:ms.partial().optional()})});var bs=p(()=>{"use strict";hs()});var ws=p(()=>{"use strict"});var ys=p(()=>{"use strict";ws()});var Z=p(()=>{"use strict";qi();Ci();ts();os();ns();ss();cs();ls();bs();ys()});var S,bt=p(()=>{"use strict";D();S=class{schema;constructor(t){this.schema=t}transform(t){let e=this.schema.safeParse(t);if(!e.success){let r=e.error.issues.map(i=>`${i.path.join(".")||"(root)"}: ${i.message}`).join("; ");throw new b(`Validation failed: ${r}`)}return e.data}}});import{randomUUID as Ml}from"node:crypto";function Vl(){return Ml()}function Lr(o){let t=o.id??Vl(),e=Li(o.steps),r=gs(o.steps,e);return{...o,id:t,steps:r}}function gs(o,t){return o.map(e=>{let r=e.id;return r||(r=Di(e.name,t),t.add(r)),e.type==="loop"?{...e,id:r,steps:gs(e.steps,t)}:{...e,id:r}})}var Ss=p(()=>{"use strict";Z()});import{Body as _s,Controller as Wl,Delete as Xl,Get as Is,HttpCode as Kl,Inject as js,Param as Ur,Patch as Hl,Post as Gl,Query as zl}from"@nestjs/common";var ue,q,Dt,Ql,xt,xs=p(()=>{"use strict";Z();ee();oe();D();bt();Ss();ue=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},q=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},Dt=function(o,t){return function(e,r){t(e,r,o)}},Ql=new Set(["completed","failed","cancelled"]),xt=class{workflows;jobs;constructor(t,e){this.workflows=t,this.jobs=e}async list(t){if(t!=null&&t!==""&&t!=="single"&&t!=="batch"&&t!=="aggregate")throw new b(`Invalid cardinality filter: ${t}`);return this.workflows.list(t?{cardinality:t}:{})}async get(t){let e=await this.workflows.get(t);if(!e)throw new h(`Workflow not found: ${t}`);return e}async create(t){let e=Lr(t),r=Oe.safeParse(e);if(!r.success){let i=r.error.issues.map(n=>`${n.path.join(".")||"(root)"}: ${n.message}`).join("; ");throw new b(`Validation failed: ${i}`)}return this.workflows.create(r.data)}async update(t,e){let r=Lr({...e,id:t}),i=Oe.safeParse(r);if(!i.success){let u=i.error.issues.map(c=>`${c.path.join(".")||"(root)"}: ${c.message}`).join("; ");throw new b(`Validation failed: ${u}`)}let{id:n,...s}=i.data,a=await this.workflows.update(t,s);if(!a)throw new h(`Workflow not found: ${t}`);return a}async remove(t){if(!await this.workflows.get(t))throw new h(`Workflow not found: ${t}`);let i=(await this.jobs.list({workflowId:t})).filter(s=>!Ql.has(s.status));if(i.length>0){let s=i.length===1?"Job":"Jobs";throw new Xt(`Cannot delete workflow ${t}: ${i.length} non-terminal ${s} still reference it`)}if(!await this.workflows.delete(t))throw new h(`Workflow not found: ${t}`)}};ue([Is(),Dt(0,zl("cardinality")),q("design:type",Function),q("design:paramtypes",[String]),q("design:returntype",Promise)],xt.prototype,"list",null);ue([Is(":id"),Dt(0,Ur("id")),q("design:type",Function),q("design:paramtypes",[String]),q("design:returntype",Promise)],xt.prototype,"get",null);ue([Gl(),Dt(0,_s(new S(ae))),q("design:type",Function),q("design:paramtypes",[Object]),q("design:returntype",Promise)],xt.prototype,"create",null);ue([Hl(":id"),Dt(0,Ur("id")),Dt(1,_s(new S(ae))),q("design:type",Function),q("design:paramtypes",[String,Object]),q("design:returntype",Promise)],xt.prototype,"update",null);ue([Xl(":id"),Kl(204),Dt(0,Ur("id")),q("design:type",Function),q("design:paramtypes",[String]),q("design:returntype",Promise)],xt.prototype,"remove",null);xt=ue([Wl("workflows"),Dt(0,js(O)),Dt(1,js(P)),q("design:paramtypes",[O,P])],xt)});function Es(o,t,e){if(!o)throw new h(`Workflow not found: ${t}`);if(o.appliesTo==="none")throw new b(`Cannot bind a View to workflow '${t}' because appliesTo is 'none'`);if(!Yi(o.appliesTo,e))throw new b(`subjectType '${e}' is not included in workflow '${t}' appliesTo`);return o}function vs(o,t){if(!o)throw new h(`Workflow not found: ${t}`);if(o.appliesTo!=="none")throw new b(`WorkflowShortcut requires appliesTo 'none', got '${String(o.appliesTo)}'`);if(o.cardinality!=="single")throw new b(`WorkflowShortcut requires cardinality 'single', got '${o.cardinality}'`);return o}var Fr=p(()=>{"use strict";Z();D()});import{Body as Jr,Controller as Yl,Delete as Zl,Get as Mr,HttpCode as tp,Inject as Pe,Param as ko,Patch as Ts,Post as ep,Query as op}from"@nestjs/common";var Bt,I,M,st,Rs=p(()=>{"use strict";Z();to();ee();D();bt();Fr();Be();Le();Fe();kr();Bt=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},I=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},M=function(o,t){return function(e,r){t(e,r,o)}},st=class{views;workflows;tickets;repo;documentation;constructor(t,e,r,i,n){this.views=t,this.workflows=e,this.tickets=r,this.repo=i,this.documentation=n}async list(t){if(t!=null&&t!==""){let e=ht.safeParse(t);if(!e.success)throw new b(`Invalid subjectType filter: ${t}`);return this.views.list({subjectType:e.data})}return this.views.list({})}async reorder(t){let e=[];for(let n of t.viewIds){let s=await this.views.get(n);if(!s)throw new b(`Unknown view id in reorder: ${n}`);e.push(s)}if(new Set(e.map(n=>n.subjectType)).size!==1)throw new b("All viewIds in a reorder request must share the same subjectType");return await this.views.reorder(t.viewIds)}async listSubjects(t){return bo(t,this.views,{tickets:this.tickets,repo:this.repo,documentation:this.documentation})}async get(t){let e=await this.views.get(t);if(!e)throw new h(`SubjectView not found: ${t}`);return e}async create(t){return await this.assertBinding(t.workflowId,t.subjectType),this.views.create(t)}async update(t,e){let r=await this.views.get(t);if(!r)throw new h(`SubjectView not found: ${t}`);await this.assertBinding(e.workflowId??r.workflowId,e.subjectType??r.subjectType);let i=await this.views.update(t,e);if(!i)throw new h(`SubjectView not found: ${t}`);return i}async remove(t){if(!await this.views.delete(t))throw new h(`SubjectView not found: ${t}`)}async assertBinding(t,e){let r=await this.workflows.get(t);Es(r,t,e)}};Bt([Mr(),M(0,op("subjectType")),I("design:type",Function),I("design:paramtypes",[String]),I("design:returntype",Promise)],st.prototype,"list",null);Bt([Ts("reorder"),M(0,Jr(new S(Eo))),I("design:type",Function),I("design:paramtypes",[Object]),I("design:returntype",Promise)],st.prototype,"reorder",null);Bt([Mr(":id/subjects"),M(0,ko("id")),I("design:type",Function),I("design:paramtypes",[String]),I("design:returntype",Promise)],st.prototype,"listSubjects",null);Bt([Mr(":id"),M(0,ko("id")),I("design:type",Function),I("design:paramtypes",[String]),I("design:returntype",Promise)],st.prototype,"get",null);Bt([ep(),M(0,Jr(new S(Io))),I("design:type",Function),I("design:paramtypes",[Object]),I("design:returntype",Promise)],st.prototype,"create",null);Bt([Ts(":id"),M(0,ko("id")),M(1,Jr(new S(xo))),I("design:type",Function),I("design:paramtypes",[String,Object]),I("design:returntype",Promise)],st.prototype,"update",null);Bt([Zl(":id"),tp(204),M(0,ko("id")),I("design:type",Function),I("design:paramtypes",[String]),I("design:returntype",Promise)],st.prototype,"remove",null);st=Bt([Yl("views"),M(0,Pe(X)),M(1,Pe(O)),M(2,Pe(Ut)),M(3,Pe(Ft)),M(4,Pe(Jt)),I("design:paramtypes",[X,O,Object,Object,Object])],st)});import{Body as Vr,Controller as rp,Delete as np,Get as Ps,HttpCode as ip,Inject as Os,Param as Wr,Patch as ks,Post as sp}from"@nestjs/common";var Kt,E,$t,wt,As=p(()=>{"use strict";Z();yr();ee();D();bt();Fr();Kt=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},E=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},$t=function(o,t){return function(e,r){t(e,r,o)}},wt=class{shortcuts;workflows;constructor(t,e){this.shortcuts=t,this.workflows=e}async list(){return this.shortcuts.list()}async reorder(t){for(let e of t.shortcutIds)if(!await this.shortcuts.get(e))throw new b(`Unknown shortcut id in reorder: ${e}`);return this.shortcuts.reorder(t.shortcutIds)}async get(t){let e=await this.shortcuts.get(t);if(!e)throw new h(`WorkflowShortcut not found: ${t}`);return e}async create(t){return await this.assertBinding(t.workflowId),this.shortcuts.create(t)}async update(t,e){let r=await this.shortcuts.get(t);if(!r)throw new h(`WorkflowShortcut not found: ${t}`);await this.assertBinding(e.workflowId??r.workflowId);let i=await this.shortcuts.update(t,e);if(!i)throw new h(`WorkflowShortcut not found: ${t}`);return i}async remove(t){if(!await this.shortcuts.delete(t))throw new h(`WorkflowShortcut not found: ${t}`)}async assertBinding(t){let e=await this.workflows.get(t);vs(e,t)}};Kt([Ps(),E("design:type",Function),E("design:paramtypes",[]),E("design:returntype",Promise)],wt.prototype,"list",null);Kt([ks("reorder"),$t(0,Vr(new S(Oo))),E("design:type",Function),E("design:paramtypes",[Object]),E("design:returntype",Promise)],wt.prototype,"reorder",null);Kt([Ps(":id"),$t(0,Wr("id")),E("design:type",Function),E("design:paramtypes",[String]),E("design:returntype",Promise)],wt.prototype,"get",null);Kt([sp(),$t(0,Vr(new S(To))),E("design:type",Function),E("design:paramtypes",[Object]),E("design:returntype",Promise)],wt.prototype,"create",null);Kt([ks(":id"),$t(0,Wr("id")),$t(1,Vr(new S(Ro))),E("design:type",Function),E("design:paramtypes",[String,Object]),E("design:returntype",Promise)],wt.prototype,"update",null);Kt([np(":id"),ip(204),$t(0,Wr("id")),E("design:type",Function),E("design:paramtypes",[String]),E("design:returntype",Promise)],wt.prototype,"remove",null);wt=Kt([rp("workflow-shortcuts"),$t(0,Os(_t)),$t(1,Os(O)),E("design:paramtypes",[_t,O])],wt)});function Ao(o,t,e=50){let r=o!=null&&o!==""?Number(o):e,i=t!=null&&t!==""?Number(t):0;return!Number.isFinite(r)||r<1?{limit:e,offset:Math.max(0,i||0)}:!Number.isFinite(i)||i<0?{limit:r,offset:0}:{limit:Math.floor(r),offset:Math.floor(i)}}function No(o,t,e){return o.slice(e,e+t)}var Xr=p(()=>{"use strict"});import{z as tt}from"zod";var qo,Co,Do,Kr=p(()=>{"use strict";qo=tt.object({workflowId:tt.string().min(1),subjectId:tt.string().min(1).optional(),inputValues:tt.record(tt.string(),tt.unknown())}),Co=tt.object({response:tt.unknown()}),Do=tt.object({workflowId:tt.string().min(1),subjectIds:tt.array(tt.string().min(1))})});import{Body as Hr,Controller as ap,Get as qs,HttpCode as cp,Inject as Ns,Param as Gr,Post as Bo,Query as Ht}from"@nestjs/common";import"zod";var Gt,v,B,up,yt,Cs=p(()=>{"use strict";go();oe();D();bt();Xr();Kr();Gt=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},v=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},B=function(o,t){return function(e,r){t(e,r,o)}},up=["pending","planning","waiting_for_human","waiting_for_children","implementing","testing","completed","failed","cancelled"],yt=class{jobs;runner;constructor(t,e){this.jobs=t,this.runner=e}async list(t,e,r,i,n,s,a){if(e!=null&&e!==""&&!up.includes(e))throw new b(`Invalid status filter: ${e}`);if(n!=null&&n!==""&&n!=="true"&&n!=="false")throw new b(`Invalid topLevelOnly filter: ${n}`);let{limit:u,offset:c}=Ao(s,a),f=await this.jobs.list({...t?{workflowId:t}:{},...e?{status:e}:{},...r?{batchId:r}:{},...i?{parentJobId:i}:{},...n==="true"?{topLevelOnly:!0}:{}});return No(f,u,c)}async latestBySubject(t){return this.jobs.latestBySubject(t.workflowId,t.subjectIds)}async get(t){let e=await this.jobs.get(t);if(!e)throw new h(`Job not found: ${t}`);return e}async create(t){return this.runner.start({workflowId:t.workflowId,...t.subjectId?{subjectId:t.subjectId}:{},inputValues:t.inputValues})}async resume(t,e){return this.runner.resume(t,e.response)}async retry(t){return this.runner.retryFailedJob(t)}};Gt([qs(),B(0,Ht("workflowId")),B(1,Ht("status")),B(2,Ht("batchId")),B(3,Ht("parentJobId")),B(4,Ht("topLevelOnly")),B(5,Ht("limit")),B(6,Ht("offset")),v("design:type",Function),v("design:paramtypes",[String,String,String,String,String,String,String]),v("design:returntype",Promise)],yt.prototype,"list",null);Gt([Bo("latest-by-subject"),cp(200),B(0,Hr(new S(Do))),v("design:type",Function),v("design:paramtypes",[Object]),v("design:returntype",Promise)],yt.prototype,"latestBySubject",null);Gt([qs(":id"),B(0,Gr("id")),v("design:type",Function),v("design:paramtypes",[String]),v("design:returntype",Promise)],yt.prototype,"get",null);Gt([Bo(),B(0,Hr(new S(qo))),v("design:type",Function),v("design:paramtypes",[Object]),v("design:returntype",Promise)],yt.prototype,"create",null);Gt([Bo(":id/resume"),B(0,Gr("id")),B(1,Hr(new S(Co))),v("design:type",Function),v("design:paramtypes",[String,Object]),v("design:returntype",Promise)],yt.prototype,"resume",null);Gt([Bo(":id/retry"),B(0,Gr("id")),v("design:type",Function),v("design:paramtypes",[String]),v("design:returntype",Promise)],yt.prototype,"retry",null);yt=Gt([ap("jobs"),B(0,Ns(P)),B(1,Ns(it)),v("design:paramtypes",[P,it])],yt)});import{z as L}from"zod";var $o,Lo,zr=p(()=>{"use strict";Z();$o=L.discriminatedUnion("mode",[L.object({mode:L.literal("view"),viewId:L.string().min(1)}),L.object({mode:L.literal("manual"),subjectType:ht,subjectIds:L.array(L.string().min(1))})]),Lo=L.object({workflowId:L.string().min(1),selection:$o,triggeredBy:L.enum(["schedule","view_bulk","multiselect"]),notificationOverride:Re.optional(),inputValues:L.record(L.string(),L.unknown())})});import{Body as lp,Controller as pp,Get as Zr,Inject as Qr,Param as Ds,Post as dp,Query as Yr}from"@nestjs/common";import"zod";var ke,V,Et,Lt,Bs=p(()=>{"use strict";go();eo();oe();D();bt();Xr();zr();ke=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},V=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},Et=function(o,t){return function(e,r){t(e,r,o)}},Lt=class{batches;jobs;runner;constructor(t,e,r){this.batches=t,this.jobs=e,this.runner=r}async list(t,e,r){let{limit:i,offset:n}=Ao(e,r),s=await this.batches.list(t?{workflowId:t}:{});return No(s,i,n)}async get(t){let e=await this.batches.get(t);if(!e)throw new h(`JobBatch not found: ${t}`);return e}async listJobs(t){if(!await this.batches.get(t))throw new h(`JobBatch not found: ${t}`);return this.jobs.list({batchId:t})}async launch(t){let e=await this.runner.launch({workflowId:t.workflowId,selection:t.selection,triggeredBy:t.triggeredBy,...t.notificationOverride?{notificationOverride:t.notificationOverride}:{},inputValues:t.inputValues});return"resolvedSubjects"in e&&"jobIds"in e?{kind:"batch",batch:e}:{kind:"job",job:e}}};ke([Zr(),Et(0,Yr("workflowId")),Et(1,Yr("limit")),Et(2,Yr("offset")),V("design:type",Function),V("design:paramtypes",[String,String,String]),V("design:returntype",Promise)],Lt.prototype,"list",null);ke([Zr(":id"),Et(0,Ds("id")),V("design:type",Function),V("design:paramtypes",[String]),V("design:returntype",Promise)],Lt.prototype,"get",null);ke([Zr(":id/jobs"),Et(0,Ds("id")),V("design:type",Function),V("design:paramtypes",[String]),V("design:returntype",Promise)],Lt.prototype,"listJobs",null);ke([dp(),Et(0,lp(new S(Lo))),V("design:type",Function),V("design:paramtypes",[Object]),V("design:returntype",Promise)],Lt.prototype,"launch",null);Lt=ke([pp("batches"),Et(0,Qr(K)),Et(1,Qr(P)),Et(2,Qr(it)),V("design:paramtypes",[K,P,it])],Lt)});import{Body as $s,Controller as fp,Delete as mp,Get as Ls,HttpCode as hp,Inject as bp,Param as tn,Patch as wp,Post as yp,Query as gp}from"@nestjs/common";var le,C,zt,vt,Us=p(()=>{"use strict";Z();br();D();bt();le=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},C=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},zt=function(o,t){return function(e,r){t(e,r,o)}},vt=class{schedules;constructor(t){this.schedules=t}async list(t){if(t==null||t==="")return this.schedules.list();if(t!=="true"&&t!=="false")throw new b(`Invalid enabled filter: ${t}`);return this.schedules.list({enabled:t==="true"})}async get(t){let e=await this.schedules.get(t);if(!e)throw new h(`Schedule not found: ${t}`);return e}async create(t){return this.schedules.create(t)}async update(t,e){let r=await this.schedules.update(t,e);if(!r)throw new h(`Schedule not found: ${t}`);return r}async remove(t){if(!await this.schedules.delete(t))throw new h(`Schedule not found: ${t}`)}};le([Ls(),zt(0,gp("enabled")),C("design:type",Function),C("design:paramtypes",[String]),C("design:returntype",Promise)],vt.prototype,"list",null);le([Ls(":id"),zt(0,tn("id")),C("design:type",Function),C("design:paramtypes",[String]),C("design:returntype",Promise)],vt.prototype,"get",null);le([yp(),zt(0,$s(new S(ce))),C("design:type",Function),C("design:paramtypes",[Object]),C("design:returntype",Promise)],vt.prototype,"create",null);le([wp(":id"),zt(0,tn("id")),zt(1,$s(new S(ce.partial().omit({id:!0})))),C("design:type",Function),C("design:paramtypes",[String,Object]),C("design:returntype",Promise)],vt.prototype,"update",null);le([mp(":id"),hp(204),zt(0,tn("id")),C("design:type",Function),C("design:paramtypes",[String]),C("design:returntype",Promise)],vt.prototype,"remove",null);vt=le([fp("schedules"),zt(0,bp(jt)),C("design:paramtypes",[jt])],vt)});import{Controller as Sp,Inject as jp,Query as Fs,Sse as _p}from"@nestjs/common";import{Observable as Ms}from"rxjs";var Js,Uo,en,Ae,Vs=p(()=>{"use strict";po();Js=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},Uo=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},en=function(o,t){return function(e,r){t(e,r,o)}},Ae=class{events;constructor(t){this.events=t}stream(t,e){return new Ms(r=>{let i=this.events.subscribe(n=>{let s=n;t!=null&&t!==""&&(!("jobId"in s)||s.jobId!==t)||e!=null&&e!==""&&(!("batchId"in s)||s.batchId!==e)||r.next({data:s})});return()=>{i()}})}};Js([_p(),en(0,Fs("jobId")),en(1,Fs("batchId")),Uo("design:type",Function),Uo("design:paramtypes",[String,String]),Uo("design:returntype",Ms)],Ae.prototype,"stream",null);Ae=Js([Sp("events"),en(0,jp(nt)),Uo("design:paramtypes",[nt])],Ae)});import{extendZodWithOpenApi as Ip}from"@asteasolutions/zod-to-openapi";import{z as xp}from"zod";var Ws=p(()=>{"use strict";Ip(xp)});import{z as Xs}from"zod";var Fo,on=p(()=>{"use strict";Fo=Xs.object({value:Xs.string().min(1)})});import{z as l}from"zod";function Jp(o){let t=l.toJSONSchema(o),{$schema:e,...r}=t;return r}function Hs(o){let t=(e,r)=>o.registerComponent("schemas",e,Jp(r)).ref;return{WorkflowDefinition:t("WorkflowDefinition",Oe),WorkflowDefinitionInput:t("WorkflowDefinitionInput",ae),UpdateWorkflowBody:t("UpdateWorkflowBody",Dp),SubjectView:t("SubjectView",_o),CreateSubjectViewBody:t("CreateSubjectViewBody",Io),ReorderViewsBody:t("ReorderViewsBody",Eo),UpdateViewBody:t("UpdateViewBody",Bp),WorkflowShortcut:t("WorkflowShortcut",vo),CreateWorkflowShortcutBody:t("CreateWorkflowShortcutBody",To),UpdateWorkflowShortcutBody:t("UpdateWorkflowShortcutBody",Ro),ReorderShortcutsBody:t("ReorderShortcutsBody",Oo),Schedule:t("Schedule",ce),UpdateScheduleBody:t("UpdateScheduleBody",$p),EngineSettings:t("EngineSettings",$r),UpdateSettingsBody:t("UpdateSettingsBody",Up),SettingsPatchResponse:t("SettingsPatchResponse",Fp),SetSecretBody:t("SetSecretBody",Fo),CreateJobBody:t("CreateJobBody",qo),ResumeJobBody:t("ResumeJobBody",Co),LatestBySubjectBody:t("LatestBySubjectBody",Do),LatestBySubjectResponse:t("LatestBySubjectResponse",Lp),LaunchBody:t("LaunchBody",Lo),Job:t("Job",rn),JobBatch:t("JobBatch",Ks),LaunchResponse:t("LaunchResponse",kp),HealthResponse:t("HealthResponse",Ap),ProviderStatus:t("ProviderStatus",Np),QueryTemplate:t("QueryTemplate",Ai),ResolveQueryTemplateBody:t("ResolveQueryTemplateBody",jo),ResolveQueryTemplateResponse:t("ResolveQueryTemplateResponse",Ni),ErrorResponse:t("ErrorResponse",qp),EngineEvent:t("EngineEvent",Cp),Subject:t("Subject",Jo)}}var Ep,vp,Tp,Rp,Jo,Op,Pp,rn,Ks,kp,Ap,Np,qp,Cp,Dp,Bp,$p,Lp,Up,Fp,T,nn,sn=p(()=>{"use strict";Ws();Z();Kr();zr();on();Ep=l.enum(["pending","planning","waiting_for_human","waiting_for_children","implementing","testing","completed","failed","cancelled"]),vp=l.object({subjectType:l.literal("ticket"),id:l.string(),source:l.enum(["jira","azure-devops","manual"]),title:l.string(),description:l.string().optional(),status:l.string(),assignee:l.string().optional(),url:l.string().optional(),raw:l.record(l.string(),l.unknown()).optional()}),Tp=l.object({subjectType:l.literal("pull_request"),id:l.string(),source:l.enum(["bitbucket","github","manual"]),title:l.string(),description:l.string().optional(),sourceBranch:l.string(),targetBranch:l.string(),author:l.string().optional(),url:l.string().optional(),raw:l.record(l.string(),l.unknown()).optional()}),Rp=l.object({subjectType:l.literal("documentation"),id:l.string(),source:l.enum(["confluence","notion","github_wiki","gitlab_wiki","azure_wiki","web","manual"]),title:l.string(),url:l.string().optional(),raw:l.record(l.string(),l.unknown()).optional()}),Jo=l.discriminatedUnion("subjectType",[vp,Tp,Rp]),Op=l.discriminatedUnion("mode",[l.object({mode:l.literal("single"),subject:Jo}),l.object({mode:l.literal("collection"),subjects:l.array(Jo)})]),Pp=l.object({id:l.string(),stepDefinitionId:l.string(),type:l.string(),status:l.enum(["pending","running","waiting_for_children","completed","failed","skipped"]),startedAt:l.string().optional(),completedAt:l.string().optional(),output:l.unknown().optional(),error:l.string().optional(),childJobIds:l.array(l.string()).optional(),iterations:l.array(l.object({index:l.number().int(),stepExecutions:l.array(l.record(l.string(),l.unknown())),startedAt:l.string(),completedAt:l.string().optional()})).optional()}),rn=l.object({id:l.string(),workflowId:l.string(),status:Ep,subjectContext:Op.optional(),selection:$o.optional(),batchId:l.string().optional(),parentJobId:l.string().optional(),parentStepExecutionId:l.string().optional(),fanOutIndex:l.number().int().optional(),retryOf:l.string().optional(),context:l.record(l.string(),l.unknown()),worktreePath:l.string().optional(),branch:l.string().optional(),currentStepId:l.string().optional(),currentStepExecutionId:l.string().optional(),stepHistory:l.array(Pp),createdAt:l.string(),updatedAt:l.string(),completedAt:l.string().optional()}),Ks=l.object({id:l.string(),workflowId:l.string(),selection:$o,resolvedSubjects:l.array(Jo),jobIds:l.array(l.string()),status:l.enum(["running","completed","completed_with_issues","failed"]),triggeredBy:l.enum(["schedule","view_bulk","multiselect"]),scheduleId:l.string().optional(),notificationOverride:Re.optional(),notificationSent:l.boolean(),createdAt:l.string(),completedAt:l.string().optional()}),kp=l.discriminatedUnion("kind",[l.object({kind:l.literal("job"),job:rn}),l.object({kind:l.literal("batch"),batch:Ks})]),Ap=l.object({ok:l.boolean(),service:l.string(),timestamp:l.string()}),Np=l.object({providerId:l.string(),secretKey:l.string(),configured:l.boolean()}),qp=l.object({error:l.string()}),Cp=l.object({type:l.string(),timestamp:l.string()}).passthrough(),Dp=ae,Bp=xo,$p=ce.partial().omit({id:!0}),Lp=l.record(l.string(),rn.nullable()),Up=Po,Fp=l.object({settings:$r,restartRequired:l.boolean()}),T=l.object({id:l.string().min(1)}),nn=l.object({limit:l.string().optional().openapi({description:"Max items to return (default 50)"}),offset:l.string().optional().openapi({description:"Number of items to skip (default 0)"})})});import{z as x}from"zod";function w(o,t){return{description:t,content:{"application/json":{schema:o}}}}function et(o){return{type:"array",items:o}}function y(o,...t){let e={400:"Validation error",404:"Resource not found",409:"Conflict"};return Object.fromEntries(t.map(r=>[String(r),w(o.ErrorResponse,e[r]??"Error")]))}function Gs(o,t){o.registerPath({method:"get",path:"/health",tags:["Health"],summary:"Health check",responses:{200:w(t.HealthResponse,"Service is healthy")}}),o.registerPath({method:"get",path:"/workflows",tags:["Workflows"],summary:"List workflow definitions",request:{query:x.object({cardinality:x.enum(["single","batch","aggregate"]).optional()})},responses:{200:w(et(t.WorkflowDefinition),"Workflow definitions"),...y(t,400)}}),o.registerPath({method:"get",path:"/workflows/{id}",tags:["Workflows"],summary:"Get a workflow definition",request:{params:T},responses:{200:w(t.WorkflowDefinition,"Workflow definition"),...y(t,404)}}),o.registerPath({method:"post",path:"/workflows",tags:["Workflows"],summary:"Create a workflow definition",request:{body:{required:!0,content:{"application/json":{schema:t.WorkflowDefinitionInput}}}},responses:{201:w(t.WorkflowDefinition,"Created workflow definition"),...y(t,400)}}),o.registerPath({method:"patch",path:"/workflows/{id}",tags:["Workflows"],summary:"Update a workflow definition",request:{params:T,body:{required:!0,content:{"application/json":{schema:t.UpdateWorkflowBody}}}},responses:{200:w(t.WorkflowDefinition,"Updated workflow definition"),...y(t,400,404)}}),o.registerPath({method:"delete",path:"/workflows/{id}",tags:["Workflows"],summary:"Delete a workflow definition",description:"Rejected with 409 if any non-terminal Job still references the workflow. Terminal Jobs (completed, failed, cancelled) do not block deletion.",request:{params:T},responses:{204:{description:"Workflow deleted"},...y(t,404,409)}}),o.registerPath({method:"get",path:"/views",tags:["Views"],summary:"List subject views",request:{query:x.object({subjectType:ht.optional()})},responses:{200:w(et(t.SubjectView),"Subject views"),...y(t,400)}}),o.registerPath({method:"get",path:"/views/{id}",tags:["Views"],summary:"Get a subject view",request:{params:T},responses:{200:w(t.SubjectView,"Subject view"),...y(t,404)}}),o.registerPath({method:"get",path:"/views/{id}/subjects",tags:["Views"],summary:"Preview subjects matching a view",description:"Live provider query for the View's saved filter. Same resolution path as launch() for { mode: 'view' }. Does not create Jobs or snapshots.",request:{params:T},responses:{200:w(et(t.Subject),"Matching subjects"),...y(t,404,400)}}),o.registerPath({method:"patch",path:"/views/reorder",tags:["Views"],summary:"Reorder views within a subject type group",request:{body:{required:!0,content:{"application/json":{schema:t.ReorderViewsBody}}}},responses:{200:w(et(t.SubjectView),"Reordered views for the subject type"),...y(t,400)}}),o.registerPath({method:"post",path:"/views",tags:["Views"],summary:"Create a subject view",request:{body:{required:!0,content:{"application/json":{schema:t.CreateSubjectViewBody}}}},responses:{201:w(t.SubjectView,"Created subject view"),...y(t,400)}}),o.registerPath({method:"patch",path:"/views/{id}",tags:["Views"],summary:"Update a subject view",request:{params:T,body:{required:!0,content:{"application/json":{schema:t.UpdateViewBody}}}},responses:{200:w(t.SubjectView,"Updated subject view"),...y(t,400,404)}}),o.registerPath({method:"delete",path:"/views/{id}",tags:["Views"],summary:"Delete a subject view",request:{params:T},responses:{204:{description:"Subject view deleted"},...y(t,404)}}),o.registerPath({method:"get",path:"/jobs",tags:["Jobs"],summary:"List jobs",request:{query:nn.extend({workflowId:x.string().optional(),status:x.enum(["pending","planning","waiting_for_human","waiting_for_children","implementing","testing","completed","failed","cancelled"]).optional(),batchId:x.string().optional(),parentJobId:x.string().optional(),topLevelOnly:x.enum(["true","false"]).optional().openapi({description:"When true, exclude jobs that belong to a batch or a parent (sub_workflow) job"})})},responses:{200:w(et(t.Job),"Jobs"),...y(t,400)}}),o.registerPath({method:"get",path:"/jobs/{id}",tags:["Jobs"],summary:"Get a job",request:{params:T},responses:{200:w(t.Job,"Job"),...y(t,404)}}),o.registerPath({method:"post",path:"/jobs",tags:["Jobs"],summary:"Start a single job",request:{body:{required:!0,content:{"application/json":{schema:t.CreateJobBody}}}},responses:{201:w(t.Job,"Started job"),...y(t,400,404)}}),o.registerPath({method:"post",path:"/jobs/latest-by-subject",tags:["Jobs"],summary:"Latest job per subject for a workflow",request:{body:{required:!0,content:{"application/json":{schema:t.LatestBySubjectBody}}}},responses:{200:w(t.LatestBySubjectResponse,"Latest job keyed by subject id"),...y(t,400)}}),o.registerPath({method:"post",path:"/jobs/{id}/resume",tags:["Jobs"],summary:"Resume a job waiting for human input",request:{params:T,body:{required:!0,content:{"application/json":{schema:t.ResumeJobBody}}}},responses:{200:w(t.Job,"Resumed job"),...y(t,400,404,409)}}),o.registerPath({method:"post",path:"/jobs/{id}/retry",tags:["Jobs"],summary:"Retry a failed job",request:{params:T},responses:{200:w(t.Job,"Retry job"),...y(t,404,409)}}),o.registerPath({method:"get",path:"/batches",tags:["Batches"],summary:"List job batches",request:{query:nn.extend({workflowId:x.string().optional()})},responses:{200:w(et(t.JobBatch),"Job batches")}}),o.registerPath({method:"get",path:"/batches/{id}",tags:["Batches"],summary:"Get a job batch",request:{params:T},responses:{200:w(t.JobBatch,"Job batch"),...y(t,404)}}),o.registerPath({method:"get",path:"/batches/{id}/jobs",tags:["Batches"],summary:"List jobs in a batch",request:{params:T},responses:{200:w(et(t.Job),"Jobs in the batch"),...y(t,404)}}),o.registerPath({method:"post",path:"/batches",tags:["Batches"],summary:"Launch a batch or aggregate run",description:"Resolves subject selection and starts either a JobBatch (batch cardinality) or a single Job (aggregate cardinality).",request:{body:{required:!0,content:{"application/json":{schema:t.LaunchBody}}}},responses:{201:w(t.LaunchResponse,"Launch result"),...y(t,400,404)}}),o.registerPath({method:"get",path:"/workflow-shortcuts",tags:["Workflow shortcuts"],summary:"List workflow shortcuts",responses:{200:w(et(t.WorkflowShortcut),"Workflow shortcuts")}}),o.registerPath({method:"get",path:"/workflow-shortcuts/{id}",tags:["Workflow shortcuts"],summary:"Get a workflow shortcut",request:{params:T},responses:{200:w(t.WorkflowShortcut,"Workflow shortcut"),...y(t,404)}}),o.registerPath({method:"post",path:"/workflow-shortcuts",tags:["Workflow shortcuts"],summary:"Create a workflow shortcut",request:{body:{required:!0,content:{"application/json":{schema:t.CreateWorkflowShortcutBody}}}},responses:{201:w(t.WorkflowShortcut,"Created workflow shortcut"),...y(t,400,404)}}),o.registerPath({method:"patch",path:"/workflow-shortcuts/reorder",tags:["Workflow shortcuts"],summary:"Reorder workflow shortcuts",request:{body:{required:!0,content:{"application/json":{schema:t.ReorderShortcutsBody}}}},responses:{200:w(et(t.WorkflowShortcut),"Reordered workflow shortcuts"),...y(t,400)}}),o.registerPath({method:"patch",path:"/workflow-shortcuts/{id}",tags:["Workflow shortcuts"],summary:"Update a workflow shortcut",request:{params:T,body:{required:!0,content:{"application/json":{schema:t.UpdateWorkflowShortcutBody}}}},responses:{200:w(t.WorkflowShortcut,"Updated workflow shortcut"),...y(t,400,404)}}),o.registerPath({method:"delete",path:"/workflow-shortcuts/{id}",tags:["Workflow shortcuts"],summary:"Delete a workflow shortcut",request:{params:T},responses:{204:{description:"Workflow shortcut deleted"},...y(t,404)}}),o.registerPath({method:"get",path:"/schedules",tags:["Schedules"],summary:"List schedules",request:{query:x.object({enabled:x.enum(["true","false"]).optional()})},responses:{200:w(et(t.Schedule),"Schedules"),...y(t,400)}}),o.registerPath({method:"get",path:"/schedules/{id}",tags:["Schedules"],summary:"Get a schedule",request:{params:T},responses:{200:w(t.Schedule,"Schedule"),...y(t,404)}}),o.registerPath({method:"post",path:"/schedules",tags:["Schedules"],summary:"Create a schedule",description:"CRUD only \u2014 creating or enabling a schedule does not cause it to fire yet.",request:{body:{required:!0,content:{"application/json":{schema:t.Schedule}}}},responses:{201:w(t.Schedule,"Created schedule"),...y(t,400)}}),o.registerPath({method:"patch",path:"/schedules/{id}",tags:["Schedules"],summary:"Update a schedule",request:{params:T,body:{required:!0,content:{"application/json":{schema:t.UpdateScheduleBody}}}},responses:{200:w(t.Schedule,"Updated schedule"),...y(t,400,404)}}),o.registerPath({method:"delete",path:"/schedules/{id}",tags:["Schedules"],summary:"Delete a schedule",request:{params:T},responses:{204:{description:"Schedule deleted"},...y(t,404)}}),o.registerPath({method:"get",path:"/providers/status",tags:["Providers"],summary:"Provider secret configuration status",description:"Reports whether each known provider API key is set. Returns key *names* only \u2014 never secret values.",responses:{200:w(et(t.ProviderStatus),"Provider configuration status")}}),o.registerPath({method:"get",path:"/providers/{providerId}/query-templates",tags:["Providers"],summary:"List query templates for a provider",description:"Named, pre-built query templates owned by the provider. Providers with none yet (e.g. documentation) return an empty list. The client never constructs `query` itself \u2014 it submits templateId + params to the resolve endpoint.",request:{params:x.object({providerId:x.string().min(1)})},responses:{200:w(et(t.QueryTemplate),"Query templates")}}),o.registerPath({method:"post",path:"/providers/{providerId}/query-templates/{templateId}/resolve",tags:["Providers"],summary:"Resolve a query template to a concrete query",description:"Provider-specific query-shape knowledge stays server-side. Returns the `query` object to store on a SubjectView, along with template provenance the client attaches separately.",request:{params:x.object({providerId:x.string().min(1),templateId:x.string().min(1)}),body:{required:!0,content:{"application/json":{schema:t.ResolveQueryTemplateBody}}}},responses:{200:w(t.ResolveQueryTemplateResponse,"Resolved query"),...y(t,400,404)}}),o.registerPath({method:"get",path:"/settings",tags:["Settings"],summary:"Get engine settings",description:"Persisted provider configuration. Never includes secret values \u2014 those live in SecretStore.",responses:{200:w(t.EngineSettings,"Current engine settings")}}),o.registerPath({method:"patch",path:"/settings",tags:["Settings"],summary:"Update engine settings",description:"Partial merge. restartRequired is true only when activeProviders was in the patch (implementation binding is a boot-time decision). Jira/Bitbucket config fields take effect on the next provider call with no restart.",request:{body:{required:!0,content:{"application/json":{schema:t.UpdateSettingsBody}}}},responses:{200:w(t.SettingsPatchResponse,"Updated settings"),...y(t,400)}}),o.registerPath({method:"post",path:"/secrets/{key}",tags:["Settings"],summary:"Store a secret",description:"Writes to SecretStore. The response never includes the secret value.",request:{params:x.object({key:x.string().min(1)}),body:{required:!0,content:{"application/json":{schema:t.SetSecretBody}}}},responses:{204:{description:"Secret stored"},...y(t,400)}}),o.registerPath({method:"get",path:"/events",tags:["Events"],summary:"Subscribe to engine events (SSE)",description:"Server-Sent Events stream. Each event `data` field is a JSON EngineEvent. Optionally filter by jobId and/or batchId.",request:{query:x.object({jobId:x.string().optional(),batchId:x.string().optional()})},responses:{200:{description:"SSE stream of engine events",content:{"text/event-stream":{schema:t.EngineEvent}}}}})}var zs=p(()=>{"use strict";Z();sn()});import{OpenAPIRegistry as Mp,OpenApiGeneratorV31 as Vp}from"@asteasolutions/zod-to-openapi";function Qs(){if(Mo)return Mo;let o=new Mp,t=Hs(o);return Gs(o,t),Mo=new Vp(o.definitions).generateDocument({openapi:"3.1.0",info:{title:"Kno Engine API",version:"0.1.0",description:"REST API for workflow definitions, jobs, batches, schedules, views, and live events."},servers:[{url:"/api"}]}),Mo}var Mo,Ys=p(()=>{"use strict";sn();zs()});import{Controller as Wp,Get as Xp,Header as Kp}from"@nestjs/common";var Zs,an,Ne,ta=p(()=>{"use strict";Ys();Zs=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},an=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},Ne=class{getOpenApiDocument(){return Qs()}};Zs([Xp("openapi.json"),Kp("Content-Type","application/json"),an("design:type",Function),an("design:paramtypes",[]),an("design:returntype",void 0)],Ne.prototype,"getOpenApiDocument",null);Ne=Zs([Wp()],Ne)});import{Controller as Hp,Get as oa,Inject as ea,Param as cn,Post as Gp,Body as zp,HttpCode as Qp}from"@nestjs/common";var Vo,gt,pe,Qt,ra=p(()=>{"use strict";xr();Er();Z();bt();Vo=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},gt=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},pe=function(o,t){return function(e,r){t(e,r,o)}},Qt=class{providerStatus;queryTemplates;constructor(t,e){this.providerStatus=t,this.queryTemplates=e}async status(){return this.providerStatus.list()}listQueryTemplates(t){return this.queryTemplates.list(t)}resolveQueryTemplate(t,e,r){return{query:this.queryTemplates.resolve(t,e,r.params)}}};Vo([oa("status"),gt("design:type",Function),gt("design:paramtypes",[]),gt("design:returntype",Promise)],Qt.prototype,"status",null);Vo([oa(":providerId/query-templates"),pe(0,cn("providerId")),gt("design:type",Function),gt("design:paramtypes",[String]),gt("design:returntype",Array)],Qt.prototype,"listQueryTemplates",null);Vo([Gp(":providerId/query-templates/:templateId/resolve"),Qp(200),pe(0,cn("providerId")),pe(1,cn("templateId")),pe(2,zp(new S(jo))),gt("design:type",Function),gt("design:paramtypes",[String,String,Object]),gt("design:returntype",Object)],Qt.prototype,"resolveQueryTemplate",null);Qt=Vo([Hp("providers"),pe(0,ea(kt)),pe(1,ea(At)),gt("design:paramtypes",[kt,At])],Qt)});import{Body as Yp,Controller as Zp,Get as td,Inject as ed,Patch as od}from"@nestjs/common";var un,Yt,na,de,ia=p(()=>{"use strict";Z();oo();bt();un=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},Yt=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},na=function(o,t){return function(e,r){t(e,r,o)}},de=class{settings;constructor(t){this.settings=t}get(){return this.settings.get()}async update(t){return{settings:await this.settings.update(t),restartRequired:Qn(t)}}};un([td(),Yt("design:type",Function),Yt("design:paramtypes",[]),Yt("design:returntype",Promise)],de.prototype,"get",null);un([od(),na(0,Yp(new S(Po))),Yt("design:type",Function),Yt("design:paramtypes",[Object]),Yt("design:returntype",Promise)],de.prototype,"update",null);de=un([Zp("settings"),na(0,ed(U)),Yt("design:paramtypes",[U])],de)});import{Body as rd,Controller as nd,HttpCode as id,Inject as sd,Param as ad,Post as cd}from"@nestjs/common";var sa,Wo,ln,qe,aa=p(()=>{"use strict";Tt();D();bt();on();sa=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},Wo=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},ln=function(o,t){return function(e,r){t(e,r,o)}},qe=class{secrets;constructor(t){this.secrets=t}async set(t,e){let r=t.trim();if(!r)throw new b("Secret key must not be empty");await this.secrets.set(r,e.value)}};sa([cd(":key"),id(204),ln(0,ad("key")),ln(1,rd(new S(Fo))),Wo("design:type",Function),Wo("design:paramtypes",[String,Object]),Wo("design:returntype",Promise)],qe.prototype,"set",null);qe=sa([nd("secrets"),ln(0,sd(ot)),Wo("design:paramtypes",[Function])],qe)});import{Module as ld}from"@nestjs/common";import{APP_FILTER as pd}from"@nestjs/core";var ud,Xo,ca=p(()=>{"use strict";xe();Nr();fo();ki();xs();Rs();As();Cs();Bs();Us();Vs();ta();ra();ia();aa();uo();ar();ud=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},Xo=class{};Xo=ud([ld({imports:[ft,se,qt,Nt,Zt],controllers:[xt,st,wt,yt,Lt,vt,Ae,Ne,Qt,de,qe],providers:[{provide:pd,useClass:So}]})],Xo)});import{Module as fd}from"@nestjs/common";var dd,Ko,ua=p(()=>{"use strict";mn();hn();bn();uo();fi();fo();xe();Nr();ca();dd=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},Ko=class{};Ko=dd([fd({imports:[Ce,De,Nt,lo,qt,ft,se,Xo],controllers:[fe]})],Ko)});import{apiReference as md}from"@scalar/nestjs-api-reference";function la(o){o.use("/api/docs",md({url:"/api/openapi.json",pageTitle:"Kno Engine API"}))}var pa=p(()=>{"use strict"});import{createServer as hd}from"node:net";function da(o){return typeof o=="object"&&o!==null&&"code"in o&&o.code==="EADDRINUSE"}async function pn(o,t=20){for(let e=0;e<t;e+=1){let r=o+e;if(await bd(r))return r}throw new Error(`No free port found in ${o}\u2013${o+t-1}`)}function bd(o){return new Promise(t=>{let e=hd();e.once("error",()=>{t(!1)}),e.once("listening",()=>{e.close(()=>t(!0))}),e.listen(o)})}var fa=p(()=>{"use strict"});import{Catch as gd,HttpStatus as Ho,NotFoundException as Sd}from"@nestjs/common";import{existsSync as ma,statSync as jd}from"node:fs";import{extname as ha,join as dn,normalize as _d,relative as Id,sep as xd}from"node:path";function ba(o){return(t,e,r)=>{if(t.method!=="GET"&&t.method!=="HEAD"){r();return}if((t.path??"").startsWith("/api")){r();return}let i=Ed(t.path??"/");if(i){let n=dn(o,i);if(vd(o,n)){e.sendFile(i,{root:o},s=>{s&&r()});return}}if(wa(t)){ya(e,o,n=>{n&&!e.headersSent&&e.status(Ho.NOT_FOUND).end()});return}e.status(Ho.NOT_FOUND).end()}}function wa(o){if(o.method!=="GET"&&o.method!=="HEAD")return!1;let t=o.path??"";if(t.startsWith("/api"))return!1;let e=ha(t);return!(e&&e!==".html")}function ya(o,t,e){o.sendFile("index.html",{root:t},e)}function Ed(o){if(o==="/"||o==="")return"index.html";let t=_d(o.replace(/^\/+/,""));return!t||t==="."||t.startsWith("..")||!ha(t)?null:t}function vd(o,t){if(!ma(t))return!1;try{if(!jd(t).isFile())return!1}catch{return!1}let e=Id(o,t);return e!==""&&!e.startsWith(`..${xd}`)&&!e.startsWith("..")}function ga(o){return dn(o,"index.html")}var wd,yd,Go,Sa=p(()=>{"use strict";wd=function(o,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,t,e,r);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(n=(i<3?s(n):i>3?s(t,e,n):s(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n},yd=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},Go=class{staticRoot;constructor(t){this.staticRoot=t}catch(t,e){let r=e.switchToHttp(),i=r.getRequest(),n=r.getResponse();if(wa(i)&&ma(dn(this.staticRoot,"index.html"))){ya(n,this.staticRoot,u=>{u&&!n.headersSent&&n.status(Ho.NOT_FOUND).json({statusCode:Ho.NOT_FOUND,message:"UI index.html could not be served"})});return}let s=t.getStatus(),a=t.getResponse();n.status(s).json(typeof a=="string"?{statusCode:s,message:a}:a)}};Go=wd([gd(Sd),yd("design:paramtypes",[String])],Go)});import{existsSync as Td}from"node:fs";import{dirname as Rd,join as zo}from"node:path";import{fileURLToPath as Od}from"node:url";function ja(){let o=Rd(Od(import.meta.url)),t=[zo(o,"../static"),zo(o,"../../static"),zo(o,"static")];for(let e of t)if(Td(zo(e,"index.html")))return e;return null}var _a=p(()=>{"use strict"});var qd={};import"reflect-metadata";import{existsSync as Pd}from"node:fs";import{Logger as kd}from"@nestjs/common";import{NestFactory as Ad}from"@nestjs/core";async function Nd(){let o=await Ad.create(Ko);o.enableCors(),o.setGlobalPrefix("api"),la(o);let t=ja(),e=t?ga(t):null;t&&e&&Pd(e)?(Qo.log(`Serving UI from ${t}`),o.use(ba(t)),o.useGlobalFilters(new Go(t))):Qo.warn("No UI found (static/index.html missing). GET / will 404; /api still works. Rebuild with `npm run build:release` before publishing.");let r=Number(process.env.PORT??3e3);if(!Number.isInteger(r)||r<1||r>65535)throw new Error(`Invalid PORT: ${process.env.PORT}`);let i=await pn(r);for(let n=0;n<5;n+=1)try{await o.listen(i),i!==r?Qo.warn(`Port ${r} is in use; listening on ${i} instead`):Qo.log(`Listening on http://localhost:${i}`);return}catch(s){if(!da(s))throw s;i=await pn(i+1)}throw new Error(`Could not bind a free port starting at ${r}`)}var Qo,Ia=p(()=>{"use strict";ua();pa();fa();Sa();_a();Qo=new kd("Bootstrap");Nd()});import{readFileSync as Cd}from"node:fs";function Dd(){let o=Cd(new URL("../package.json",import.meta.url),"utf8");return JSON.parse(o).version}var Yo=process.argv.slice(2);Yo.includes("--version")||Yo.includes("-v")?console.log(Dd()):Yo.includes("--help")||Yo.includes("-h")?console.log(["Usage: knoflows [options]","","Starts the knoflows engine (REST API + bundled web client).","","Options:"," -v, --version Print the engine version and exit"," -h, --help Print this message and exit","","Environment:"," PORT Preferred HTTP port (default 3000). If taken, the next free port is used."," KNO_SQLITE_PATH SQLite file path, or :memory: for an ephemeral database"].join(`
144
+ `)):await Promise.resolve().then(()=>(Ia(),qd));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@knoflows/engine",
3
- "version": "0.1.0-alpha.4",
3
+ "version": "0.1.0-alpha.5",
4
4
  "type": "module",
5
5
  "license": "UNLICENSED",
6
6
  "bin": {