@knoflows/engine 0.1.0-alpha.1 → 0.1.0-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/engine.js +11 -10
- package/package.json +5 -4
package/dist/engine.js
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
|
|
2
|
+
var l=(o,t)=>()=>(o&&(t=o(o=0)),t);import{Controller as bs,Get as gs}from"@nestjs/common";var Rn,To,te,Pn=l(()=>{"use strict";Rn=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},To=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},te=class{getHealth(){return{ok:!0,service:"kno-engine",timestamp:new Date().toISOString()}}};Rn([gs(),To("design:type",Function),To("design:paramtypes",[]),To("design:returntype",Object)],te.prototype,"getHealth",null);te=Rn([bs("health")],te)});import{Module as ws}from"@nestjs/common";var ys,_e,An=l(()=>{"use strict";ys=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},_e=class{};_e=ys([ws({})],_e)});import{Module as _s}from"@nestjs/common";var Ss,je,kn=l(()=>{"use strict";Ss=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},je=class{};je=Ss([_s({})],je)});var Pt,Ie=l(()=>{"use strict";Pt=Symbol("TICKET_PROVIDER")});import{randomUUID as js}from"node:crypto";function Is(o,t){return Object.entries(t).every(([e,n])=>o[e]===n)}var xe,Nn=l(()=>{"use strict";xe=class{tickets;comments;constructor(t=[]){this.tickets=new Map(t.map(e=>[e.id,structuredClone(e)])),this.comments=new Map}async get(t){let e=this.tickets.get(t);if(!e)throw new Error(`Ticket not found: ${t}`);return structuredClone(e)}async query(t){return[...this.tickets.values()].filter(e=>Is(e,t)).map(e=>structuredClone(e))}async getComments(t){return await this.get(t),structuredClone(this.comments.get(t)??[])}async postComment(t,e){await this.get(t);let n=this.comments.get(t)??[];n.push({id:js(),subjectId:t,body:e,createdAt:new Date().toISOString()}),this.comments.set(t,n)}async updateStatus(t,e){let n=this.tickets.get(t);if(!n)throw new Error(`Ticket not found: ${t}`);n.status=e}}});var At,Ee=l(()=>{"use strict";At=Symbol("REPO_PROVIDER")});import{randomUUID as xs}from"node:crypto";function Es(o,t){return Object.entries(t).every(([e,n])=>e==="status"?o.raw?.status===n:o[e]===n)}var ve,Cn=l(()=>{"use strict";ve=class{pullRequests;comments;constructor(t=[]){this.pullRequests=new Map(t.map(e=>[e.id,structuredClone(e)])),this.comments=new Map}async get(t){let e=this.pullRequests.get(t);if(!e)throw new Error(`Pull request not found: ${t}`);return structuredClone(e)}async query(t){return[...this.pullRequests.values()].filter(e=>Es(e,t)).map(e=>structuredClone(e))}async getComments(t){return await this.get(t),structuredClone(this.comments.get(t)??[])}async postComment(t,e){await this.get(t);let n=this.comments.get(t)??[];n.push({id:xs(),subjectId:t,body:e,createdAt:new Date().toISOString()}),this.comments.set(t,n)}async updateStatus(t,e){let n=this.pullRequests.get(t);if(!n)throw new Error(`Pull request not found: ${t}`);n.raw={...n.raw??{},status:e}}}});var kt,Te=l(()=>{"use strict";kt=Symbol("DOCUMENTATION_PROVIDER")});import{randomUUID as vs}from"node:crypto";var Ts,Oe,Dn=l(()=>{"use strict";Ts=new Set(["github_wiki","gitlab_wiki","azure_wiki","web"]),Oe=class{pages;contentById;comments;constructor(t=[]){this.pages=new Map,this.contentById=new Map,this.comments=new Map;for(let e of t){let{content:n,...i}=e;this.pages.set(i.id,structuredClone(i)),n!==void 0&&this.contentById.set(i.id,n)}}async get(t){let e=this.pages.get(t);if(!e)throw new Error(`Documentation page not found: ${t}`);return structuredClone(e)}async getContent(t){await this.get(t);let e=this.contentById.get(t);if(e===void 0)throw new Error(`Documentation content not found: ${t}`);return e}async query(t){let e=t.pageIds;if(!Array.isArray(e))throw new Error("Documentation query requires { pageIds: string[] }");let n=[];for(let i of e)n.push(await this.get(String(i)));return n}async getComments(t){let e=await this.get(t);return this.assertCommentsSupported(e),structuredClone(this.comments.get(t)??[])}async postComment(t,e){let n=await this.get(t);this.assertCommentsSupported(n);let i=this.comments.get(t)??[];i.push({id:vs(),subjectId:t,body:e,createdAt:new Date().toISOString()}),this.comments.set(t,i)}assertCommentsSupported(t){if(Ts.has(t.source))throw new Error(`Comments are not supported for documentation source '${t.source}'`)}}});var ee,Oo=l(()=>{"use strict";ee=Symbol("AGENT_PROVIDER")});import{createCipheriv as Os,createDecipheriv as Rs,randomBytes as $n}from"node:crypto";import{mkdir as qn,readFile as Ln,writeFile as Bn}from"node:fs/promises";import{join as Po}from"node:path";function ct(o){return`kno.${o}.apiKey`}function Ns(o){return Po(o,"secrets")}function Fn(o){return new Ao(Ns(o.dataDir),o.keyring)}function Cs(o){try{return o(Re,"__kno_probe__").getPassword(),!0}catch(t){return ko(t)}}function ko(o){let t=o instanceof Error?o.message:String(o);return/noentry|no matching entry|not found|no such/i.test(t)}var Re,Jn,Ps,Ro,As,ks,Ao,H,yt=l(()=>{"use strict";Re="kno-flows";Jn="aes-256-gcm",Ps=12,Ro=32,As="master.key",ks="store.json",Ao=class{secretsDir;keyring;keyringResolved=!1;masterKey=null;constructor(t,e){this.secretsDir=t,this.keyring=e,e!==void 0&&(this.keyringResolved=!0)}async get(t){let e=await this.resolveKeyring();if(e)try{let n=e(Re,t).getPassword();if(n!=null)return n}catch(n){ko(n)||this.disableKeyring()}return this.fileGet(t)}async set(t,e){let n=await this.resolveKeyring();if(n)try{n(Re,t).setPassword(e),await this.fileDelete(t);return}catch{this.disableKeyring()}await this.fileSet(t,e)}async delete(t){let e=await this.resolveKeyring();if(e)try{e(Re,t).deletePassword()}catch(n){ko(n)||this.disableKeyring()}await this.fileDelete(t)}disableKeyring(){this.keyring=null,this.keyringResolved=!0}async resolveKeyring(){if(this.keyringResolved)return this.keyring??null;this.keyringResolved=!0;try{let{Entry:t}=await import("@napi-rs/keyring"),e=(n,i)=>new t(n,i);return Cs(e)?(this.keyring=e,e):(this.keyring=null,null)}catch{return this.keyring=null,null}}async fileGet(t){let n=(await this.readStore())[t];return n?this.decrypt(n):null}async fileSet(t,e){let n=await this.readStore();n[t]=await this.encrypt(e),await this.writeStore(n)}async fileDelete(t){let e=await this.readStore();t in e&&(delete e[t],await this.writeStore(e))}async readStore(){try{let t=await Ln(this.storePath(),"utf8"),e=JSON.parse(t);if(e==null||typeof e!="object"||Array.isArray(e))throw new Error(`Corrupt secret store at ${this.storePath()}`);return e}catch(t){if(t.code==="ENOENT")return{};throw t}}async writeStore(t){await qn(this.secretsDir,{recursive:!0}),await Bn(this.storePath(),JSON.stringify(t,null,2),{encoding:"utf8",mode:384})}async encrypt(t){let e=await this.loadOrCreateMasterKey(),n=$n(Ps),i=Os(Jn,e,n),r=Buffer.concat([i.update(t,"utf8"),i.final()]);return{iv:n.toString("base64"),tag:i.getAuthTag().toString("base64"),ciphertext:r.toString("base64")}}async decrypt(t){let e=await this.loadOrCreateMasterKey(),n=Rs(Jn,e,Buffer.from(t.iv,"base64"));return n.setAuthTag(Buffer.from(t.tag,"base64")),Buffer.concat([n.update(Buffer.from(t.ciphertext,"base64")),n.final()]).toString("utf8")}async loadOrCreateMasterKey(){if(this.masterKey)return this.masterKey;await qn(this.secretsDir,{recursive:!0});let t=this.masterKeyPath();try{let n=(await Ln(t,"utf8")).trim(),i=Buffer.from(n,"hex");if(i.length!==Ro)throw new Error(`Secret store master key at ${t} is not ${Ro} bytes`);return this.masterKey=i,i}catch(n){if(n.code!=="ENOENT")throw n}let e=$n(Ro);return await Bn(t,e.toString("hex"),{encoding:"utf8",mode:384}),this.masterKey=e,e}storePath(){return Po(this.secretsDir,ks)}masterKeyPath(){return Po(this.secretsDir,As)}};H=Symbol("SECRET_STORE")});function Pe(o){let t=ct(o),e=Ls[o]??o;return new Error(`${e} API key not configured \u2014 set '${t}' via the setup script`)}function Un(o){let t=new Map;for(let n of o){let i=n.content.trim();if(!i)continue;let r=t.get(n.tier)??[];r.push(i),t.set(n.tier,r)}let e=[];for(let n of $s){let i=t.get(n);i?.length&&e.push(`## ${Ds[n]}
|
|
3
3
|
${i.join(`
|
|
4
4
|
|
|
5
5
|
`)}`)}return e.join(`
|
|
6
6
|
|
|
7
|
-
`)}function
|
|
8
|
-
${
|
|
9
|
-
${
|
|
7
|
+
`)}function oe(o){let t=[],e=Un(o.knowledge);return e&&t.push(e),t.push(`# Objective
|
|
8
|
+
${o.objective}`),t.push(`# Output format
|
|
9
|
+
${qs[o.outputFormat]}`),t.join(`
|
|
10
10
|
|
|
11
|
-
`)}function Ut(n,t){return t==="free_text"?n:Ro(n)}function Ro(n){let t=[...n.matchAll(/```json\s*([\s\S]*?)```/gi)].map(i=>i[1].trim()),e=[...n.matchAll(/```\s*([\s\S]*?)```/g)].map(i=>i[1].trim()),o=[...t].reverse();o.length===0&&o.push(...[...e].reverse()),o.push(n.trim());for(let i of o)if(i)try{return JSON.parse(i)}catch{continue}throw new Error("No valid JSON block found in agent response")}var yr=et("anthropic"),ue=class{secrets;queryFn;constructor(t,e){this.secrets=t,this.queryFn=e}async run(t){let e=await this.requireApiKey(),o=Ft(t),i={permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,env:{...process.env,ANTHROPIC_API_KEY:e}};t.cwd&&(i.cwd=t.cwd),t.sessionId&&(i.resume=t.sessionId);let r=this.queryFn??wr,s,a,u;for await(let c of r({prompt:o,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:Ut(a,t.outputFormat),sessionId:s}}async requireApiKey(){let t=await this.secrets.get(yr);if(!t)throw ce("anthropic");return t}};async function*wr(n){let{query:t}=await import("@anthropic-ai/claude-agent-sdk"),e=n.options;yield*t({prompt:n.prompt,options:{permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,...e?.cwd?{cwd:e.cwd}:{},...e?.resume?{resume:e.resume}:{},...e?.env?{env:e.env}:{}}})}var gr=et("cursor"),de=class{secrets;sdk;constructor(t,e){this.secrets=t,this.sdk=e}async run(t){let e=await this.requireApiKey(),o=Ft(t),i=this.sdk??await jr(),r=_r(e,t.cwd),s=t.sessionId?await i.resume(t.sessionId,r):await i.create(r);try{let u=await(await s.send(o)).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:Ut(c,t.outputFormat),sessionId:s.agentId}}finally{await s[Symbol.asyncDispose]?.()}}async requireApiKey(){let t=await this.secrets.get(gr);if(!t)throw ce("cursor");return t}};function _r(n,t){return{apiKey:n,model:{id:"composer-2.5"},local:{...t?{cwd:t}:{},settingSources:[]}}}async function jr(){let{Agent:n}=await import("@cursor/sdk");return{create:t=>n.create({apiKey:t.apiKey,model:t.model,local:{...t.local?.cwd?{cwd:t.local.cwd}:{},settingSources:[]}}),resume:(t,e)=>n.resume(t,{apiKey:e.apiKey,model:e.model,local:{...e.local?.cwd?{cwd:e.local.cwd}:{},settingSources:[]}})}}var Mt=Symbol("NOTIFICATION_PROVIDER");var pe=class{async send(t){console.log("[notification]",JSON.stringify(t))}};var Vt=Symbol("KNOWLEDGE_PROVIDER");import{readdir as Sr,readFile as Ir}from"node:fs/promises";import{join as Po}from"node:path";var le=class{baseDir;constructor(t){this.baseDir=t}async resolve(t,e){let o=Po(this.baseDir,t),i;try{i=await Sr(o)}catch(a){if(a.code==="ENOENT")return[];throw a}let r=i.filter(a=>a.endsWith(".md")).sort(),s=[];for(let a of r){let u=Po(o,a),c=await Ir(u,"utf8");s.push({tier:t,content:c,sourceRef:u})}return s}};import{Module as xr}from"@nestjs/common";import{mkdirSync as vr}from"node:fs";import{dirname as Tr,join as Or}from"node:path";import{fileURLToPath as Rr}from"node:url";var Er=function(n,t,e,o){var i=arguments.length,r=i<3?t:o===null?o=Object.getOwnPropertyDescriptor(t,e):o,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(n,t,e,o);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},Ao=Or(Tr(Rr(import.meta.url)),"../../data");vr(Ao,{recursive:!0});var Ot=class{};Ot=Er([xr({providers:[{provide:U,useFactory:()=>To({dataDir:Ao})}],exports:[U]})],Ot);import{Module as Ai}from"@nestjs/common";import{Injectable as Qr}from"@nestjs/common";import{mkdirSync as Zr}from"node:fs";import{dirname as ti}from"node:path";import{fileURLToPath as ei}from"node:url";import{DatabaseSync as Bo}from"node:sqlite";import{drizzle as Hr}from"drizzle-orm/node-sqlite";import{DatabaseSync as Zu}from"node:sqlite";import{defineRelations as Kr}from"drizzle-orm";import{index as Pr,sqliteTable as Ar,text as W}from"drizzle-orm/sqlite-core";var G=Ar("workflow_definitions",{id:W("id").primaryKey(),name:W("name").notNull(),description:W("description"),appliesTo:W("applies_to",{mode:"json"}).$type().notNull(),cardinality:W("cardinality",{enum:["single","batch","aggregate"]}).notNull(),inputSchema:W("input_schema",{mode:"json"}).$type().notNull(),steps:W("steps",{mode:"json"}).$type().notNull(),notificationPolicy:W("notification_policy",{mode:"json"}).$type().notNull(),createdAt:W("created_at").notNull(),updatedAt:W("updated_at").notNull()},n=>[Pr("workflow_definitions_cardinality_idx").on(n.cardinality)]);import{index as No,integer as Nr,sqliteTable as kr,text as Kt}from"drizzle-orm/sqlite-core";var z=kr("subject_views",{id:Kt("id").primaryKey(),name:Kt("name").notNull(),subjectType:Kt("subject_type").$type().notNull(),query:Kt("query",{mode:"json"}).$type().notNull(),description:Kt("description"),order:Nr("order").notNull().default(0)},n=>[No("subject_views_subject_type_idx").on(n.subjectType),No("subject_views_subject_type_order_idx").on(n.subjectType,n.order)]);import{index as fe,integer as $r,sqliteTable as qr,text as E}from"drizzle-orm/sqlite-core";import{index as ko,integer as Cr,sqliteTable as Dr,text as Y}from"drizzle-orm/sqlite-core";var dt=Dr("job_batches",{id:Y("id").primaryKey(),workflowId:Y("workflow_id").notNull(),selection:Y("selection",{mode:"json"}).$type().notNull(),resolvedSubjects:Y("resolved_subjects",{mode:"json"}).$type().notNull(),status:Y("status",{enum:["running","completed","completed_with_issues","failed"]}).notNull(),triggeredBy:Y("triggered_by",{enum:["schedule","view_bulk","multiselect"]}).notNull(),scheduleId:Y("schedule_id"),notificationOverride:Y("notification_override",{mode:"json"}).$type(),notificationSent:Cr("notification_sent",{mode:"boolean"}).notNull(),createdAt:Y("created_at").notNull(),completedAt:Y("completed_at")},n=>[ko("job_batches_workflow_id_idx").on(n.workflowId),ko("job_batches_schedule_id_idx").on(n.scheduleId)]);var Q=qr("jobs",{id:E("id").primaryKey(),workflowId:E("workflow_id").notNull().references(()=>G.id),status:E("status").$type().notNull(),selection:E("selection",{mode:"json"}).$type(),batchId:E("batch_id").references(()=>dt.id),parentJobId:E("parent_job_id"),parentStepExecutionId:E("parent_step_execution_id"),fanOutIndex:$r("fan_out_index"),retryOf:E("retry_of"),context:E("context",{mode:"json"}).$type().notNull(),worktreePath:E("worktree_path"),branch:E("branch"),currentStepId:E("current_step_id"),currentStepExecutionId:E("current_step_execution_id"),createdAt:E("created_at").notNull(),updatedAt:E("updated_at").notNull(),completedAt:E("completed_at")},n=>[fe("jobs_workflow_id_idx").on(n.workflowId),fe("jobs_status_idx").on(n.status),fe("jobs_batch_id_idx").on(n.batchId),fe("jobs_parent_job_id_idx").on(n.parentJobId)]);import{index as Co,sqliteTable as Lr,text as Xt}from"drizzle-orm/sqlite-core";var Rt=Lr("job_subjects",{id:Xt("id").primaryKey(),jobId:Xt("job_id").notNull().references(()=>Q.id),subjectType:Xt("subject_type").$type().notNull(),subjectId:Xt("subject_id").notNull(),snapshot:Xt("snapshot",{mode:"json"}).$type().notNull()},n=>[Co("job_subjects_job_id_idx").on(n.jobId),Co("job_subjects_subject_lookup_idx").on(n.subjectType,n.subjectId)]);import{index as Do,integer as Br,sqliteTable as Jr,text as M}from"drizzle-orm/sqlite-core";var St=Jr("job_step_executions",{id:M("id").primaryKey(),jobId:M("job_id").notNull().references(()=>Q.id),stepDefinitionId:M("step_definition_id").notNull(),type:M("type").$type().notNull(),status:M("status").$type().notNull(),startedAt:M("started_at"),completedAt:M("completed_at"),output:M("output",{mode:"json"}).$type(),error:M("error"),childJobIds:M("child_job_ids",{mode:"json"}).$type(),parentStepExecutionId:M("parent_step_execution_id").references(()=>St.id),iterationIndex:Br("iteration_index")},n=>[Do("job_step_executions_job_id_idx").on(n.jobId),Do("job_step_executions_parent_idx").on(n.parentStepExecutionId)]);import{index as Fr,integer as Ur,sqliteTable as Mr,text as ot}from"drizzle-orm/sqlite-core";var pt=Mr("schedules",{id:ot("id").primaryKey(),workflowId:ot("workflow_id").notNull(),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:Ur("enabled",{mode:"boolean"}).notNull(),lastFiredAt:ot("last_fired_at"),createdAt:ot("created_at").notNull()},n=>[Fr("schedules_enabled_idx").on(n.enabled)]);import{sqliteTable as Vr,text as $o}from"drizzle-orm/sqlite-core";var Ht="default",Pt=Vr("settings",{id:$o("id").primaryKey(),data:$o("data",{mode:"json"}).$type().notNull()});var Xr={workflowDefinitions:G,subjectViews:z,jobs:Q,jobSubjects:Rt,jobStepExecutions:St,jobBatches:dt,schedules:pt,settings:Pt},qo=Kr(Xr,n=>({workflowDefinitions:{},subjectViews:{},schedules:{},settings:{},jobs:{subjects:n.many.jobSubjects({from:n.jobs.id,to:n.jobSubjects.jobId}),stepExecutions:n.many.jobStepExecutions({from:n.jobs.id,to:n.jobStepExecutions.jobId}),batch:n.one.jobBatches({from:n.jobs.batchId,to:n.jobBatches.id})},jobSubjects:{job:n.one.jobs({from:n.jobSubjects.jobId,to:n.jobs.id})},jobStepExecutions:{job:n.one.jobs({from:n.jobStepExecutions.jobId,to:n.jobs.id}),parent:n.one.jobStepExecutions({from:n.jobStepExecutions.parentStepExecutionId,to:n.jobStepExecutions.id,alias:"job_step_executions_parent"}),children:n.many.jobStepExecutions({from:n.jobStepExecutions.id,to:n.jobStepExecutions.parentStepExecutionId,alias:"job_step_executions_children"})},jobBatches:{jobs:n.many.jobs({from:n.jobBatches.id,to:n.jobs.batchId})}}));function Lo(n){return n.exec("PRAGMA foreign_keys = ON;"),Hr({client:n,relations:qo})}function Wr(n,t,e){return n.prepare(`PRAGMA table_info(${t})`).all().some(i=>i.name===e)}function Gr(n){Wr(n,"subject_views","order")||n.exec('ALTER TABLE subject_views ADD COLUMN "order" INTEGER NOT NULL DEFAULT 0'),n.exec(`
|
|
11
|
+
`)}function ne(o,t){return t==="free_text"?o:Mn(o)}function Mn(o){let t=[...o.matchAll(/```json\s*([\s\S]*?)```/gi)].map(i=>i[1].trim()),e=[...o.matchAll(/```\s*([\s\S]*?)```/g)].map(i=>i[1].trim()),n=[...t].reverse();n.length===0&&n.push(...[...e].reverse()),n.push(o.trim());for(let i of n)if(i)try{return JSON.parse(i)}catch{continue}throw new Error("No valid JSON block found in agent response")}var Ds,$s,qs,Ls,Ae=l(()=>{"use strict";yt();Ds={user:"User preferences",organization:"Organization guidelines",project:"Project context"},$s=["user","organization","project"],qs={questionnaire:'Respond with a single fenced JSON block matching this shape exactly: {"questions":[{"id":"<string>","prompt":"<string>"}]}. No other prose outside the fence.',confirmation:'Respond with a single fenced JSON block matching this shape exactly: {"approved":<boolean>}. No other prose outside the fence.',comment_suggestions:'Respond with a single fenced JSON block matching this shape exactly: {"suggestions":[{"body":"<string>"}]}. No other prose outside the fence.',free_text:"Respond in plain text. Do not wrap the answer in a JSON object."},Ls={anthropic:"Anthropic",cursor:"Cursor"}});async function*Js(o){let{query:t}=await import("@anthropic-ai/claude-agent-sdk"),e=o.options;yield*t({prompt:o.prompt,options:{permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,...e?.cwd?{cwd:e.cwd}:{},...e?.resume?{resume:e.resume}:{},...e?.env?{env:e.env}:{}}})}var Bs,ke,Vn=l(()=>{"use strict";Ae();yt();Ae();Bs=ct("anthropic"),ke=class{secrets;queryFn;constructor(t,e){this.secrets=t,this.queryFn=e}async run(t){let e=await this.requireApiKey(),n=oe(t),i={permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,env:{...process.env,ANTHROPIC_API_KEY:e}};t.cwd&&(i.cwd=t.cwd),t.sessionId&&(i.resume=t.sessionId);let r=this.queryFn??Js,s,a,u;for await(let c of r({prompt:n,options:i}))c.session_id&&(s=c.session_id),c.type==="result"&&(c.subtype==="success"&&typeof c.result=="string"?a=c.result:u=c.errors?.join("; ")||c.subtype||"Claude agent returned an error result");if(u)throw new Error(`Claude agent failed: ${u}`);if(a==null)throw new Error("Claude agent returned no result text");if(!s)throw new Error("Claude agent returned no session id");return{raw:a,parsed:ne(a,t.outputFormat),sessionId:s}}async requireApiKey(){let t=await this.secrets.get(Bs);if(!t)throw Pe("anthropic");return t}}});function Us(o,t){return{apiKey:o,model:{id:"composer-2.5"},local:{...t?{cwd:t}:{},settingSources:[]}}}async function Ms(){let{Agent:o}=await import("@cursor/sdk");return{create:t=>o.create({apiKey:t.apiKey,model:t.model,local:{...t.local?.cwd?{cwd:t.local.cwd}:{},settingSources:[]}}),resume:(t,e)=>o.resume(t,{apiKey:e.apiKey,model:e.model,local:{...e.local?.cwd?{cwd:e.local.cwd}:{},settingSources:[]}})}}var Fs,Ne,Kn=l(()=>{"use strict";Ae();yt();Fs=ct("cursor"),Ne=class{secrets;sdk;constructor(t,e){this.secrets=t,this.sdk=e}async run(t){let e=await this.requireApiKey(),n=oe(t),i=this.sdk??await Ms(),r=Us(e,t.cwd),s=t.sessionId?await i.resume(t.sessionId,r):await i.create(r);try{let u=await(await s.send(n)).wait();if(u.status!=="finished")throw new Error(u.error?.message||`Cursor agent ended with status '${u.status}'`);let c=u.result??"";return{raw:c,parsed:ne(c,t.outputFormat),sessionId:s.agentId}}finally{await s[Symbol.asyncDispose]?.()}}async requireApiKey(){let t=await this.secrets.get(Fs);if(!t)throw Pe("cursor");return t}}});var re,No=l(()=>{"use strict";re=Symbol("NOTIFICATION_PROVIDER")});var Ce,Xn=l(()=>{"use strict";Ce=class{async send(t){console.log("[notification]",JSON.stringify(t))}}});var ie,Co=l(()=>{"use strict";ie=Symbol("KNOWLEDGE_PROVIDER")});import{readdir as Vs,readFile as Ks}from"node:fs/promises";import{join as Hn}from"node:path";var De,Wn=l(()=>{"use strict";De=class{baseDir;constructor(t){this.baseDir=t}async resolve(t,e){let n=Hn(this.baseDir,t),i;try{i=await Vs(n)}catch(a){if(a.code==="ENOENT")return[];throw a}let r=i.filter(a=>a.endsWith(".md")).sort(),s=[];for(let a of r){let u=Hn(n,a),c=await Ks(u,"utf8");s.push({tier:t,content:c,sourceRef:u})}return s}}});import{Module as Hs}from"@nestjs/common";import{mkdirSync as Ws}from"node:fs";import{dirname as Gs,join as zs}from"node:path";import{fileURLToPath as Ys}from"node:url";var Xs,Gn,Bt,Do=l(()=>{"use strict";yt();Xs=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},Gn=zs(Gs(Ys(import.meta.url)),"../../data");Ws(Gn,{recursive:!0});Bt=class{};Bt=Xs([Hs({providers:[{provide:H,useFactory:()=>Fn({dataDir:Gn})}],exports:[H]})],Bt)});import{index as Qs,sqliteTable as Zs,text as tt}from"drizzle-orm/sqlite-core";var et,$e=l(()=>{"use strict";et=Zs("workflow_definitions",{id:tt("id").primaryKey(),name:tt("name").notNull(),description:tt("description"),appliesTo:tt("applies_to",{mode:"json"}).$type().notNull(),cardinality:tt("cardinality",{enum:["single","batch","aggregate"]}).notNull(),inputSchema:tt("input_schema",{mode:"json"}).$type().notNull(),steps:tt("steps",{mode:"json"}).$type().notNull(),notificationPolicy:tt("notification_policy",{mode:"json"}).$type().notNull(),createdAt:tt("created_at").notNull(),updatedAt:tt("updated_at").notNull()},o=>[Qs("workflow_definitions_cardinality_idx").on(o.cardinality)])});import{index as zn,integer as ta,sqliteTable as ea,text as se}from"drizzle-orm/sqlite-core";var ot,$o=l(()=>{"use strict";ot=ea("subject_views",{id:se("id").primaryKey(),name:se("name").notNull(),subjectType:se("subject_type").$type().notNull(),query:se("query",{mode:"json"}).$type().notNull(),description:se("description"),order:ta("order").notNull().default(0)},o=>[zn("subject_views_subject_type_idx").on(o.subjectType),zn("subject_views_subject_type_order_idx").on(o.subjectType,o.order)])});import{index as Yn,integer as oa,sqliteTable as na,text as nt}from"drizzle-orm/sqlite-core";var wt,qe=l(()=>{"use strict";wt=na("job_batches",{id:nt("id").primaryKey(),workflowId:nt("workflow_id").notNull(),selection:nt("selection",{mode:"json"}).$type().notNull(),resolvedSubjects:nt("resolved_subjects",{mode:"json"}).$type().notNull(),status:nt("status",{enum:["running","completed","completed_with_issues","failed"]}).notNull(),triggeredBy:nt("triggered_by",{enum:["schedule","view_bulk","multiselect"]}).notNull(),scheduleId:nt("schedule_id"),notificationOverride:nt("notification_override",{mode:"json"}).$type(),notificationSent:oa("notification_sent",{mode:"boolean"}).notNull(),createdAt:nt("created_at").notNull(),completedAt:nt("completed_at")},o=>[Yn("job_batches_workflow_id_idx").on(o.workflowId),Yn("job_batches_schedule_id_idx").on(o.scheduleId)])});import{index as Le,integer as ra,sqliteTable as ia,text as v}from"drizzle-orm/sqlite-core";var rt,ae=l(()=>{"use strict";$e();qe();rt=ia("jobs",{id:v("id").primaryKey(),workflowId:v("workflow_id").notNull().references(()=>et.id),status:v("status").$type().notNull(),selection:v("selection",{mode:"json"}).$type(),batchId:v("batch_id").references(()=>wt.id),parentJobId:v("parent_job_id"),parentStepExecutionId:v("parent_step_execution_id"),fanOutIndex:ra("fan_out_index"),retryOf:v("retry_of"),context:v("context",{mode:"json"}).$type().notNull(),worktreePath:v("worktree_path"),branch:v("branch"),currentStepId:v("current_step_id"),currentStepExecutionId:v("current_step_execution_id"),createdAt:v("created_at").notNull(),updatedAt:v("updated_at").notNull(),completedAt:v("completed_at")},o=>[Le("jobs_workflow_id_idx").on(o.workflowId),Le("jobs_status_idx").on(o.status),Le("jobs_batch_id_idx").on(o.batchId),Le("jobs_parent_job_id_idx").on(o.parentJobId)])});import{index as Qn,sqliteTable as sa,text as ce}from"drizzle-orm/sqlite-core";var Jt,qo=l(()=>{"use strict";ae();Jt=sa("job_subjects",{id:ce("id").primaryKey(),jobId:ce("job_id").notNull().references(()=>rt.id),subjectType:ce("subject_type").$type().notNull(),subjectId:ce("subject_id").notNull(),snapshot:ce("snapshot",{mode:"json"}).$type().notNull()},o=>[Qn("job_subjects_job_id_idx").on(o.jobId),Qn("job_subjects_subject_lookup_idx").on(o.subjectType,o.subjectId)])});import{index as Zn,integer as aa,sqliteTable as ca,text as W}from"drizzle-orm/sqlite-core";var Nt,Lo=l(()=>{"use strict";ae();Nt=ca("job_step_executions",{id:W("id").primaryKey(),jobId:W("job_id").notNull().references(()=>rt.id),stepDefinitionId:W("step_definition_id").notNull(),type:W("type").$type().notNull(),status:W("status").$type().notNull(),startedAt:W("started_at"),completedAt:W("completed_at"),output:W("output",{mode:"json"}).$type(),error:W("error"),childJobIds:W("child_job_ids",{mode:"json"}).$type(),parentStepExecutionId:W("parent_step_execution_id").references(()=>Nt.id),iterationIndex:aa("iteration_index")},o=>[Zn("job_step_executions_job_id_idx").on(o.jobId),Zn("job_step_executions_parent_idx").on(o.parentStepExecutionId)])});import{index as ua,integer as da,sqliteTable as pa,text as ut}from"drizzle-orm/sqlite-core";var St,Bo=l(()=>{"use strict";St=pa("schedules",{id:ut("id").primaryKey(),workflowId:ut("workflow_id").notNull(),viewId:ut("view_id").notNull(),triggerType:ut("trigger_type",{enum:["cron"]}).notNull(),cadence:ut("cadence").notNull(),notificationOverride:ut("notification_override",{mode:"json"}).$type(),missedFirePolicy:ut("missed_fire_policy",{enum:["skip","catch_up"]}).notNull(),enabled:da("enabled",{mode:"boolean"}).notNull(),lastFiredAt:ut("last_fired_at"),createdAt:ut("created_at").notNull()},o=>[ua("schedules_enabled_idx").on(o.enabled)])});import{sqliteTable as la,text as tr}from"drizzle-orm/sqlite-core";var ue,Ft,Jo=l(()=>{"use strict";ue="default",Ft=la("settings",{id:tr("id").primaryKey(),data:tr("data",{mode:"json"}).$type().notNull()})});import{defineRelations as fa}from"drizzle-orm";var ma,er,or=l(()=>{"use strict";$e();$o();ae();qo();Lo();qe();Bo();Jo();ma={workflowDefinitions:et,subjectViews:ot,jobs:rt,jobSubjects:Jt,jobStepExecutions:Nt,jobBatches:wt,schedules:St,settings:Ft},er=fa(ma,o=>({workflowDefinitions:{},subjectViews:{},schedules:{},settings:{},jobs:{subjects:o.many.jobSubjects({from:o.jobs.id,to:o.jobSubjects.jobId}),stepExecutions:o.many.jobStepExecutions({from:o.jobs.id,to:o.jobStepExecutions.jobId}),batch:o.one.jobBatches({from:o.jobs.batchId,to:o.jobBatches.id})},jobSubjects:{job:o.one.jobs({from:o.jobSubjects.jobId,to:o.jobs.id})},jobStepExecutions:{job:o.one.jobs({from:o.jobStepExecutions.jobId,to:o.jobs.id}),parent:o.one.jobStepExecutions({from:o.jobStepExecutions.parentStepExecutionId,to:o.jobStepExecutions.id,alias:"job_step_executions_parent"}),children:o.many.jobStepExecutions({from:o.jobStepExecutions.id,to:o.jobStepExecutions.parentStepExecutionId,alias:"job_step_executions_children"})},jobBatches:{jobs:o.many.jobs({from:o.jobBatches.id,to:o.jobs.batchId})}}))});import{drizzle as ha}from"drizzle-orm/node-sqlite";import{DatabaseSync as _l}from"node:sqlite";function nr(o){return o.exec("PRAGMA foreign_keys = ON;"),ha({client:o,relations:er})}var rr=l(()=>{"use strict";or()});function ba(o,t,e){return o.prepare(`PRAGMA table_info(${t})`).all().some(i=>i.name===e)}function ga(o){ba(o,"subject_views","order")||o.exec('ALTER TABLE subject_views ADD COLUMN "order" INTEGER NOT NULL DEFAULT 0'),o.exec(`
|
|
12
12
|
CREATE INDEX IF NOT EXISTS subject_views_subject_type_order_idx
|
|
13
13
|
ON subject_views (subject_type, "order");
|
|
14
|
-
`)}function
|
|
14
|
+
`)}function Fo(o){o.exec(`
|
|
15
15
|
PRAGMA foreign_keys = ON;
|
|
16
16
|
|
|
17
17
|
CREATE TABLE IF NOT EXISTS workflow_definitions (
|
|
@@ -127,7 +127,8 @@ ${hr[n.outputFormat]}`),t.join(`
|
|
|
127
127
|
id TEXT PRIMARY KEY NOT NULL,
|
|
128
128
|
data TEXT NOT NULL
|
|
129
129
|
);
|
|
130
|
-
`),Gr(n)}var zr=function(n,t,e,o){var i=arguments.length,r=i<3?t:o===null?o=Object.getOwnPropertyDescriptor(t,e):o,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(n,t,e,o);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},Yr=function(n,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,t)},V=class{sqlite;db;constructor(){let e=process.env.KNO_SQLITE_PATH??ei(new URL("../../data/kno.db",import.meta.url));e===":memory:"?this.sqlite=new Bo(":memory:"):(Zr(ti(e),{recursive:!0}),this.sqlite=new Bo(e)),this.db=Lo(this.sqlite),We(this.sqlite)}async onModuleInit(){We(this.sqlite)}getDb(){return this.db}getSqlite(){return this.sqlite}};V=zr([Qr(),Yr("design:paramtypes",[])],V);import{Injectable as ri}from"@nestjs/common";import{eq as Jo}from"drizzle-orm";var oi=function(n,t,e,o){var i=arguments.length,r=i<3?t:o===null?o=Object.getOwnPropertyDescriptor(t,e):o,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(n,t,e,o);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},ni=function(n,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,t)},D=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(G).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 o=await this.get(t);return o?(await this.db.update(G).set({name:e.name??o.name,description:e.description!==void 0?e.description??null:o.description??null,appliesTo:e.appliesTo??o.appliesTo,cardinality:e.cardinality??o.cardinality,inputSchema:e.inputSchema??o.inputSchema,steps:e.steps??o.steps,notificationPolicy:e.notificationPolicy??o.notificationPolicy,updatedAt:new Date().toISOString()}).where(Jo(G.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(o=>this.toDomain(o))}async delete(t){if(!await this.get(t))return!1;try{this.sqlite?.exec("PRAGMA foreign_keys = OFF"),await this.db.delete(G).where(Jo(G.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}}};D=oi([ri(),ni("design:paramtypes",[Object,Function])],D);import{Injectable as ai}from"@nestjs/common";import{eq as Ge}from"drizzle-orm";var ii=function(n,t,e,o){var i=arguments.length,r=i<3?t:o===null?o=Object.getOwnPropertyDescriptor(t,e):o,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(n,t,e,o);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},si=function(n,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,t)},Fo=["ticket","pull_request","documentation"],$=class{db;constructor(t){this.db=t}async create(t){let e=await this.nextOrder(t.subjectType);return await this.db.insert(z).values({id:t.id,name:t.name,subjectType:t.subjectType,query:t.query,description:t.description??null,order:e}),await this.get(t.id)}async get(t){let e=await this.db.query.subjectViews.findFirst({where:{id:t}});return e?this.toDomain(e):null}async update(t,e){let o=await this.get(t);return o?(await this.db.update(z).set({name:e.name??o.name,subjectType:e.subjectType??o.subjectType,query:e.query??o.query,description:e.description!==void 0?e.description??null:o.description??null}).where(Ge(z.id,t)),this.get(t)):null}async list(t={}){let e=t.subjectType?await this.db.query.subjectViews.findMany({where:{subjectType:t.subjectType}}):await this.db.query.subjectViews.findMany();return this.sortViews(e.map(o=>this.toDomain(o)))}async reorder(t){let e=[];for(let i of t){let r=await this.get(i);if(!r)return[];e.push(r)}let o=e[0].subjectType;if(!e.every(i=>i.subjectType===o))return[];for(let i=0;i<t.length;i+=1)await this.db.update(z).set({order:i}).where(Ge(z.id,t[i]));return this.list({subjectType:o})}async delete(t){return await this.get(t)?(await this.db.delete(z).where(Ge(z.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(o=>o.order))+1}sortViews(t){return[...t].sort((e,o)=>{let i=Fo.indexOf(e.subjectType)-Fo.indexOf(o.subjectType);return i!==0?i:e.order-o.order})}toDomain(t){return{id:t.id,name:t.name,subjectType:t.subjectType,query:t.query,order:t.order,...t.description!=null?{description:t.description}:{}}}};$=ii([ai(),si("design:paramtypes",[Object])],$);import{Injectable as di}from"@nestjs/common";import{eq as ze}from"drizzle-orm";import{randomUUID as pi}from"node:crypto";var ci=function(n,t,e,o){var i=arguments.length,r=i<3?t:o===null?o=Object.getOwnPropertyDescriptor(t,e):o,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(n,t,e,o);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},ui=function(n,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,t)},S=class{db;constructor(t){this.db=t}async create(t){return await this.db.insert(Q).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 o=await this.get(t);if(!o)return null;let i={...o,...e,id:t,context:e.context??o.context,stepHistory:e.stepHistory??o.stepHistory,updatedAt:e.updatedAt??new Date().toISOString()};return await this.db.update(Q).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(ze(Q.id,t)),e.subjectContext!==void 0&&await this.replaceSubjects(t,e.subjectContext),e.stepHistory!==void 0&&await this.replaceStepExecutions(t,e.stepHistory),this.get(t)}async list(t={}){let e={};t.workflowId!==void 0&&(e.workflowId=t.workflowId),t.status!==void 0&&(e.status=t.status),t.batchId!==void 0&&(e.batchId=t.batchId),t.parentJobId!==void 0&&(e.parentJobId=t.parentJobId),t.parentStepExecutionId!==void 0&&(e.parentStepExecutionId=t.parentStepExecutionId);let i=(Object.keys(e).length>0?await this.db.query.jobs.findMany({where:e,with:{subjects:!0,stepExecutions:!0}}):await this.db.query.jobs.findMany({with:{subjects:!0,stepExecutions:!0}})).map(r=>this.toDomain(r,r.subjects,r.stepExecutions));return t.topLevelOnly?i.filter(r=>r.batchId==null&&r.parentJobId==null):i}jobToRow(t){return{id:t.id,workflowId:t.workflowId,status:t.status,selection:t.selection??null,batchId:t.batchId??null,parentJobId:t.parentJobId??null,parentStepExecutionId:t.parentStepExecutionId??null,fanOutIndex:t.fanOutIndex??null,retryOf:t.retryOf??null,context:t.context,worktreePath:t.worktreePath??null,branch:t.branch??null,currentStepId:t.currentStepId??null,currentStepExecutionId:t.currentStepExecutionId??null,createdAt:t.createdAt,updatedAt:t.updatedAt,completedAt:t.completedAt??null}}async replaceSubjects(t,e){await this.db.delete(Rt).where(ze(Rt.jobId,t));let o=li(e);o.length!==0&&await this.db.insert(Rt).values(o.map(i=>({id:pi(),jobId:t,subjectType:i.subjectType,subjectId:i.id,snapshot:i})))}async replaceStepExecutions(t,e){await this.db.delete(St).where(ze(St.jobId,t));let o=Mo(t,e);o.length!==0&&await this.db.insert(St).values(o)}toDomain(t,e,o){let i=fi(e.map(s=>s.snapshot)),r=mi(o);return{id:t.id,workflowId:t.workflowId,status:t.status,...i?{subjectContext:i}:{},...t.selection!=null?{selection:t.selection}:{},...t.batchId!=null?{batchId:t.batchId}:{},...t.parentJobId!=null?{parentJobId:t.parentJobId}:{},...t.parentStepExecutionId!=null?{parentStepExecutionId:t.parentStepExecutionId}:{},...t.fanOutIndex!=null?{fanOutIndex:t.fanOutIndex}:{},...t.retryOf!=null?{retryOf:t.retryOf}:{},context:t.context,...t.worktreePath!=null?{worktreePath:t.worktreePath}:{},...t.branch!=null?{branch:t.branch}:{},...t.currentStepId!=null?{currentStepId:t.currentStepId}:{},...t.currentStepExecutionId!=null?{currentStepExecutionId:t.currentStepExecutionId}:{},stepHistory:r,createdAt:t.createdAt,updatedAt:t.updatedAt,...t.completedAt!=null?{completedAt:t.completedAt}:{}}}};S=ci([di(),ui("design:paramtypes",[Object])],S);function li(n){return n?n.mode==="single"?[n.subject]:n.subjects:[]}function fi(n){if(n.length!==0)return n.length===1?{mode:"single",subject:n[0]}:{mode:"collection",subjects:n}}function Mo(n,t,e=null,o=null){let i=[];for(let r of t)if(i.push({id:r.id,jobId:n,stepDefinitionId:r.stepDefinitionId,type:r.type,status:r.status,startedAt:r.startedAt??null,completedAt:r.completedAt??null,output:r.output??null,error:r.error??null,childJobIds:r.childJobIds??null,parentStepExecutionId:e,iterationIndex:o}),r.iterations)for(let s of r.iterations)i.push(...Mo(n,s.stepExecutions,r.id,s.index));return i}function mi(n){let t=new Map;for(let i of n){let r=i.parentStepExecutionId,s=t.get(r)??[];s.push(i),t.set(r,s)}let e=i=>{let r=t.get(i)??[];if(r.length===0)return;let s=new Map;for(let a of r){if(a.iterationIndex==null)continue;let u=s.get(a.iterationIndex)??[];u.push(a),s.set(a.iterationIndex,u)}if(s.size!==0)return[...s.entries()].sort(([a],[u])=>a-u).map(([a,u])=>{let c=u.map(p=>Uo(p,e(p.id)));return{index:a,stepExecutions:c,startedAt:hi(c),...yi(c)?{completedAt:bi(c)}:{}}})};return(t.get(null)??[]).filter(i=>i.iterationIndex==null).map(i=>Uo(i,e(i.id)))}function Uo(n,t){return{id:n.id,stepDefinitionId:n.stepDefinitionId,type:n.type,status:n.status,...n.startedAt!=null?{startedAt:n.startedAt}:{},...n.completedAt!=null?{completedAt:n.completedAt}:{},...n.output!==null&&n.output!==void 0?{output:n.output}:{},...n.error!=null?{error:n.error}:{},...n.childJobIds!=null?{childJobIds:n.childJobIds}:{},...t&&t.length>0?{iterations:t}:{}}}function hi(n){let t=n.map(e=>e.startedAt).filter(e=>e!=null);return t.length===0?"":t.reduce((e,o)=>e<o?e:o)}function bi(n){return n.map(e=>e.completedAt).filter(e=>e!=null).reduce((e,o)=>e>o?e:o)}function yi(n){return n.length>0&&n.every(t=>t.completedAt!=null)}import{Injectable as _i}from"@nestjs/common";import{eq as ji}from"drizzle-orm";var wi=function(n,t,e,o){var i=arguments.length,r=i<3?t:o===null?o=Object.getOwnPropertyDescriptor(t,e):o,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(n,t,e,o);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},gi=function(n,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,t)},q=class{db;constructor(t){this.db=t}async create(t){return await this.db.insert(dt).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(o=>o.id)):null}async update(t,e){let o=await this.get(t);return o?(await this.db.update(dt).set({workflowId:e.workflowId??o.workflowId,selection:e.selection??o.selection,resolvedSubjects:e.resolvedSubjects??o.resolvedSubjects,status:e.status??o.status,triggeredBy:e.triggeredBy??o.triggeredBy,scheduleId:e.scheduleId!==void 0?e.scheduleId??null:o.scheduleId??null,notificationOverride:e.notificationOverride!==void 0?e.notificationOverride??null:o.notificationOverride??null,notificationSent:e.notificationSent??o.notificationSent,createdAt:e.createdAt??o.createdAt,completedAt:e.completedAt!==void 0?e.completedAt??null:o.completedAt??null}).where(ji(dt.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(o=>this.toDomain(o,o.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}:{}}}};q=wi([_i(),gi("design:paramtypes",[Object])],q);import{Injectable as Ei}from"@nestjs/common";import{eq as Vo}from"drizzle-orm";var Si=function(n,t,e,o){var i=arguments.length,r=i<3?t:o===null?o=Object.getOwnPropertyDescriptor(t,e):o,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(n,t,e,o);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},Ii=function(n,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,t)},nt=class{db;constructor(t){this.db=t}async create(t){return await this.db.insert(pt).values({id:t.id,workflowId:t.workflowId,viewId:t.viewId,triggerType:t.trigger.type,cadence:t.trigger.cadence,notificationOverride:t.notificationOverride??null,missedFirePolicy:t.missedFirePolicy,enabled:t.enabled,lastFiredAt:t.lastFiredAt??null,createdAt:t.createdAt}),await this.get(t.id)}async get(t){let e=await this.db.query.schedules.findFirst({where:{id:t}});return e?this.toDomain(e):null}async update(t,e){let o=await this.get(t);if(!o)return null;let i=e.trigger??o.trigger;return await this.db.update(pt).set({workflowId:e.workflowId??o.workflowId,viewId:e.viewId??o.viewId,triggerType:i.type,cadence:i.cadence,notificationOverride:e.notificationOverride!==void 0?e.notificationOverride??null:o.notificationOverride??null,missedFirePolicy:e.missedFirePolicy??o.missedFirePolicy,enabled:e.enabled??o.enabled,lastFiredAt:e.lastFiredAt!==void 0?e.lastFiredAt??null:o.lastFiredAt??null,createdAt:e.createdAt??o.createdAt}).where(Vo(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(o=>this.toDomain(o))}async delete(t){return await this.get(t)?(await this.db.delete(pt).where(Vo(pt.id,t)),!0):!1}async findDue(t){return(await this.list({enabled:!0})).filter(o=>o.lastFiredAt==null||o.lastFiredAt<t)}toDomain(t){return{id:t.id,workflowId:t.workflowId,viewId:t.viewId,trigger:{type:"cron",cadence:t.cadence},...t.notificationOverride!=null?{notificationOverride:t.notificationOverride}:{},missedFirePolicy:t.missedFirePolicy,enabled:t.enabled,...t.lastFiredAt!=null?{lastFiredAt:t.lastFiredAt}:{},createdAt:t.createdAt}}};nt=Si([Ei(),Ii("design:paramtypes",[Object])],nt);import{Injectable as Ti}from"@nestjs/common";import{eq as Oi}from"drizzle-orm";var xi=function(n,t,e,o){var i=arguments.length,r=i<3?t:o===null?o=Object.getOwnPropertyDescriptor(t,e):o,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(n,t,e,o);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},vi=function(n,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,t)},N=class{db;constructor(t){this.db=t}async get(){let t=await this.db.query.settings.findFirst({where:{id:Ht}});return Ye(t?t.data:{})}async update(t){let e=Ri(await this.get(),t);return await this.db.query.settings.findFirst({where:{id:Ht}})?await this.db.update(Pt).set({data:e}).where(Oi(Pt.id,Ht)):await this.db.insert(Pt).values({id:Ht,data:e}),e}};N=xi([Ti(),vi("design:paramtypes",[Object])],N);function Ri(n,t){let e={...n.activeProviders,...t.activeProviders},o=t.jira!==void 0?{...n.jira,...t.jira}:n.jira,i=t.bitbucket!==void 0?{...n.bitbucket,...t.bitbucket}:n.bitbucket;return Ye({activeProviders:e,...o&&Object.keys(o).length>0?{jira:o}:{},...i&&Object.keys(i).length>0?{bitbucket:i}:{}})}function Ye(n){return{...n,activeProviders:{ticket:n.activeProviders?.ticket??"manual",repo:n.activeProviders?.repo??"manual",agent:n.activeProviders?.agent??"claude"},...n.jira?{jira:n.jira}:{},...n.bitbucket?{bitbucket:n.bitbucket}:{}}}function Ko(n){return Object.prototype.hasOwnProperty.call(n,"activeProviders")}var Pi=function(n,t,e,o){var i=arguments.length,r=i<3?t:o===null?o=Object.getOwnPropertyDescriptor(t,e):o,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(n,t,e,o);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},Ni=[D,$,S,q,nt,N],Z=class{};Z=Pi([Ai({providers:[V,{provide:D,useFactory:n=>new D(n.getDb(),n.getSqlite()),inject:[V]},{provide:$,useFactory:n=>new $(n.getDb()),inject:[V]},{provide:S,useFactory:n=>new S(n.getDb()),inject:[V]},{provide:q,useFactory:n=>new q(n.getDb()),inject:[V]},{provide:nt,useFactory:n=>new nt(n.getDb()),inject:[V]},{provide:N,useFactory:n=>new N(n.getDb()),inject:[V]}],exports:[V,...Ni]})],Z);import{Injectable as Xi,Logger as Hi,Inject as Wi}from"@nestjs/common";function Qe(n){return n==null?"":typeof n=="string"?n:Ho(n).replace(/\n+$/,"")}function Xo(n){return{version:1,type:"doc",content:n.split(`
|
|
131
|
-
`).map(e=>({type:"paragraph",content:e.length===0?[]:[{type:"text",text:e}]}))}}function
|
|
132
|
-
`;let e=(t.content??[]).map(
|
|
133
|
-
`:e}var At="kno.jira.apiToken",ki=50,Ci=10,me=500,ye=class{secrets;settings;fetchFn;constructor(t,e,o=fetch){this.secrets=t,this.settings=e,this.fetchFn=o}async get(t){let{baseUrl:e}=await this.requireConfig(),o=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(t)}`);return Wo(o,e)}async query(t){let{baseUrl:e}=await this.requireConfig(),o=Di(t),i=[],r,s=new Set;for(let a=0;a<Ci&&i.length<me;a++){let u={jql:o,maxResults:Math.min(ki,me-i.length),fields:["summary","description","status","assignee"]};r&&(u.nextPageToken=r);let c=await this.request("POST","/rest/api/3/search/jql",{body:u}),p=Array.isArray(c.issues)?c.issues:[];for(let b of p){if(i.length>=me)break;i.push(Wo(b,e))}let l=typeof c.nextPageToken=="string"?c.nextPageToken:void 0;if(c.isLast===!0||!l||p.length===0||l===r||s.has(l))break;s.add(l),r=l}return i}async getComments(t){let e=[],o=0,i=100,r=me;for(;e.length<r;){let s=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(t)}/comment?startAt=${o}&maxResults=${i}`),a=Array.isArray(s.comments)?s.comments:[];for(let u of a)e.push({id:String(u.id??""),subjectId:t,body:Qe(u.body),...u.author?.displayName?{author:u.author.displayName}:{},createdAt:u.created??"",raw:u});if(o+=a.length,a.length===0||typeof s.total=="number"&&o>=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:Xo(e)}})}async updateStatus(t,e){let o=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(t)}/transitions`),i=Array.isArray(o.transitions)?o.transitions:[],r=e.trim().toLowerCase(),s=i.find(a=>(a.to?.name??"").trim().toLowerCase()===r);if(!s?.id){let a=i.map(c=>c.to?.name).filter(c=>typeof c=="string"&&c.length>0),u=a.length>0?a.join(", "):"(none)";throw new Error(`No Jira transition to status '${e}' from the current state. Available: ${u}`)}await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(t)}/transitions`,{body:{transition:{id:s.id}}})}async requireConfig(){let t=(await this.settings.get()).jira,e=t?.baseUrl?.trim(),o=t?.email?.trim(),i=await this.secrets.get(At),r=[];if(e||r.push("settings.jira.baseUrl"),o||r.push("settings.jira.email"),i||r.push(`SecretStore '${At}'`),r.length>0)throw new Error(`Jira is not configured \u2014 missing ${r.join(", ")}. Set jira.baseUrl and jira.email via PATCH /api/settings, and store the API token with: POST /api/secrets/${At} or npm --workspace apps/engine run set-secret -- ${At} <value>`);return{baseUrl:e,email:o,token:i}}async request(t,e,o={}){let{baseUrl:i,email:r,token:s}=await this.requireConfig(),a=`${i.replace(/\/$/,"")}${e}`,u={Authorization:`Basic ${Buffer.from(`${r}:${s}`).toString("base64")}`,Accept:"application/json"};o.body!==void 0&&(u["Content-Type"]="application/json");let c=await this.fetchFn(a,{method:t,headers:u,...o.body!==void 0?{body:JSON.stringify(o.body)}:{}});if(!c.ok){let l=await c.text().catch(()=>"");throw new Error(`Jira ${t} ${e} failed (${c.status}): ${l||c.statusText}`)}if(c.status===204)return;let p=await c.text();if(p)return JSON.parse(p)}};function Di(n){if(typeof n.jql=="string"&&n.jql.trim().length>0)return n.jql;let t=[];if(he(n.project)&&t.push(`project = ${be(n.project)}`),he(n.status)&&t.push(`status = ${be(n.status)}`),he(n.assignee)&&t.push(`assignee = ${be(n.assignee)}`),he(n.sprintId)){let e=n.sprintId;t.push(typeof e=="number"||/^\d+$/.test(String(e))?`sprint = ${Number(e)}`:`sprint = ${be(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 he(n){return n!=null&&n!==""}function be(n){return`"${String(n).replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Wo(n,t){let e=String(n.key??n.id??""),o=n.fields??{},i=Qe(o.description);return{id:e,source:"jira",title:String(o.summary??""),...i?{description:i}:{},status:String(o.status?.name??""),...o.assignee?.displayName?{assignee:String(o.assignee.displayName)}:{},url:`${t.replace(/\/$/,"")}/browse/${e}`,raw:n}}var Nt="kno.bitbucket.apiToken",$i="https://api.bitbucket.org/2.0";var ge=class{secrets;settings;fetchFn;constructor(t,e,o=fetch){this.secrets=t,this.settings=e,this.fetchFn=o}async get(t){let{repoSlug:e,prNumber:o}=we(t),{workspace:i}=await this.requireConfig(),r=await this.request("GET",this.prPath(i,e,o));return Go(r,e)}async query(t){let e=Li(t),{baseUrl:o,workspace:i}=await this.requireConfig(),r=Bi(t),s=[],a=new Set,u=new URLSearchParams({pagelen:String(50)});r&&u.set("q",r);let c=`${o.replace(/\/$/,"")}/repositories/${encodeURIComponent(i)}/${encodeURIComponent(e)}/pullrequests?${u.toString()}`;for(let p=0;p<10&&s.length<500&&!(!c||a.has(c));p++){a.add(c);let l=await this.request("GET",c),b=Array.isArray(l.values)?l.values:[];for(let j of b){if(s.length>=500)break;s.push(Go(j,e))}let f=typeof l.next=="string"&&l.next.length>0?l.next:void 0;if(!f||b.length===0)break;c=f}return s}async getComments(t){let{repoSlug:e,prNumber:o}=we(t),{workspace:i}=await this.requireConfig(),r=[],s=new Set,a=`${this.prPath(i,e,o)}/comments?pagelen=50`;for(let u=0;u<10&&r.length<500&&!(!a||s.has(a));u++){s.add(a);let c=await this.request("GET",a),p=Array.isArray(c.values)?c.values:[];for(let b of p)r.push(Ui(b,t));let l=typeof c.next=="string"&&c.next.length>0?c.next:void 0;if(!l||p.length===0)break;a=l}return r}async postComment(t,e){let{repoSlug:o,prNumber:i}=we(t),{workspace:r}=await this.requireConfig();await this.request("POST",`${this.prPath(r,o,i)}/comments`,{body:{content:{raw:e}}})}async updateStatus(t,e){let{repoSlug:o,prNumber:i}=we(t),{workspace:r}=await this.requireConfig(),s=Ji(e);await this.request("POST",`${this.prPath(r,o,i)}/${s}`)}prPath(t,e,o){return`/repositories/${encodeURIComponent(t)}/${encodeURIComponent(e)}/pullrequests/${encodeURIComponent(o)}`}async requireConfig(){let t=(await this.settings.get()).bitbucket,e=(t?.baseUrl?.trim()||$i).replace(/\/$/,""),o=t?.email?.trim(),i=t?.workspace?.trim(),r=await this.secrets.get(Nt),s=[];if(o||s.push("settings.bitbucket.email"),i||s.push("settings.bitbucket.workspace"),r||s.push(`SecretStore '${Nt}'`),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/${Nt} or npm --workspace apps/engine run set-secret -- ${Nt} <value>`);return{baseUrl:e,email:o,workspace:i,token:r}}async request(t,e,o={}){let{baseUrl:i,email:r,token:s}=await this.requireConfig(),a=e.startsWith("http://")||e.startsWith("https://")?e:`${i}${e.startsWith("/")?e:`/${e}`}`,u={Authorization:`Basic ${Buffer.from(`${r}:${s}`).toString("base64")}`,Accept:"application/json"};o.body!==void 0&&(u["Content-Type"]="application/json");let c=await this.fetchFn(a,{method:t,headers:u,...o.body!==void 0?{body:JSON.stringify(o.body)}:{}});if(!c.ok){let l=await c.text().catch(()=>"");throw new Error(`Bitbucket ${t} ${e} failed (${c.status}): ${l||c.statusText}`)}if(c.status===204)return;let p=await c.text();if(p)return JSON.parse(p)}};function we(n){let t=n.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 '${n}'`);let o=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 '${n}'`);return{repoSlug:o,prNumber:i}}function qi(n,t){return`${n}#${t}`}function Li(n){let t=n.repoSlug;if(typeof t!="string"||t.trim().length===0)throw new Error("Bitbucket query requires filter.repoSlug \u2014 PR listing is scoped per repository");return t.trim()}function Bi(n){if(typeof n.q=="string"&&n.q.trim().length>0)return n.q;if(Fi(n.state)){let t=String(n.state).trim().toUpperCase();if(t!=="OPEN"&&t!=="MERGED"&&t!=="DECLINED")throw new Error(`Bitbucket query filter.state must be OPEN, MERGED, or DECLINED, got '${String(n.state)}'`);return`state="${t}"`}}function Ji(n){let t=n.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 '${n}'. Accepted: approved, declined/rejected, merged`)}function Fi(n){return n!=null&&n!==""}function Go(n,t){let e=String(n.id??""),o=typeof n.description=="string"?n.description:"";return{id:qi(t,e),source:"bitbucket",title:String(n.title??""),...o?{description:o}:{},sourceBranch:String(n.source?.branch?.name??""),targetBranch:String(n.destination?.branch?.name??""),...n.author?.display_name?{author:n.author.display_name}:{},...n.links?.html?.href?{url:n.links.html.href}:{},raw:n}}function Ui(n,t){let e=n.user?.display_name??n.author?.display_name;return{id:String(n.id??""),subjectId:t,body:n.content?.raw??"",...e?{author:e}:{},createdAt:n.created_on??"",raw:n}}var Mi=function(n,t,e,o){var i=arguments.length,r=i<3?t:o===null?o=Object.getOwnPropertyDescriptor(t,e):o,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(n,t,e,o);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},Vi=function(n,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,t)},Ki=function(n,t){return function(e,o){t(e,o,n)}},Ze,Gi=[{providerId:"anthropic",secretKey:et("anthropic")},{providerId:"cursor",secretKey:et("cursor")},{providerId:"jira",secretKey:At},{providerId:"bitbucket",secretKey:Nt}];async function zo(n){let t=[];for(let e of Gi){let o=await n.get(e.secretKey);t.push({providerId:e.providerId,secretKey:e.secretKey,configured:typeof o=="string"&&o.length>0})}return t}async function zi(n,t){let e=await zo(n);for(let o of e)o.configured||t(`${o.providerId} API key not configured (looked up as '${o.secretKey}'). GET /api/providers/status lists what's missing; store a key with: POST /api/secrets/${o.secretKey} or npm --workspace apps/engine run set-secret -- ${o.secretKey} <value>`)}function Yo(n={}){let t=n.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 Qo(n={}){let t=n.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 Zo(n={}){let t=n.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 lt=Ze=class{secrets;logger=new Hi(Ze.name);constructor(t){this.secrets=t}async onModuleInit(){await zi(this.secrets,t=>this.logger.warn(t))}list(){return zo(this.secrets)}};lt=Ze=Mi([Xi(),Ki(0,Wi(U)),Vi("design:paramtypes",[Function])],lt);import{fileURLToPath as Zi}from"node:url";import{dirname as ts,join as es}from"node:path";var Yi=function(n,t,e,o){var i=arguments.length,r=i<3?t:o===null?o=Object.getOwnPropertyDescriptor(t,e):o,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(n,t,e,o);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},os=es(ts(Zi(import.meta.url)),"../../../knowledge"),ft=class{};ft=Yi([Qi({imports:[Ot,Z],providers:[{provide:gt,useFactory:async(n,t)=>Qo(await t.get())==="jira"?new ye(n,t):new re([]),inject:[U,N]},{provide:_t,useFactory:async(n,t)=>Zo(await t.get())==="bitbucket"?new ge(n,t):new ie([]),inject:[U,N]},{provide:jt,useFactory:()=>new se([])},{provide:Jt,useFactory:async(n,t)=>Yo(await t.get())==="cursor"?new de(n):new ue(n),inject:[U,N]},{provide:Mt,useClass:pe},{provide:Vt,useFactory:()=>new le(os)},lt],exports:[gt,_t,jt,Jt,Mt,Vt,lt]})],ft);import{Module as rs}from"@nestjs/common";var ns=function(n,t,e,o){var i=arguments.length,r=i<3?t:o===null?o=Object.getOwnPropertyDescriptor(t,e):o,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(n,t,e,o);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},_e=class{};_e=ns([rs({})],_e);import{Global as cs,Module as us}from"@nestjs/common";import{Injectable as ss}from"@nestjs/common";var is=function(n,t,e,o){var i=arguments.length,r=i<3?t:o===null?o=Object.getOwnPropertyDescriptor(t,e):o,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(n,t,e,o);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},K=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)}};K=is([ss()],K);var as=function(n,t,e,o){var i=arguments.length,r=i<3?t:o===null?o=Object.getOwnPropertyDescriptor(t,e):o,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(n,t,e,o);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},mt=class{};mt=as([cs(),us({providers:[K],exports:[K]})],mt);import{Module as Js}from"@nestjs/common";import{Module as ys}from"@nestjs/common";import{mkdirSync as ws}from"node:fs";import{dirname as gs,join as _s}from"node:path";import{fileURLToPath as js}from"node:url";import{Injectable as ls}from"@nestjs/common";import{execFile as fs}from"node:child_process";import{mkdirSync as tn}from"node:fs";import{join as to}from"node:path";import{promisify as ms}from"node:util";var ds=function(n,t,e,o){var i=arguments.length,r=i<3?t:o===null?o=Object.getOwnPropertyDescriptor(t,e):o,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(n,t,e,o);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},ps=function(n,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,t)},hs=ms(fs),rt=class{worktreesRoot;constructor(t){this.worktreesRoot=t,tn(this.worktreesRoot,{recursive:!0})}async createWorktree(t,e){let o=e.worktreePath??to(this.worktreesRoot,t);return tn(to(o,".."),{recursive:!0}),await this.git(e.repoPath,["worktree","add","-b",e.branchName,o,e.baseBranch]),{worktreePath:o,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 o=e.remote??"origin";e.branch?await this.git(t,["push",o,e.branch]):await this.git(t,["push",o,"HEAD"])}async git(t,e){try{let o=await hs("git",e,{cwd:t,encoding:"utf8",windowsHide:!0});return{stdout:o.stdout??"",stderr:o.stderr??""}}catch(o){let i=o,r=en(i.stderr),s=en(i.stdout),a=r||s||i.message||"unknown git error";throw new Error(`git ${e.join(" ")} failed (cwd=${t}, code=${String(i.code??"?")}): ${a}`)}}};rt=ds([ls(),ps("design:paramtypes",[String])],rt);function en(n){return n==null?"":typeof n=="string"?n:n.toString("utf8")}function on(n){return to(n,"worktrees")}var bs=function(n,t,e,o){var i=arguments.length,r=i<3?t:o===null?o=Object.getOwnPropertyDescriptor(t,e):o,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(n,t,e,o);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},nn=_s(gs(js(import.meta.url)),"../../data");ws(nn,{recursive:!0});var je=class{};je=bs([ys({providers:[{provide:rt,useFactory:()=>new rt(on(nn))}],exports:[rt]})],je);import{Inject as J,Injectable as Ns}from"@nestjs/common";import{randomUUID as ro}from"node:crypto";import{exec as ks}from"node:child_process";import{promisify as Cs}from"node:util";var It=class extends Error{constructor(t){super(t),this.name=this.constructor.name}},h=class extends It{httpStatus=404},m=class extends It{httpStatus=400},Et=class extends It{httpStatus=409};function Se(n,t){return n.replace(/\{\{\s*([^}]+?)\s*\}\}/g,(e,o)=>{let i=Ss(t,o.trim());return i==null?"":typeof i=="string"?i:JSON.stringify(i)})}function Ss(n,t){let e=t.split(".").filter(Boolean),o=n;for(let i of e){if(o==null||typeof o!="object")return;o=o[i]}return o}function Wt(n,t){return typeof n=="string"?Se(n,t):Array.isArray(n)?n.map(e=>Wt(e,t)):n&&typeof n=="object"?Object.fromEntries(Object.entries(n).map(([e,o])=>[e,Wt(o,t)])):n}function rn(n,t){switch(n){case"questionnaire":return eo(t);case"confirmation":return Is(t);case"conversation":return Es(t);default:return n}}function eo(n){if(typeof n=="string"&&n.trim())return[n.trim()];if(!n||typeof n!="object")return[];let t=n.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 Is(n){if(typeof n=="string"&&n.trim())return[n.trim()];if(!n||typeof n!="object")return[];let t=n;for(let e of["prompt","message","summary","question"]){let o=t[e];if(typeof o=="string"&&o.trim())return[o.trim()]}return"approved"in t&&!("questions"in t)?[]:eo(n)}function Es(n){if(typeof n=="string"&&n.trim())return[n.trim()];if(!n||typeof n!="object")return[];let t=n;for(let e of["prompt","message","text"]){let o=t[e];if(typeof o=="string"&&o.trim())return[o.trim()]}return"suggestions"in t?[]:"questions"in t?eo(n):[]}function kt(n,t){for(let e of n){if(e.id===t)return e;if(e.iterations)for(let o of e.iterations){let i=kt(o.stepExecutions,t);if(i)return i}}}function Gt(n,t,e,o){for(let i=0;i<n.length;i++){let r=n[i];if(r.id===t)return{execution:r,siblings:n,index:i,parentLoopExecutionId:e,iterationIndex:o};if(r.iterations)for(let s of r.iterations){let a=Gt(s.stepExecutions,t,r.id,s.index);if(a)return a}}}function k(n,t,e){return n.map(o=>o.id===t?e(o):o.iterations?{...o,iterations:o.iterations.map(i=>({...i,stepExecutions:k(i.stepExecutions,t,e)}))}:o)}function oo(n,t,e,o){return e==null?[...n,t]:n.map(i=>{if(i.id===e){let r=[...i.iterations??[]],s=r.find(a=>a.index===o);if(s){let a={...s,stepExecutions:[...s.stepExecutions,t]},u=r.findIndex(c=>c.index===o);r[u]=a}else{let a={index:o,stepExecutions:[t],startedAt:t.startedAt??new Date().toISOString()};r.push(a),r.sort((u,c)=>u.index-c.index)}return{...i,iterations:r}}return i.iterations?{...i,iterations:i.iterations.map(r=>({...r,stepExecutions:oo(r.stepExecutions,t,e,o)}))}:i})}function zt(n,t){for(let e of n){if(e.id===t)return e;if(e.type==="loop"){let o=zt(e.steps,t);if(o)return o}}}function sn(n,t,e){return k(n,t,o=>{let i=(o.iterations??[]).map(r=>{if(r.index!==e)return r;let s=r.stepExecutions.every(a=>a.completedAt)?r.stepExecutions.map(a=>a.completedAt).reduce((a,u)=>a>u?a:u):void 0;return{...r,...s?{completedAt:s}:{}}});return{...o,iterations:i}})}import{z as L}from"zod";var xs=L.object({questions:L.array(L.object({id:L.string(),prompt:L.string()}))}),vs=L.object({approved:L.boolean()}),Ts=L.object({suggestions:L.array(L.object({body:L.string()}))}),Os=L.string(),Rs={questionnaire:xs,confirmation:vs,comment_suggestions:Ts,free_text:Os};function an(n,t){let e=Rs[n].safeParse(t);if(!e.success){let o=e.error.issues.map(i=>`${i.path.length?i.path.join("."):"(root)"}: ${i.message}`).join("; ");throw new Error(`Agent output failed validation for format '${n}': ${o}`)}return e.data}function cn(n){return n==="completed"||n==="failed"||n==="cancelled"}function no(n,t){let e=new Map;for(let i of n){let r=t(i);if(r==null)continue;let s=e.get(r)??[];s.push(i),e.set(r,s)}if(e.size===0)return null;let o=[];for(let i of e.values()){let r=new Set(i.map(a=>a.retryOf).filter(a=>a!=null)),s=i.find(a=>!r.has(a.id));if(!s)return null;o.push(s)}return{activeJobs:o,allTerminal:o.every(i=>cn(i.status)),groupCount:e.size}}function un(n){let t=n.every(o=>o.status==="completed"),e=n.every(o=>o.status==="failed"||o.status==="cancelled");return t?"completed":e?"failed":"completed_with_issues"}async function Ie(n,t,e){let o=await t.get(n);if(!o)throw new h(`SubjectView not found: ${n}`);if(o.subjectType==="ticket")return(await e.tickets.query(o.query)).map(r=>({subjectType:"ticket",...r}));if(o.subjectType==="pull_request")return(await e.repo.query(o.query)).map(r=>({subjectType:"pull_request",...r}));if(o.subjectType==="documentation")return(await e.documentation.query(o.query)).map(r=>({subjectType:"documentation",...r}));throw new m(`Unsupported subjectType on view: ${o.subjectType}`)}var Ps=function(n,t,e,o){var i=arguments.length,r=i<3?t:o===null?o=Object.getOwnPropertyDescriptor(t,e):o,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(n,t,e,o);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},As=function(n,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,t)},B=function(n,t){return function(e,o){t(e,o,n)}},Ds=Cs(ks),$s=["user","organization","project"],X=class{workflows;jobs;batches;views;events;tickets;repo;documentation;agent;notifications;knowledge;git;childTerminalLocks=new Set;batchTerminalLocks=new Set;constructor(t,e,o,i,r,s,a,u,c,p,l,b){this.workflows=t,this.jobs=e,this.batches=o,this.views=i,this.events=r,this.tickets=s,this.repo=a,this.documentation=u,this.agent=c,this.notifications=p,this.knowledge=l,this.git=b,this.events.subscribe(f=>{let j=f;(j.type==="job_completed"||j.type==="job_failed")&&this.onChildTerminal(j.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 m("launch() does not support cardinality 'single'; use start() with a subjectId");if(e.cardinality!=="batch"&&e.cardinality!=="aggregate")throw new m(`Unsupported cardinality: ${e.cardinality}`);pn(e.inputSchema,t.inputValues);let o=await this.resolveSelection(t.selection);if(e.cardinality==="aggregate"){let a=await this.createJob({workflowId:e.id,subjectContext:{mode:"collection",subjects:o},selection:t.selection,inputValues:t.inputValues});return this.emit({type:"job_started",jobId:a.id,timestamp:new Date().toISOString()}),this.runJob(a.id)}let i=new Date().toISOString(),r=await this.batches.create({id:ro(),workflowId:e.id,selection:t.selection,resolvedSubjects:o,status:"running",triggeredBy:t.triggeredBy,...t.notificationOverride?{notificationOverride:t.notificationOverride}:{},notificationSent:!1,createdAt:i}),s=[];for(let a=0;a<o.length;a++){let u=o[a],c=await this.createJob({workflowId:e.id,subjectContext:{mode:"single",subject:u},selection:t.selection,batchId:r.id,fanOutIndex:a,inputValues:t.inputValues});s.push(c)}for(let a of s)this.emit({type:"job_started",jobId:a.id,timestamp:new Date().toISOString()}),await this.runJob(a.id);return await this.batches.get(r.id)}async createJob(t){let e=await this.workflows.get(t.workflowId);if(!e)throw new h(`Workflow not found: ${t.workflowId}`);if(!t.subjectContext&&e.cardinality!=="single")throw new m(`Workflow Runner only supports cardinality 'single' at start() without an explicit subjectContext (got '${e.cardinality}')`);pn(e.inputSchema,t.inputValues);let o=t.subjectContext??await this.resolveSubjectContext(e,t.subjectId),i=new Date().toISOString();return this.jobs.create({id:ro(),workflowId:e.id,status:"pending",...o?{subjectContext:o}:{},...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 o=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,o,o.steps,void 0,void 0,0);return i.outcome==="paused"||i.outcome==="failed"?i.job:this.completeJob(i.job,o)}async resume(t,e){let o=await this.jobs.get(t);if(!o)throw new h(`Job not found: ${t}`);if(o.status!=="waiting_for_human")throw new Et(`Job ${t} is not waiting for human input (status: ${o.status})`);let i=await this.requireWorkflow(o.workflowId),r=o.currentStepExecutionId;if(!r)throw new Error(`Job ${t} is waiting_for_human but has no currentStepExecutionId`);let s=kt(o.stepHistory,r);if(!s)throw new Error(`Paused execution ${r} not found on job ${t}`);if(s.type==="loop")return this.resumeAskHuman(o,i,s,e);if(s.type!=="interaction")throw new Error(`Paused execution ${r} has type '${s.type}'; expected interaction or loop`);let a=new Date().toISOString(),u=k(o.stepHistory,r,j=>({...j,status:"completed",completedAt:a,output:e})),c=e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{response:e};o=await this.persistJob({...o,status:"planning",context:{...o.context,[s.stepDefinitionId]:e},stepHistory:u,currentStepId:void 0,currentStepExecutionId:void 0,updatedAt:a}),this.emit({type:"human_answered",jobId:o.id,answers:c,timestamp:a});let p=Gt(o.stepHistory,r);if(!p)throw new Error(`Could not locate frame for execution ${r}`);let l=this.sequenceForFrameOnJob(o,i,p),b=p.index+1,f=await this.executeStepSequence(o,i,l,p.parentLoopExecutionId,p.iterationIndex,b);return f.outcome==="paused"||f.outcome==="failed"?f.job:p.parentLoopExecutionId!=null&&p.iterationIndex!=null?this.continueLoopAfterBody(f.job,i,p.parentLoopExecutionId,p.iterationIndex):this.completeJob(f.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 Et(`Job ${t} is not failed (status: ${e.status})`);let o=e.parentJobId!=null&&e.parentStepExecutionId!=null&&e.fanOutIndex!=null,i=e.batchId!=null&&e.fanOutIndex!=null;if(!o&&!i)throw new m(`Job ${t} is not a retryable sub_workflow child or batch member`);if(o){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=k(a.stepHistory,e.parentStepExecutionId,p=>({...p,status:"waiting_for_children",error:void 0,completedAt:void 0,childJobIds:[...p.childJobIds??[],u.id]}));return a=await this.persistJob({...a,status:"waiting_for_children",stepHistory:c,completedAt:void 0,updatedAt:new Date().toISOString()}),this.emit({type:"job_started",jobId:u.id,timestamp:new Date().toISOString()}),this.emit({type:"job_retried",jobId:u.id,retryOf:e.id,timestamp:new Date().toISOString()}),this.runJob(u.id),u}let r=await this.batches.get(e.batchId);if(!r)throw new h(`JobBatch not found: ${e.batchId}`);r.status!=="running"&&await this.batches.update(r.id,{status:"running",completedAt:null,notificationSent:!1});let s=await this.createJob({workflowId:e.workflowId,subjectContext:e.subjectContext,selection:e.selection,batchId:e.batchId,fanOutIndex:e.fanOutIndex,inputValues:{},retryOf:e.id});return this.emit({type:"job_started",jobId:s.id,timestamp:new Date().toISOString()}),this.emit({type:"job_retried",jobId:s.id,retryOf:e.id,timestamp:new Date().toISOString()}),this.runJob(s.id),s}async executeStepSequence(t,e,o,i,r,s){let a=t;for(let u=s;u<o.length;u++){let c=o[u],p=new Date().toISOString(),l={id:ro(),stepDefinitionId:c.id,type:c.type,status:"running",startedAt:p},b=oo(a.stepHistory,l,i,r);a=await this.persistJob({...a,status:a.status==="pending"?"planning":a.status,currentStepId:c.id,currentStepExecutionId:l.id,stepHistory:b,updatedAt:p}),this.emit({type:"step_started",jobId:a.id,stepDefinitionId:c.id,timestamp:p});try{let f=await this.dispatchStep(a,e,c,l.id,i,r);if(a=f.job,f.outcome==="paused"||f.outcome==="failed")return f}catch(f){return{outcome:"failed",job:await this.failJob(a,e,l.id,c.id,f)}}}return i!=null&&r!=null&&(a=await this.persistJob({...a,stepHistory:sn(a.stepHistory,i,r),updatedAt:new Date().toISOString()})),{outcome:"completed",job:a}}async dispatchStep(t,e,o,i,r,s){switch(o.type){case"agent":return{outcome:"completed",job:await this.executeAgentStep(t,o,i)};case"interaction":return{outcome:"paused",job:await this.pauseForInteraction(t,e,o,i)};case"git":return{outcome:"completed",job:await this.executeGitStep(t,o,i)};case"provider_action":return{outcome:"completed",job:await this.executeProviderActionStep(t,o,i)};case"shell":return{outcome:"completed",job:await this.executeShellStep(t,o,i)};case"loop":return this.runLoopStep(t,e,o,i,r,s);case"sub_workflow":return this.runSubWorkflowStep(t,o,i);default:{let a=o;throw new m(`Step type '${a.type}' not yet supported by the Workflow Runner`)}}}async runLoopStep(t,e,o,i,r,s,a=0,u=o.maxIterations){let c=t,p=a;for(;;){if(p>=u)switch(o.onMaxIterations.action){case"fail":return c=await this.failExecution(c,e,i,o.id,`Loop '${o.id}' exceeded maxIterations (${u})`),{outcome:"failed",job:c};case"continue":return c=await this.finishExecution(c,i,o.id,{iterations:p,exitedOnMaxIterations:!0}),{outcome:"completed",job:c};case"ask_human":{let b={maxIterationsCheckpoint:!0,nextIteration:p,effectiveMaxIterations:u},f=new Date().toISOString(),j=k(c.stepHistory,i,I=>({...I,status:"pending",output:b}));return c=await this.persistJob({...c,status:"waiting_for_human",currentStepId:o.id,currentStepExecutionId:i,stepHistory:j,updatedAt:f}),this.emit({type:"waiting_for_human",jobId:c.id,stepDefinitionId:o.id,interaction:"confirmation",data:b,questions:[`Loop '${o.id}' reached maxIterations (${u}). Extend, continue, or cancel?`],timestamp:f}),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 '${o.id}'`,jobId:c.id}),{outcome:"paused",job:c}}default:{let b=o.onMaxIterations;throw new Error(`Unknown onMaxIterations action: ${JSON.stringify(b)}`)}}let l=await this.executeStepSequence(c,e,o.steps,i,p,0);if(c=l.job,l.outcome==="paused")return l;if(l.outcome==="failed")return c=await this.failExecution(c,e,i,o.id,"Loop body failed"),{outcome:"failed",job:c};if(dn(o.until,c.context))return c=await this.finishExecution(c,i,o.id,{iterations:p+1}),{outcome:"completed",job:c};p+=1}}async resumeAskHuman(t,e,o,i){let r=i,s=o.output;if(!s?.maxIterationsCheckpoint)throw new Error(`Loop execution ${o.id} is not at an ask_human checkpoint`);let a=zt(e.steps,o.stepDefinitionId);if(!a||a.type!=="loop")throw new Error(`Loop step definition '${o.stepDefinitionId}' not found`);let u=Gt(t.stepHistory,o.id),c=new Date().toISOString();if(r.action==="cancel")return await this.failExecution({...t,status:"planning",currentStepId:void 0,currentStepExecutionId:void 0,updatedAt:c},e,o.id,a.id,"Loop cancelled by human at maxIterations checkpoint");if(r.action==="continue"){let j=await this.persistJob({...t,status:"planning",currentStepId:void 0,currentStepExecutionId:void 0,stepHistory:k(t.stepHistory,o.id,I=>({...I,status:"completed",completedAt:c,output:{iterations:s.nextIteration,exitedOnMaxIterations:!0,humanAction:"continue"}})),updatedAt:c});return this.emit({type:"human_answered",jobId:j.id,answers:r,timestamp:c}),this.emit({type:"step_completed",jobId:j.id,stepDefinitionId:a.id,timestamp:c}),u?.parentLoopExecutionId!=null&&u.iterationIndex!=null?this.continueLoopAfterBody(j,e,u.parentLoopExecutionId,u.iterationIndex):this.continueTopLevelAfter(j,e,a.id)}let p=typeof r.additionalIterations=="number"?r.additionalIterations:0,l=s.effectiveMaxIterations+p,b=await this.persistJob({...t,status:"planning",currentStepId:void 0,currentStepExecutionId:void 0,stepHistory:k(t.stepHistory,o.id,j=>({...j,status:"running",output:void 0})),updatedAt:c});this.emit({type:"human_answered",jobId:b.id,answers:r,timestamp:c});let f=await this.runLoopStep(b,e,a,o.id,u?.parentLoopExecutionId,u?.iterationIndex,s.nextIteration,l);return f.outcome==="paused"||f.outcome==="failed"?f.job:u?.parentLoopExecutionId!=null&&u.iterationIndex!=null?this.continueLoopAfterBody(f.job,e,u.parentLoopExecutionId,u.iterationIndex):this.continueTopLevelAfter(f.job,e,a.id)}async continueLoopAfterBody(t,e,o,i){let r=kt(t.stepHistory,o);if(!r)throw new Error(`Loop execution ${o} not found`);let s=zt(e.steps,r.stepDefinitionId);if(!s||s.type!=="loop")throw new Error(`Loop step '${r.stepDefinitionId}' not found`);let a=Gt(t.stepHistory,o),u=r.output?.effectiveMaxIterations??s.maxIterations,c=t;if(dn(s.until,c.context))c=await this.finishExecution(c,o,s.id,{iterations:i+1});else{let p=i+1,l=await this.runLoopStep(c,e,s,o,a?.parentLoopExecutionId,a?.iterationIndex,p,u);if(l.outcome==="paused"||l.outcome==="failed")return l.job;c=l.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,o){let i=e.steps.findIndex(s=>s.id===o),r=await this.executeStepSequence(t,e,e.steps,void 0,void 0,i+1);return r.outcome==="paused"||r.outcome==="failed"?r.job:this.completeJob(r.job,e)}sequenceForFrameOnJob(t,e,o){if(o.parentLoopExecutionId==null)return e.steps;let i=kt(t.stepHistory,o.parentLoopExecutionId);if(!i)throw new Error(`Parent loop execution ${o.parentLoopExecutionId} not found`);let r=zt(e.steps,i.stepDefinitionId);if(!r||r.type!=="loop")throw new Error(`Parent loop step '${i.stepDefinitionId}' not found`);return r.steps}async runSubWorkflowStep(t,e,o){if(!t.subjectContext||t.subjectContext.mode!=="collection")throw new m(`sub_workflow steps require subjectContext.mode === 'collection' (job ${t.id})`);let i=t.subjectContext.subjects,r=[];for(let p=0;p<i.length;p++){let l=i[p],b=await this.createJob({workflowId:e.workflowId,subjectContext:{mode:"single",subject:l},inputValues:{},parentJobId:t.id,parentStepExecutionId:o,fanOutIndex:p});r.push(b)}let s=r.map(p=>p.id),a=new Date().toISOString(),u=k(t.stepHistory,o,p=>({...p,status:"waiting_for_children",childJobIds:s})),c=await this.persistJob({...t,status:"waiting_for_children",currentStepId:e.id,currentStepExecutionId:o,stepHistory:u,updatedAt:a});for(let p of r)this.emit({type:"job_started",jobId:p.id,timestamp:a}),this.runJob(p.id);return{outcome:"paused",job:c}}async onChildTerminal(t){let e=await this.jobs.get(t);if(!e?.parentJobId||!e.parentStepExecutionId)return;let o=`${e.parentJobId}:${e.parentStepExecutionId}`;if(!this.childTerminalLocks.has(o)){this.childTerminalLocks.add(o);try{let i=(await this.jobs.list({parentJobId:e.parentJobId,parentStepExecutionId:e.parentStepExecutionId})).filter(I=>I.parentStepExecutionId===e.parentStepExecutionId),r=no(i,I=>I.fanOutIndex);if(!r?.allTerminal)return;let{activeJobs:s}=r,a=await this.jobs.get(e.parentJobId);if(!a||a.status!=="waiting_for_children"&&a.status!=="failed")return;let u=await this.requireWorkflow(a.workflowId),c=e.parentStepExecutionId,p=kt(a.stepHistory,c);if(!p||p.type!=="sub_workflow")return;if(s.some(I=>I.status==="failed")){await this.failExecution(a,u,c,p.stepDefinitionId,"One or more child jobs failed");return}let b=s.slice().sort((I,Hn)=>(I.fanOutIndex??0)-(Hn.fanOutIndex??0)).map(I=>({fanOutIndex:I.fanOutIndex,jobId:I.id,output:I.context})),f=new Date().toISOString();a=await this.persistJob({...a,status:"planning",context:{...a.context,[p.stepDefinitionId]:b},currentStepId:void 0,currentStepExecutionId:void 0,stepHistory:k(a.stepHistory,c,I=>({...I,status:"completed",completedAt:f,output:b})),completedAt:void 0,updatedAt:f}),this.emit({type:"step_completed",jobId:a.id,stepDefinitionId:p.stepDefinitionId,timestamp:f});let j=await this.continueTopLevelAfter(a,u,p.stepDefinitionId)}finally{this.childTerminalLocks.delete(o)}}}async onBatchMemberTerminal(t){let e=await this.jobs.get(t);if(!e?.batchId)return;let o=e.batchId;if(!this.batchTerminalLocks.has(o)){this.batchTerminalLocks.add(o);try{let i=await this.batches.get(e.batchId);if(!i||i.status!=="running")return;let r=await this.jobs.list({batchId:i.id}),s=no(r,l=>l.fanOutIndex);if(!s||s.groupCount!==i.resolvedSubjects.length||!s.allTerminal)return;let{activeJobs:a}=s,u=un(a),c=new Date().toISOString(),p=await this.batches.update(i.id,{status:u,completedAt:c});if(!p)return;if(this.emit({type:"batch_completed",batchId:p.id,summary:a.map(l=>({jobId:l.id,status:l.status})),timestamp:c}),!p.notificationSent){let l=await this.requireWorkflow(p.workflowId),b=p.notificationOverride??l.notificationPolicy,f=u==="completed"?"on_complete":"on_fail";b.triggers.includes(f)&&await this.notifications.send({title:`Batch ${u}: ${l.name}`,body:`JobBatch ${p.id} finished with status '${u}' (${a.length} members)`,batchId:p.id}),await this.batches.update(p.id,{notificationSent:!0})}}finally{this.batchTerminalLocks.delete(o)}}}async resolveSelection(t){if(t.mode==="view")return Ie(t.viewId,this.views,{tickets:this.tickets,repo:this.repo,documentation:this.documentation});let e=[];for(let o of t.subjectIds)if(t.subjectType==="ticket"){let i=await this.tickets.get(o);e.push({subjectType:"ticket",...i})}else if(t.subjectType==="pull_request"){let i=await this.repo.get(o);e.push({subjectType:"pull_request",...i})}else if(t.subjectType==="documentation"){let i=await this.documentation.get(o);e.push({subjectType:"documentation",...i})}else throw new m(`Unsupported subjectType: ${t.subjectType}`);return e}async executeAgentStep(t,e,o){let i=e.knowledgeScope?.length?e.knowledgeScope:$s,r=await this.resolveKnowledge(i),s=Ee(t),a=Se(e.objective,s),u=await this.agent.run({objective:a,outputFormat:e.outputFormat,knowledge:r,context:{...s,stepId:e.id},...t.worktreePath?{cwd:t.worktreePath}:{}}),c=an(e.outputFormat,u.parsed);return this.finishExecution(t,o,e.id,c)}async executeGitStep(t,e,o){let i=Wt(e.params,Ee(t));switch(e.operation){case"create_worktree":{let r=await this.git.createWorktree(t.id,{repoPath:tt(i,"repoPath"),baseBranch:tt(i,"baseBranch"),branchName:tt(i,"branchName"),...typeof i.worktreePath=="string"?{worktreePath:i.worktreePath}:{}});return this.finishExecution(t,o,e.id,r,{worktreePath:r.worktreePath,branch:r.branch})}case"create_branch":{let r=xe(t),s=tt(i,"branchName");return await this.git.createBranch(r,{branchName:s,...typeof i.baseBranch=="string"?{baseBranch:i.baseBranch}:{}}),this.finishExecution(t,o,e.id,{branch:s},{branch:s})}case"checkout":{let r=xe(t),s=tt(i,"branch");return await this.git.checkout(r,{branch:s}),this.finishExecution(t,o,e.id,{branch:s},{branch:s})}case"commit":{let r=xe(t),s=await this.git.commit(r,{message:tt(i,"message"),addAll:i.addAll!==!1});return this.finishExecution(t,o,e.id,s)}case"push":{let r=xe(t);return await this.git.push(r,{...typeof i.remote=="string"?{remote:i.remote}:{},...typeof i.branch=="string"?{branch:i.branch}:{}}),this.finishExecution(t,o,e.id,{remote:typeof i.remote=="string"?i.remote:"origin",branch:typeof i.branch=="string"?i.branch:t.branch})}default:{let r=e.operation;throw new Error(`Unknown git operation: ${r}`)}}}async executeProviderActionStep(t,e,o){if(!t.subjectContext||t.subjectContext.mode!=="single")throw new m(`provider_action steps require subjectContext.mode === 'single' (job ${t.id})`);let i=t.subjectContext.subject,r=i.id,s=Wt(e.params??{},Ee(t))??{},a;if(i.subjectType==="documentation")switch(e.action){case"get_subject":a=await this.documentation.get(r);break;case"get_content":a=await this.documentation.getContent(r);break;case"get_comments":a=await this.documentation.getComments(r);break;case"post_comment":await this.documentation.postComment(r,tt(s,"body")),a={posted:!0};break;case"update_status":throw new Error(`Provider action '${e.action}' is not valid for subject type 'documentation'`);default:{let u=e.action;throw new Error(`Unknown provider action: ${u}`)}}else{let u=i.subjectType==="ticket"?this.tickets:i.subjectType==="pull_request"?this.repo:null;if(!u)throw new Error(`Unsupported subjectType for provider_action: ${i.subjectType}`);switch(e.action){case"get_subject":a=await u.get(r);break;case"get_comments":a=await u.getComments(r);break;case"post_comment":await u.postComment(r,tt(s,"body")),a={posted:!0};break;case"update_status":await u.updateStatus(r,tt(s,"status")),a={status:tt(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,o,e.id,a)}async executeShellStep(t,e,o){let i=Se(e.command,Ee(t)),r=t.worktreePath??process.cwd();try{let s=await Ds(i,{cwd:r,windowsHide:!0});return this.finishExecution(t,o,e.id,{exitCode:0,stdout:String(s.stdout??""),stderr:String(s.stderr??"")})}catch(s){let a=s,u=a.stderr??"",c=a.stdout??"",p=typeof a.code=="number"?a.code:Number.parseInt(String(a.code??"1"),10)||1;throw new Error(`shell command failed (exit ${p}, cwd=${r}): ${u||c||a.message||i}`)}}async pauseForInteraction(t,e,o,i){let r=new Date().toISOString(),s=qs(e,o.id),a=s!=null?t.context[s]:void 0,u=k(t.stepHistory,i,b=>({...b,status:"pending"})),c=await this.persistJob({...t,status:"waiting_for_human",currentStepId:o.id,currentStepExecutionId:i,stepHistory:u,updatedAt:r}),p=rn(o.interaction,a);return this.emit({type:"waiting_for_human",jobId:c.id,stepDefinitionId:o.id,interaction:o.interaction,data:a,questions:p,timestamp:r}),e.notificationPolicy.triggers.includes("on_needs_input")&&o.notify!==!1&&await this.notifications.send({title:`Input needed: ${e.name}`,body:`Job ${c.id} is waiting for human input on step '${o.id}'`,jobId:c.id}),c}async finishExecution(t,e,o,i,r={}){let s=new Date().toISOString(),a=k(t.stepHistory,e,c=>({...c,status:"completed",completedAt:s,output:i})),u=await this.persistJob({...t,...r,context:{...t.context,[o]:i},stepHistory:a,updatedAt:s});return this.emit({type:"step_completed",jobId:u.id,stepDefinitionId:o,timestamp:s}),u}async failExecution(t,e,o,i,r){return this.failJob(t,e,o,i,new Error(r))}async completeJob(t,e){let o=new Date().toISOString(),i=await this.persistJob({...t,status:"completed",currentStepId:void 0,currentStepExecutionId:void 0,completedAt:o,updatedAt:o});return this.emit({type:"job_completed",jobId:i.id,timestamp:o}),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,o,i,r){let s=r instanceof Error?r.message:String(r),a=new Date().toISOString(),u=k(t.stepHistory,o,p=>({...p,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 o=Ls(t.appliesTo);if(!e)throw new Error(`Workflow '${t.id}' applies to '${o}' but no subjectId was provided`);if(o==="ticket")return{mode:"single",subject:{subjectType:"ticket",...await this.tickets.get(e)}};if(o==="pull_request")return{mode:"single",subject:{subjectType:"pull_request",...await this.repo.get(e)}};if(o==="documentation")return{mode:"single",subject:{subjectType:"documentation",...await this.documentation.get(e)}};throw new Error(`Unsupported subjectType for workflow subject resolution: ${o}`)}async resolveKnowledge(t){let e=[];for(let o of t)e.push(...await this.knowledge.resolve(o));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)}};X=Ps([Ns(),B(0,J(D)),B(1,J(S)),B(2,J(q)),B(3,J($)),B(4,J(K)),B(5,J(gt)),B(6,J(_t)),B(7,J(jt)),B(8,J(Jt)),B(9,J(Mt)),B(10,J(Vt)),B(11,J(rt)),As("design:paramtypes",[D,S,q,$,K,Object,Object,Object,Object,Object,Object,rt])],X);function dn(n,t){let e=t[n.stepId];if(e==null||typeof e!="object")return n.type==="field_empty";let o=e[n.field];return n.type==="field_empty"?o==null?!0:typeof o=="string"||Array.isArray(o)?o.length===0:!1:o===n.value}function qs(n,t){let e=i=>{let r=[];for(let s of i)r.push(s),s.type==="loop"&&r.push(...e(s.steps));return r},o=i=>{let r=i.findIndex(s=>s.id===t);if(r>=0){for(let s=r-1;s>=0;s--)if(i[s].type==="agent")return i[s].id;return}for(let s of i)if(s.type==="loop"){let a=o(s.steps);if(a!==void 0||s.steps.some(u=>u.id===t))return a}};return o(n.steps)}function Ee(n){let t={...n.context};return n.subjectContext?.mode==="single"&&(t.subject=n.subjectContext.subject),n.worktreePath&&(t.worktreePath=n.worktreePath),n.branch&&(t.branch=n.branch),t}function xe(n){if(!n.worktreePath)throw new Error(`Job ${n.id} has no worktreePath; run create_worktree first`);return n.worktreePath}function tt(n,t){let e=n[t];if(typeof e!="string"||e.length===0)throw new Error(`Missing required string param '${t}'`);return e}function Ls(n){if(n==="none")throw new Error("normalizeAppliesTo called with none");if(Array.isArray(n)){if(n.length!==1)throw new Error(`Workflow Runner requires appliesTo to be a single SubjectType (got ${JSON.stringify(n)})`);return n[0]}return n}function pn(n,t){for(let e of n)if(e.required&&(t[e.name]===void 0||t[e.name]===null))throw new m(`Missing required input: ${e.name}`)}var Bs=function(n,t,e,o){var i=arguments.length,r=i<3?t:o===null?o=Object.getOwnPropertyDescriptor(t,e):o,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(n,t,e,o);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},Ct=class{};Ct=Bs([Js({imports:[Z,ft,mt,je],providers:[X],exports:[X]})],Ct);import{Module as gc}from"@nestjs/common";import{APP_FILTER as _c}from"@nestjs/core";import{Catch as Us}from"@nestjs/common";var Fs=function(n,t,e,o){var i=arguments.length,r=i<3?t:o===null?o=Object.getOwnPropertyDescriptor(t,e):o,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(n,t,e,o);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},ve=class{catch(t,e){e.switchToHttp().getResponse().status(t.httpStatus).json({error:t.message})}};ve=Fs([Us(It)],ve);import{Body as hn,Controller as Hs,Delete as Ws,Get as bn,HttpCode as Gs,Inject as fn,Param as so,Patch as zs,Post as Ys,Query as Qs}from"@nestjs/common";import{workflowDefinitionInputSchema as yn,workflowDefinitionSchema as mn}from"@knoflows/shared";var _=class{schema;constructor(t){this.schema=t}transform(t){let e=this.schema.safeParse(t);if(!e.success){let o=e.error.issues.map(i=>`${i.path.join(".")||"(root)"}: ${i.message}`).join("; ");throw new m(`Validation failed: ${o}`)}return e.data}};import{collectExistingStepIds as Ms,generateUniqueStepId as Vs}from"@knoflows/shared";import{randomUUID as Ks}from"node:crypto";function Xs(){return Ks()}function io(n){let t=n.id??Xs(),e=Ms(n.steps),o=ln(n.steps,e);return{...n,id:t,steps:o}}function ln(n,t){return n.map(e=>{let o=e.id;return o||(o=Vs(e.name,t),t.add(o)),e.type==="loop"?{...e,id:o,steps:ln(e.steps,t)}:{...e,id:o}})}var Dt=function(n,t,e,o){var i=arguments.length,r=i<3?t:o===null?o=Object.getOwnPropertyDescriptor(t,e):o,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(n,t,e,o);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},x=function(n,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,t)},ht=function(n,t){return function(e,o){t(e,o,n)}},Zs=new Set(["completed","failed","cancelled"]),it=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 m(`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=io(t),o=mn.safeParse(e);if(!o.success){let i=o.error.issues.map(r=>`${r.path.join(".")||"(root)"}: ${r.message}`).join("; ");throw new m(`Validation failed: ${i}`)}return this.workflows.create(o.data)}async update(t,e){let o=io({...e,id:t}),i=mn.safeParse(o);if(!i.success){let u=i.error.issues.map(c=>`${c.path.join(".")||"(root)"}: ${c.message}`).join("; ");throw new m(`Validation failed: ${u}`)}let{id:r,...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=>!Zs.has(s.status));if(i.length>0){let s=i.length===1?"Job":"Jobs";throw new Et(`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}`)}};Dt([bn(),ht(0,Qs("cardinality")),x("design:type",Function),x("design:paramtypes",[String]),x("design:returntype",Promise)],it.prototype,"list",null);Dt([bn(":id"),ht(0,so("id")),x("design:type",Function),x("design:paramtypes",[String]),x("design:returntype",Promise)],it.prototype,"get",null);Dt([Ys(),ht(0,hn(new _(yn))),x("design:type",Function),x("design:paramtypes",[Object]),x("design:returntype",Promise)],it.prototype,"create",null);Dt([zs(":id"),ht(0,so("id")),ht(1,hn(new _(yn))),x("design:type",Function),x("design:paramtypes",[String,Object]),x("design:returntype",Promise)],it.prototype,"update",null);Dt([Ws(":id"),Gs(204),ht(0,so("id")),x("design:type",Function),x("design:paramtypes",[String]),x("design:returntype",Promise)],it.prototype,"remove",null);it=Dt([Hs("workflows"),ht(0,fn(D)),ht(1,fn(S)),x("design:paramtypes",[D,S])],it);import{Body as ao,Controller as ta,Delete as ea,Get as co,HttpCode as oa,Inject as Te,Param as Oe,Patch as wn,Post as na,Query as ra}from"@nestjs/common";import{createSubjectViewSchema as ia,reorderViewsBodySchema as sa,subjectTypeSchema as aa,subjectViewSchema as ca}from"@knoflows/shared";var bt=function(n,t,e,o){var i=arguments.length,r=i<3?t:o===null?o=Object.getOwnPropertyDescriptor(t,e):o,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(n,t,e,o);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},g=function(n,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,t)},F=function(n,t){return function(e,o){t(e,o,n)}},H=class{views;tickets;repo;documentation;constructor(t,e,o,i){this.views=t,this.tickets=e,this.repo=o,this.documentation=i}async list(t){if(t!=null&&t!==""){let e=aa.safeParse(t);if(!e.success)throw new m(`Invalid subjectType filter: ${t}`);return this.views.list({subjectType:e.data})}return this.views.list({})}async reorder(t){let e=[];for(let r of t.viewIds){let s=await this.views.get(r);if(!s)throw new m(`Unknown view id in reorder: ${r}`);e.push(s)}if(new Set(e.map(r=>r.subjectType)).size!==1)throw new m("All viewIds in a reorder request must share the same subjectType");return await this.views.reorder(t.viewIds)}async listSubjects(t){return Ie(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 this.views.create(t)}async update(t,e){let o=await this.views.update(t,e);if(!o)throw new h(`SubjectView not found: ${t}`);return o}async remove(t){if(!await this.views.delete(t))throw new h(`SubjectView not found: ${t}`)}};bt([co(),F(0,ra("subjectType")),g("design:type",Function),g("design:paramtypes",[String]),g("design:returntype",Promise)],H.prototype,"list",null);bt([wn("reorder"),F(0,ao(new _(sa))),g("design:type",Function),g("design:paramtypes",[Object]),g("design:returntype",Promise)],H.prototype,"reorder",null);bt([co(":id/subjects"),F(0,Oe("id")),g("design:type",Function),g("design:paramtypes",[String]),g("design:returntype",Promise)],H.prototype,"listSubjects",null);bt([co(":id"),F(0,Oe("id")),g("design:type",Function),g("design:paramtypes",[String]),g("design:returntype",Promise)],H.prototype,"get",null);bt([na(),F(0,ao(new _(ia))),g("design:type",Function),g("design:paramtypes",[Object]),g("design:returntype",Promise)],H.prototype,"create",null);bt([wn(":id"),F(0,Oe("id")),F(1,ao(new _(ca.partial().omit({id:!0,order:!0})))),g("design:type",Function),g("design:paramtypes",[String,Object]),g("design:returntype",Promise)],H.prototype,"update",null);bt([ea(":id"),oa(204),F(0,Oe("id")),g("design:type",Function),g("design:paramtypes",[String]),g("design:returntype",Promise)],H.prototype,"remove",null);H=bt([ta("views"),F(0,Te($)),F(1,Te(gt)),F(2,Te(_t)),F(3,Te(jt)),g("design:paramtypes",[$,Object,Object,Object])],H);import{Body as _n,Controller as ua,Get as jn,Inject as gn,Param as uo,Post as po,Query as xt}from"@nestjs/common";import"zod";function Re(n,t,e=50){let o=n!=null&&n!==""?Number(n):e,i=t!=null&&t!==""?Number(t):0;return!Number.isFinite(o)||o<1?{limit:e,offset:Math.max(0,i||0)}:!Number.isFinite(i)||i<0?{limit:o,offset:0}:{limit:Math.floor(o),offset:Math.floor(i)}}function Pe(n,t,e){return n.slice(e,e+t)}import{z as yt}from"zod";var Ae=yt.object({workflowId:yt.string().min(1),subjectId:yt.string().min(1).optional(),inputValues:yt.record(yt.string(),yt.unknown())}),Ne=yt.object({response:yt.unknown()});var $t=function(n,t,e,o){var i=arguments.length,r=i<3?t:o===null?o=Object.getOwnPropertyDescriptor(t,e):o,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(n,t,e,o);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},v=function(n,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,t)},P=function(n,t){return function(e,o){t(e,o,n)}},da=["pending","planning","waiting_for_human","waiting_for_children","implementing","testing","completed","failed","cancelled"],st=class{jobs;runner;constructor(t,e){this.jobs=t,this.runner=e}async list(t,e,o,i,r,s,a){if(e!=null&&e!==""&&!da.includes(e))throw new m(`Invalid status filter: ${e}`);if(r!=null&&r!==""&&r!=="true"&&r!=="false")throw new m(`Invalid topLevelOnly filter: ${r}`);let{limit:u,offset:c}=Re(s,a),p=await this.jobs.list({...t?{workflowId:t}:{},...e?{status:e}:{},...o?{batchId:o}:{},...i?{parentJobId:i}:{},...r==="true"?{topLevelOnly:!0}:{}});return Pe(p,u,c)}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)}};$t([jn(),P(0,xt("workflowId")),P(1,xt("status")),P(2,xt("batchId")),P(3,xt("parentJobId")),P(4,xt("topLevelOnly")),P(5,xt("limit")),P(6,xt("offset")),v("design:type",Function),v("design:paramtypes",[String,String,String,String,String,String,String]),v("design:returntype",Promise)],st.prototype,"list",null);$t([jn(":id"),P(0,uo("id")),v("design:type",Function),v("design:paramtypes",[String]),v("design:returntype",Promise)],st.prototype,"get",null);$t([po(),P(0,_n(new _(Ae))),v("design:type",Function),v("design:paramtypes",[Object]),v("design:returntype",Promise)],st.prototype,"create",null);$t([po(":id/resume"),P(0,uo("id")),P(1,_n(new _(Ne))),v("design:type",Function),v("design:paramtypes",[String,Object]),v("design:returntype",Promise)],st.prototype,"resume",null);$t([po(":id/retry"),P(0,uo("id")),v("design:type",Function),v("design:paramtypes",[String]),v("design:returntype",Promise)],st.prototype,"retry",null);st=$t([ua("jobs"),P(0,gn(S)),P(1,gn(X)),v("design:paramtypes",[S,X])],st);import{Body as fa,Controller as ma,Get as mo,Inject as lo,Param as Sn,Post as ha,Query as fo}from"@nestjs/common";import"zod";import{z as A}from"zod";import{notificationPolicySchema as pa,subjectTypeSchema as la}from"@knoflows/shared";var ke=A.discriminatedUnion("mode",[A.object({mode:A.literal("view"),viewId:A.string().min(1)}),A.object({mode:A.literal("manual"),subjectType:la,subjectIds:A.array(A.string().min(1))})]),Ce=A.object({workflowId:A.string().min(1),selection:ke,triggeredBy:A.enum(["schedule","view_bulk","multiselect"]),notificationOverride:pa.optional(),inputValues:A.record(A.string(),A.unknown())});var Yt=function(n,t,e,o){var i=arguments.length,r=i<3?t:o===null?o=Object.getOwnPropertyDescriptor(t,e):o,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(n,t,e,o);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},C=function(n,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,t)},at=function(n,t){return function(e,o){t(e,o,n)}},wt=class{batches;jobs;runner;constructor(t,e,o){this.batches=t,this.jobs=e,this.runner=o}async list(t,e,o){let{limit:i,offset:r}=Re(e,o),s=await this.batches.list(t?{workflowId:t}:{});return Pe(s,i,r)}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}}};Yt([mo(),at(0,fo("workflowId")),at(1,fo("limit")),at(2,fo("offset")),C("design:type",Function),C("design:paramtypes",[String,String,String]),C("design:returntype",Promise)],wt.prototype,"list",null);Yt([mo(":id"),at(0,Sn("id")),C("design:type",Function),C("design:paramtypes",[String]),C("design:returntype",Promise)],wt.prototype,"get",null);Yt([mo(":id/jobs"),at(0,Sn("id")),C("design:type",Function),C("design:paramtypes",[String]),C("design:returntype",Promise)],wt.prototype,"listJobs",null);Yt([ha(),at(0,fa(new _(Ce))),C("design:type",Function),C("design:paramtypes",[Object]),C("design:returntype",Promise)],wt.prototype,"launch",null);wt=Yt([ma("batches"),at(0,lo(q)),at(1,lo(S)),at(2,lo(X)),C("design:paramtypes",[q,S,X])],wt);import{Body as In,Controller as ba,Delete as ya,Get as En,HttpCode as wa,Inject as ga,Param as ho,Patch as _a,Post as ja,Query as Sa}from"@nestjs/common";import{scheduleSchema as xn}from"@knoflows/shared";var qt=function(n,t,e,o){var i=arguments.length,r=i<3?t:o===null?o=Object.getOwnPropertyDescriptor(t,e):o,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(n,t,e,o);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},T=function(n,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,t)},vt=function(n,t){return function(e,o){t(e,o,n)}},ct=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 m(`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 o=await this.schedules.update(t,e);if(!o)throw new h(`Schedule not found: ${t}`);return o}async remove(t){if(!await this.schedules.delete(t))throw new h(`Schedule not found: ${t}`)}};qt([En(),vt(0,Sa("enabled")),T("design:type",Function),T("design:paramtypes",[String]),T("design:returntype",Promise)],ct.prototype,"list",null);qt([En(":id"),vt(0,ho("id")),T("design:type",Function),T("design:paramtypes",[String]),T("design:returntype",Promise)],ct.prototype,"get",null);qt([ja(),vt(0,In(new _(xn))),T("design:type",Function),T("design:paramtypes",[Object]),T("design:returntype",Promise)],ct.prototype,"create",null);qt([_a(":id"),vt(0,ho("id")),vt(1,In(new _(xn.partial().omit({id:!0})))),T("design:type",Function),T("design:paramtypes",[String,Object]),T("design:returntype",Promise)],ct.prototype,"update",null);qt([ya(":id"),wa(204),vt(0,ho("id")),T("design:type",Function),T("design:paramtypes",[String]),T("design:returntype",Promise)],ct.prototype,"remove",null);ct=qt([ba("schedules"),vt(0,ga(nt)),T("design:paramtypes",[nt])],ct);import{Controller as Ia,Inject as Ea,Query as vn,Sse as xa}from"@nestjs/common";import{Observable as On}from"rxjs";var Tn=function(n,t,e,o){var i=arguments.length,r=i<3?t:o===null?o=Object.getOwnPropertyDescriptor(t,e):o,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(n,t,e,o);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},De=function(n,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,t)},bo=function(n,t){return function(e,o){t(e,o,n)}},Qt=class{events;constructor(t){this.events=t}stream(t,e){return new On(o=>{let i=this.events.subscribe(r=>{let s=r;t!=null&&t!==""&&(!("jobId"in s)||s.jobId!==t)||e!=null&&e!==""&&(!("batchId"in s)||s.batchId!==e)||o.next({data:s})});return()=>{i()}})}};Tn([xa(),bo(0,vn("jobId")),bo(1,vn("batchId")),De("design:type",Function),De("design:paramtypes",[String,String]),De("design:returntype",On)],Qt.prototype,"stream",null);Qt=Tn([Ia("events"),bo(0,Ea(K)),De("design:paramtypes",[K])],Qt);import{Controller as Za,Get as tc,Header as ec}from"@nestjs/common";import{OpenAPIRegistry as Ya,OpenApiGeneratorV31 as Qa}from"@asteasolutions/zod-to-openapi";import{extendZodWithOpenApi as va}from"@asteasolutions/zod-to-openapi";import{z as Ta}from"zod";va(Ta);import{z as d}from"zod";import{engineSettingsPatchSchema as Oa,engineSettingsSchema as Pn,notificationPolicySchema as Ra,createSubjectViewSchema as Pa,reorderViewsBodySchema as Aa,scheduleSchema as An,subjectViewSchema as Nn,workflowDefinitionInputSchema as kn,workflowDefinitionSchema as Na}from"@knoflows/shared";import{z as Rn}from"zod";var $e=Rn.object({value:Rn.string().min(1)});var ka=d.enum(["pending","planning","waiting_for_human","waiting_for_children","implementing","testing","completed","failed","cancelled"]),Ca=d.object({subjectType:d.literal("ticket"),id:d.string(),source:d.enum(["jira","azure-devops","manual"]),title:d.string(),description:d.string().optional(),status:d.string(),assignee:d.string().optional(),url:d.string().optional(),raw:d.record(d.string(),d.unknown()).optional()}),Da=d.object({subjectType:d.literal("pull_request"),id:d.string(),source:d.enum(["bitbucket","github","manual"]),title:d.string(),description:d.string().optional(),sourceBranch:d.string(),targetBranch:d.string(),author:d.string().optional(),url:d.string().optional(),raw:d.record(d.string(),d.unknown()).optional()}),$a=d.object({subjectType:d.literal("documentation"),id:d.string(),source:d.enum(["confluence","notion","github_wiki","gitlab_wiki","azure_wiki","web","manual"]),title:d.string(),url:d.string().optional(),raw:d.record(d.string(),d.unknown()).optional()}),qe=d.discriminatedUnion("subjectType",[Ca,Da,$a]),qa=d.discriminatedUnion("mode",[d.object({mode:d.literal("single"),subject:qe}),d.object({mode:d.literal("collection"),subjects:d.array(qe)})]),La=d.object({id:d.string(),stepDefinitionId:d.string(),type:d.string(),status:d.enum(["pending","running","waiting_for_children","completed","failed","skipped"]),startedAt:d.string().optional(),completedAt:d.string().optional(),output:d.unknown().optional(),error:d.string().optional(),childJobIds:d.array(d.string()).optional(),iterations:d.array(d.object({index:d.number().int(),stepExecutions:d.array(d.record(d.string(),d.unknown())),startedAt:d.string(),completedAt:d.string().optional()})).optional()}),Cn=d.object({id:d.string(),workflowId:d.string(),status:ka,subjectContext:qa.optional(),selection:ke.optional(),batchId:d.string().optional(),parentJobId:d.string().optional(),parentStepExecutionId:d.string().optional(),fanOutIndex:d.number().int().optional(),retryOf:d.string().optional(),context:d.record(d.string(),d.unknown()),worktreePath:d.string().optional(),branch:d.string().optional(),currentStepId:d.string().optional(),currentStepExecutionId:d.string().optional(),stepHistory:d.array(La),createdAt:d.string(),updatedAt:d.string(),completedAt:d.string().optional()}),Dn=d.object({id:d.string(),workflowId:d.string(),selection:ke,resolvedSubjects:d.array(qe),jobIds:d.array(d.string()),status:d.enum(["running","completed","completed_with_issues","failed"]),triggeredBy:d.enum(["schedule","view_bulk","multiselect"]),scheduleId:d.string().optional(),notificationOverride:Ra.optional(),notificationSent:d.boolean(),createdAt:d.string(),completedAt:d.string().optional()}),Ba=d.discriminatedUnion("kind",[d.object({kind:d.literal("job"),job:Cn}),d.object({kind:d.literal("batch"),batch:Dn})]),Ja=d.object({ok:d.boolean(),service:d.string(),timestamp:d.string()}),Fa=d.object({providerId:d.string(),secretKey:d.string(),configured:d.boolean()}),Ua=d.object({error:d.string()}),Ma=d.object({type:d.string(),timestamp:d.string()}).passthrough(),Va=kn,Ka=Nn.partial().omit({id:!0,order:!0}),Xa=An.partial().omit({id:!0}),Ha=Oa,Wa=d.object({settings:Pn,restartRequired:d.boolean()}),O=d.object({id:d.string().min(1)}),yo=d.object({limit:d.string().optional().openapi({description:"Max items to return (default 50)"}),offset:d.string().optional().openapi({description:"Number of items to skip (default 0)"})});function Ga(n){let t=d.toJSONSchema(n),{$schema:e,...o}=t;return o}function $n(n){let t=(e,o)=>n.registerComponent("schemas",e,Ga(o)).ref;return{WorkflowDefinition:t("WorkflowDefinition",Na),WorkflowDefinitionInput:t("WorkflowDefinitionInput",kn),UpdateWorkflowBody:t("UpdateWorkflowBody",Va),SubjectView:t("SubjectView",Nn),CreateSubjectViewBody:t("CreateSubjectViewBody",Pa),ReorderViewsBody:t("ReorderViewsBody",Aa),UpdateViewBody:t("UpdateViewBody",Ka),Schedule:t("Schedule",An),UpdateScheduleBody:t("UpdateScheduleBody",Xa),EngineSettings:t("EngineSettings",Pn),UpdateSettingsBody:t("UpdateSettingsBody",Ha),SettingsPatchResponse:t("SettingsPatchResponse",Wa),SetSecretBody:t("SetSecretBody",$e),CreateJobBody:t("CreateJobBody",Ae),ResumeJobBody:t("ResumeJobBody",Ne),LaunchBody:t("LaunchBody",Ce),Job:t("Job",Cn),JobBatch:t("JobBatch",Dn),LaunchResponse:t("LaunchResponse",Ba),HealthResponse:t("HealthResponse",Ja),ProviderStatus:t("ProviderStatus",Fa),ErrorResponse:t("ErrorResponse",Ua),EngineEvent:t("EngineEvent",Ma),Subject:t("Subject",qe)}}import{z as R}from"zod";import{subjectTypeSchema as za}from"@knoflows/shared";function y(n,t){return{description:t,content:{"application/json":{schema:n}}}}function ut(n){return{type:"array",items:n}}function w(n,...t){let e={400:"Validation error",404:"Resource not found",409:"Conflict"};return Object.fromEntries(t.map(o=>[String(o),y(n.ErrorResponse,e[o]??"Error")]))}function qn(n,t){n.registerPath({method:"get",path:"/health",tags:["Health"],summary:"Health check",responses:{200:y(t.HealthResponse,"Service is healthy")}}),n.registerPath({method:"get",path:"/workflows",tags:["Workflows"],summary:"List workflow definitions",request:{query:R.object({cardinality:R.enum(["single","batch","aggregate"]).optional()})},responses:{200:y(ut(t.WorkflowDefinition),"Workflow definitions"),...w(t,400)}}),n.registerPath({method:"get",path:"/workflows/{id}",tags:["Workflows"],summary:"Get a workflow definition",request:{params:O},responses:{200:y(t.WorkflowDefinition,"Workflow definition"),...w(t,404)}}),n.registerPath({method:"post",path:"/workflows",tags:["Workflows"],summary:"Create a workflow definition",request:{body:{required:!0,content:{"application/json":{schema:t.WorkflowDefinitionInput}}}},responses:{201:y(t.WorkflowDefinition,"Created workflow definition"),...w(t,400)}}),n.registerPath({method:"patch",path:"/workflows/{id}",tags:["Workflows"],summary:"Update a workflow definition",request:{params:O,body:{required:!0,content:{"application/json":{schema:t.UpdateWorkflowBody}}}},responses:{200:y(t.WorkflowDefinition,"Updated workflow definition"),...w(t,400,404)}}),n.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:O},responses:{204:{description:"Workflow deleted"},...w(t,404,409)}}),n.registerPath({method:"get",path:"/views",tags:["Views"],summary:"List subject views",request:{query:R.object({subjectType:za.optional()})},responses:{200:y(ut(t.SubjectView),"Subject views"),...w(t,400)}}),n.registerPath({method:"get",path:"/views/{id}",tags:["Views"],summary:"Get a subject view",request:{params:O},responses:{200:y(t.SubjectView,"Subject view"),...w(t,404)}}),n.registerPath({method:"get",path:"/views/{id}/subjects",tags:["Views"],summary:"Preview subjects matching a view",description:"Live provider query for the View's saved filter. Same resolution path as launch() for { mode: 'view' }. Does not create Jobs or snapshots.",request:{params:O},responses:{200:y(ut(t.Subject),"Matching subjects"),...w(t,404,400)}}),n.registerPath({method:"patch",path:"/views/reorder",tags:["Views"],summary:"Reorder views within a subject type group",request:{body:{required:!0,content:{"application/json":{schema:t.ReorderViewsBody}}}},responses:{200:y(ut(t.SubjectView),"Reordered views for the subject type"),...w(t,400)}}),n.registerPath({method:"post",path:"/views",tags:["Views"],summary:"Create a subject view",request:{body:{required:!0,content:{"application/json":{schema:t.CreateSubjectViewBody}}}},responses:{201:y(t.SubjectView,"Created subject view"),...w(t,400)}}),n.registerPath({method:"patch",path:"/views/{id}",tags:["Views"],summary:"Update a subject view",request:{params:O,body:{required:!0,content:{"application/json":{schema:t.UpdateViewBody}}}},responses:{200:y(t.SubjectView,"Updated subject view"),...w(t,400,404)}}),n.registerPath({method:"delete",path:"/views/{id}",tags:["Views"],summary:"Delete a subject view",request:{params:O},responses:{204:{description:"Subject view deleted"},...w(t,404)}}),n.registerPath({method:"get",path:"/jobs",tags:["Jobs"],summary:"List jobs",request:{query:yo.extend({workflowId:R.string().optional(),status:R.enum(["pending","planning","waiting_for_human","waiting_for_children","implementing","testing","completed","failed","cancelled"]).optional(),batchId:R.string().optional(),parentJobId:R.string().optional(),topLevelOnly:R.enum(["true","false"]).optional().openapi({description:"When true, exclude jobs that belong to a batch or a parent (sub_workflow) job"})})},responses:{200:y(ut(t.Job),"Jobs"),...w(t,400)}}),n.registerPath({method:"get",path:"/jobs/{id}",tags:["Jobs"],summary:"Get a job",request:{params:O},responses:{200:y(t.Job,"Job"),...w(t,404)}}),n.registerPath({method:"post",path:"/jobs",tags:["Jobs"],summary:"Start a single job",request:{body:{required:!0,content:{"application/json":{schema:t.CreateJobBody}}}},responses:{201:y(t.Job,"Started job"),...w(t,400,404)}}),n.registerPath({method:"post",path:"/jobs/{id}/resume",tags:["Jobs"],summary:"Resume a job waiting for human input",request:{params:O,body:{required:!0,content:{"application/json":{schema:t.ResumeJobBody}}}},responses:{200:y(t.Job,"Resumed job"),...w(t,400,404,409)}}),n.registerPath({method:"post",path:"/jobs/{id}/retry",tags:["Jobs"],summary:"Retry a failed job",request:{params:O},responses:{200:y(t.Job,"Retry job"),...w(t,404,409)}}),n.registerPath({method:"get",path:"/batches",tags:["Batches"],summary:"List job batches",request:{query:yo.extend({workflowId:R.string().optional()})},responses:{200:y(ut(t.JobBatch),"Job batches")}}),n.registerPath({method:"get",path:"/batches/{id}",tags:["Batches"],summary:"Get a job batch",request:{params:O},responses:{200:y(t.JobBatch,"Job batch"),...w(t,404)}}),n.registerPath({method:"get",path:"/batches/{id}/jobs",tags:["Batches"],summary:"List jobs in a batch",request:{params:O},responses:{200:y(ut(t.Job),"Jobs in the batch"),...w(t,404)}}),n.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:y(t.LaunchResponse,"Launch result"),...w(t,400,404)}}),n.registerPath({method:"get",path:"/schedules",tags:["Schedules"],summary:"List schedules",request:{query:R.object({enabled:R.enum(["true","false"]).optional()})},responses:{200:y(ut(t.Schedule),"Schedules"),...w(t,400)}}),n.registerPath({method:"get",path:"/schedules/{id}",tags:["Schedules"],summary:"Get a schedule",request:{params:O},responses:{200:y(t.Schedule,"Schedule"),...w(t,404)}}),n.registerPath({method:"post",path:"/schedules",tags:["Schedules"],summary:"Create a schedule",description:"CRUD only \u2014 creating or enabling a schedule does not cause it to fire yet.",request:{body:{required:!0,content:{"application/json":{schema:t.Schedule}}}},responses:{201:y(t.Schedule,"Created schedule"),...w(t,400)}}),n.registerPath({method:"patch",path:"/schedules/{id}",tags:["Schedules"],summary:"Update a schedule",request:{params:O,body:{required:!0,content:{"application/json":{schema:t.UpdateScheduleBody}}}},responses:{200:y(t.Schedule,"Updated schedule"),...w(t,400,404)}}),n.registerPath({method:"delete",path:"/schedules/{id}",tags:["Schedules"],summary:"Delete a schedule",request:{params:O},responses:{204:{description:"Schedule deleted"},...w(t,404)}}),n.registerPath({method:"get",path:"/providers/status",tags:["Providers"],summary:"Provider secret configuration status",description:"Reports whether each known provider API key is set. Returns key *names* only \u2014 never secret values.",responses:{200:y(ut(t.ProviderStatus),"Provider configuration status")}}),n.registerPath({method:"get",path:"/settings",tags:["Settings"],summary:"Get engine settings",description:"Persisted provider configuration. Never includes secret values \u2014 those live in SecretStore.",responses:{200:y(t.EngineSettings,"Current engine settings")}}),n.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:y(t.SettingsPatchResponse,"Updated settings"),...w(t,400)}}),n.registerPath({method:"post",path:"/secrets/{key}",tags:["Settings"],summary:"Store a secret",description:"Writes to SecretStore. The response never includes the secret value.",request:{params:R.object({key:R.string().min(1)}),body:{required:!0,content:{"application/json":{schema:t.SetSecretBody}}}},responses:{204:{description:"Secret stored"},...w(t,400)}}),n.registerPath({method:"get",path:"/events",tags:["Events"],summary:"Subscribe to engine events (SSE)",description:"Server-Sent Events stream. Each event `data` field is a JSON EngineEvent. Optionally filter by jobId and/or batchId.",request:{query:R.object({jobId:R.string().optional(),batchId:R.string().optional()})},responses:{200:{description:"SSE stream of engine events",content:{"text/event-stream":{schema:t.EngineEvent}}}}})}var Le;function Ln(){if(Le)return Le;let n=new Ya,t=$n(n);return qn(n,t),Le=new Qa(n.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"}]}),Le}var Bn=function(n,t,e,o){var i=arguments.length,r=i<3?t:o===null?o=Object.getOwnPropertyDescriptor(t,e):o,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(n,t,e,o);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},wo=function(n,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,t)},Zt=class{getOpenApiDocument(){return Ln()}};Bn([tc("openapi.json"),ec("Content-Type","application/json"),wo("design:type",Function),wo("design:paramtypes",[]),wo("design:returntype",void 0)],Zt.prototype,"getOpenApiDocument",null);Zt=Bn([Za()],Zt);import{Controller as nc,Get as rc,Inject as ic}from"@nestjs/common";var Jn=function(n,t,e,o){var i=arguments.length,r=i<3?t:o===null?o=Object.getOwnPropertyDescriptor(t,e):o,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(n,t,e,o);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},Be=function(n,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,t)},oc=function(n,t){return function(e,o){t(e,o,n)}},te=class{providerStatus;constructor(t){this.providerStatus=t}async status(){return this.providerStatus.list()}};Jn([rc("status"),Be("design:type",Function),Be("design:paramtypes",[]),Be("design:returntype",Promise)],te.prototype,"status",null);te=Jn([nc("providers"),oc(0,ic(lt)),Be("design:paramtypes",[lt])],te);import{Body as sc,Controller as ac,Get as cc,Inject as uc,Patch as dc}from"@nestjs/common";import{engineSettingsPatchSchema as pc}from"@knoflows/shared";var go=function(n,t,e,o){var i=arguments.length,r=i<3?t:o===null?o=Object.getOwnPropertyDescriptor(t,e):o,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(n,t,e,o);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},Tt=function(n,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,t)},Fn=function(n,t){return function(e,o){t(e,o,n)}},Lt=class{settings;constructor(t){this.settings=t}get(){return this.settings.get()}async update(t){return{settings:await this.settings.update(t),restartRequired:Ko(t)}}};go([cc(),Tt("design:type",Function),Tt("design:paramtypes",[]),Tt("design:returntype",Promise)],Lt.prototype,"get",null);go([dc(),Fn(0,sc(new _(pc))),Tt("design:type",Function),Tt("design:paramtypes",[Object]),Tt("design:returntype",Promise)],Lt.prototype,"update",null);Lt=go([ac("settings"),Fn(0,uc(N)),Tt("design:paramtypes",[N])],Lt);import{Body as lc,Controller as fc,HttpCode as mc,Inject as hc,Param as bc,Post as yc}from"@nestjs/common";var Un=function(n,t,e,o){var i=arguments.length,r=i<3?t:o===null?o=Object.getOwnPropertyDescriptor(t,e):o,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(n,t,e,o);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},Je=function(n,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,t)},_o=function(n,t){return function(e,o){t(e,o,n)}},ee=class{secrets;constructor(t){this.secrets=t}async set(t,e){let o=t.trim();if(!o)throw new m("Secret key must not be empty");await this.secrets.set(o,e.value)}};Un([yc(":key"),mc(204),_o(0,bc("key")),_o(1,lc(new _($e))),Je("design:type",Function),Je("design:paramtypes",[String,Object]),Je("design:returntype",Promise)],ee.prototype,"set",null);ee=Un([fc("secrets"),_o(0,hc(U)),Je("design:paramtypes",[Function])],ee);var wc=function(n,t,e,o){var i=arguments.length,r=i<3?t:o===null?o=Object.getOwnPropertyDescriptor(t,e):o,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(n,t,e,o);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},Fe=class{};Fe=wc([gc({imports:[Z,Ct,mt,ft,Ot],controllers:[it,H,st,wt,ct,Qt,Zt,te,Lt,ee],providers:[{provide:_c,useClass:ve}]})],Fe);var jc=function(n,t,e,o){var i=arguments.length,r=i<3?t:o===null?o=Object.getOwnPropertyDescriptor(t,e):o,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(n,t,e,o);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},Ue=class{};Ue=jc([Sc({imports:[oe,ne,ft,_e,mt,Z,Ct,Fe],controllers:[Bt]})],Ue);import{apiReference as Ic}from"@scalar/nestjs-api-reference";function Mn(n){n.use("/api/docs",Ic({url:"/api/openapi.json",pageTitle:"Kno Engine API"}))}import{existsSync as Ec}from"node:fs";import{dirname as xc,join as Vn}from"node:path";import{fileURLToPath as vc}from"node:url";function Kn(){let n=xc(vc(import.meta.url)),t=[Vn(n,"../../static"),Vn(n,"../static")];for(let e of t)if(Ec(e))return e;return null}async function Rc(){let n=await Oc.create(Ue);n.enableCors(),n.setGlobalPrefix("api"),Mn(n);let t=Kn();t&&Tc(Xn(t,"index.html"))&&(n.useStaticAssets(t),n.use((o,i,r)=>{if(o.method!=="GET"&&o.method!=="HEAD"||o.path.startsWith("/api"))return r();i.sendFile(Xn(t,"index.html"))}));let e=Number(process.env.PORT??3e3);await n.listen(e)}Rc();
|
|
130
|
+
`),ga(o)}var ir=l(()=>{"use strict"});import{Injectable as Sa}from"@nestjs/common";import{mkdirSync as _a}from"node:fs";import{dirname as ja}from"node:path";import{fileURLToPath as Ia}from"node:url";import{DatabaseSync as sr}from"node:sqlite";var ya,wa,G,ar=l(()=>{"use strict";rr();ir();ya=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},wa=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},G=class{sqlite;db;constructor(){let e=process.env.KNO_SQLITE_PATH??Ia(new URL("../../data/kno.db",import.meta.url));e===":memory:"?this.sqlite=new sr(":memory:"):(_a(ja(e),{recursive:!0}),this.sqlite=new sr(e)),this.db=nr(this.sqlite),Fo(this.sqlite)}async onModuleInit(){Fo(this.sqlite)}getDb(){return this.db}getSqlite(){return this.sqlite}};G=ya([Sa(),wa("design:paramtypes",[])],G)});import{Injectable as va}from"@nestjs/common";import{eq as cr}from"drizzle-orm";var xa,Ea,L,Be=l(()=>{"use strict";$e();xa=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},Ea=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},L=class{db;sqlite;constructor(t,e){this.db=t,this.sqlite=e}async create(t){let e=new Date().toISOString();return await this.db.insert(et).values({id:t.id,name:t.name,description:t.description??null,appliesTo:t.appliesTo,cardinality:t.cardinality,inputSchema:t.inputSchema,steps:t.steps,notificationPolicy:t.notificationPolicy,createdAt:e,updatedAt:e}),await this.get(t.id)}async get(t){let e=await this.db.query.workflowDefinitions.findFirst({where:{id:t}});return e?this.toDomain(e):null}async update(t,e){let n=await this.get(t);return n?(await this.db.update(et).set({name:e.name??n.name,description:e.description!==void 0?e.description??null:n.description??null,appliesTo:e.appliesTo??n.appliesTo,cardinality:e.cardinality??n.cardinality,inputSchema:e.inputSchema??n.inputSchema,steps:e.steps??n.steps,notificationPolicy:e.notificationPolicy??n.notificationPolicy,updatedAt:new Date().toISOString()}).where(cr(et.id,t)),this.get(t)):null}async list(t={}){return(t.cardinality?await this.db.query.workflowDefinitions.findMany({where:{cardinality:t.cardinality}}):await this.db.query.workflowDefinitions.findMany()).map(n=>this.toDomain(n))}async delete(t){if(!await this.get(t))return!1;try{this.sqlite?.exec("PRAGMA foreign_keys = OFF"),await this.db.delete(et).where(cr(et.id,t))}finally{this.sqlite?.exec("PRAGMA foreign_keys = ON")}return!0}toDomain(t){return{id:t.id,name:t.name,...t.description!=null?{description:t.description}:{},appliesTo:t.appliesTo,cardinality:t.cardinality,inputSchema:t.inputSchema,steps:t.steps,notificationPolicy:t.notificationPolicy}}};L=xa([va(),Ea("design:paramtypes",[Object,Function])],L)});import{Injectable as Ra}from"@nestjs/common";import{eq as Uo}from"drizzle-orm";var Ta,Oa,ur,B,Je=l(()=>{"use strict";$o();Ta=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},Oa=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},ur=["ticket","pull_request","documentation"],B=class{db;constructor(t){this.db=t}async create(t){let e=await this.nextOrder(t.subjectType);return await this.db.insert(ot).values({id:t.id,name:t.name,subjectType:t.subjectType,query:t.query,description:t.description??null,order:e}),await this.get(t.id)}async get(t){let e=await this.db.query.subjectViews.findFirst({where:{id:t}});return e?this.toDomain(e):null}async update(t,e){let n=await this.get(t);return n?(await this.db.update(ot).set({name:e.name??n.name,subjectType:e.subjectType??n.subjectType,query:e.query??n.query,description:e.description!==void 0?e.description??null:n.description??null}).where(Uo(ot.id,t)),this.get(t)):null}async list(t={}){let e=t.subjectType?await this.db.query.subjectViews.findMany({where:{subjectType:t.subjectType}}):await this.db.query.subjectViews.findMany();return this.sortViews(e.map(n=>this.toDomain(n)))}async reorder(t){let e=[];for(let i of t){let r=await this.get(i);if(!r)return[];e.push(r)}let n=e[0].subjectType;if(!e.every(i=>i.subjectType===n))return[];for(let i=0;i<t.length;i+=1)await this.db.update(ot).set({order:i}).where(Uo(ot.id,t[i]));return this.list({subjectType:n})}async delete(t){return await this.get(t)?(await this.db.delete(ot).where(Uo(ot.id,t)),!0):!1}async nextOrder(t){let e=await this.db.query.subjectViews.findMany({where:{subjectType:t}});return e.length===0?0:Math.max(...e.map(n=>n.order))+1}sortViews(t){return[...t].sort((e,n)=>{let i=ur.indexOf(e.subjectType)-ur.indexOf(n.subjectType);return i!==0?i:e.order-n.order})}toDomain(t){return{id:t.id,name:t.name,subjectType:t.subjectType,query:t.query,order:t.order,...t.description!=null?{description:t.description}:{}}}};B=Ta([Ra(),Oa("design:paramtypes",[Object])],B)});import{Injectable as ka}from"@nestjs/common";import{eq as Mo}from"drizzle-orm";import{randomUUID as Na}from"node:crypto";function Ca(o){return o?o.mode==="single"?[o.subject]:o.subjects:[]}function Da(o){if(o.length!==0)return o.length===1?{mode:"single",subject:o[0]}:{mode:"collection",subjects:o}}function pr(o,t,e=null,n=null){let i=[];for(let r of t)if(i.push({id:r.id,jobId:o,stepDefinitionId:r.stepDefinitionId,type:r.type,status:r.status,startedAt:r.startedAt??null,completedAt:r.completedAt??null,output:r.output??null,error:r.error??null,childJobIds:r.childJobIds??null,parentStepExecutionId:e,iterationIndex:n}),r.iterations)for(let s of r.iterations)i.push(...pr(o,s.stepExecutions,r.id,s.index));return i}function $a(o){let t=new Map;for(let i of o){let r=i.parentStepExecutionId,s=t.get(r)??[];s.push(i),t.set(r,s)}let e=i=>{let r=t.get(i)??[];if(r.length===0)return;let s=new Map;for(let a of r){if(a.iterationIndex==null)continue;let u=s.get(a.iterationIndex)??[];u.push(a),s.set(a.iterationIndex,u)}if(s.size!==0)return[...s.entries()].sort(([a],[u])=>a-u).map(([a,u])=>{let c=u.map(f=>dr(f,e(f.id)));return{index:a,stepExecutions:c,startedAt:qa(c),...Ba(c)?{completedAt:La(c)}:{}}})};return(t.get(null)??[]).filter(i=>i.iterationIndex==null).map(i=>dr(i,e(i.id)))}function dr(o,t){return{id:o.id,stepDefinitionId:o.stepDefinitionId,type:o.type,status:o.status,...o.startedAt!=null?{startedAt:o.startedAt}:{},...o.completedAt!=null?{completedAt:o.completedAt}:{},...o.output!==null&&o.output!==void 0?{output:o.output}:{},...o.error!=null?{error:o.error}:{},...o.childJobIds!=null?{childJobIds:o.childJobIds}:{},...t&&t.length>0?{iterations:t}:{}}}function qa(o){let t=o.map(e=>e.startedAt).filter(e=>e!=null);return t.length===0?"":t.reduce((e,n)=>e<n?e:n)}function La(o){return o.map(e=>e.completedAt).filter(e=>e!=null).reduce((e,n)=>e>n?e:n)}function Ba(o){return o.length>0&&o.every(t=>t.completedAt!=null)}var Pa,Aa,x,Ut=l(()=>{"use strict";ae();qo();Lo();Pa=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},Aa=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},x=class{db;constructor(t){this.db=t}async create(t){return await this.db.insert(rt).values(this.jobToRow(t)),await this.replaceSubjects(t.id,t.subjectContext),await this.replaceStepExecutions(t.id,t.stepHistory),await this.get(t.id)}async get(t){let e=await this.db.query.jobs.findFirst({where:{id:t},with:{subjects:!0,stepExecutions:!0}});return e?this.toDomain(e,e.subjects,e.stepExecutions):null}async update(t,e){let n=await this.get(t);if(!n)return null;let i={...n,...e,id:t,context:e.context??n.context,stepHistory:e.stepHistory??n.stepHistory,updatedAt:e.updatedAt??new Date().toISOString()};return await this.db.update(rt).set({workflowId:i.workflowId,status:i.status,selection:i.selection??null,batchId:i.batchId??null,parentJobId:i.parentJobId??null,parentStepExecutionId:i.parentStepExecutionId??null,fanOutIndex:i.fanOutIndex??null,retryOf:i.retryOf??null,context:i.context,worktreePath:i.worktreePath??null,branch:i.branch??null,currentStepId:i.currentStepId??null,currentStepExecutionId:i.currentStepExecutionId??null,createdAt:i.createdAt,updatedAt:i.updatedAt,completedAt:i.completedAt??null}).where(Mo(rt.id,t)),e.subjectContext!==void 0&&await this.replaceSubjects(t,e.subjectContext),e.stepHistory!==void 0&&await this.replaceStepExecutions(t,e.stepHistory),this.get(t)}async list(t={}){let e={};t.workflowId!==void 0&&(e.workflowId=t.workflowId),t.status!==void 0&&(e.status=t.status),t.batchId!==void 0&&(e.batchId=t.batchId),t.parentJobId!==void 0&&(e.parentJobId=t.parentJobId),t.parentStepExecutionId!==void 0&&(e.parentStepExecutionId=t.parentStepExecutionId);let i=(Object.keys(e).length>0?await this.db.query.jobs.findMany({where:e,with:{subjects:!0,stepExecutions:!0}}):await this.db.query.jobs.findMany({with:{subjects:!0,stepExecutions:!0}})).map(r=>this.toDomain(r,r.subjects,r.stepExecutions));return t.topLevelOnly?i.filter(r=>r.batchId==null&&r.parentJobId==null):i}jobToRow(t){return{id:t.id,workflowId:t.workflowId,status:t.status,selection:t.selection??null,batchId:t.batchId??null,parentJobId:t.parentJobId??null,parentStepExecutionId:t.parentStepExecutionId??null,fanOutIndex:t.fanOutIndex??null,retryOf:t.retryOf??null,context:t.context,worktreePath:t.worktreePath??null,branch:t.branch??null,currentStepId:t.currentStepId??null,currentStepExecutionId:t.currentStepExecutionId??null,createdAt:t.createdAt,updatedAt:t.updatedAt,completedAt:t.completedAt??null}}async replaceSubjects(t,e){await this.db.delete(Jt).where(Mo(Jt.jobId,t));let n=Ca(e);n.length!==0&&await this.db.insert(Jt).values(n.map(i=>({id:Na(),jobId:t,subjectType:i.subjectType,subjectId:i.id,snapshot:i})))}async replaceStepExecutions(t,e){await this.db.delete(Nt).where(Mo(Nt.jobId,t));let n=pr(t,e);n.length!==0&&await this.db.insert(Nt).values(n)}toDomain(t,e,n){let i=Da(e.map(s=>s.snapshot)),r=$a(n);return{id:t.id,workflowId:t.workflowId,status:t.status,...i?{subjectContext:i}:{},...t.selection!=null?{selection:t.selection}:{},...t.batchId!=null?{batchId:t.batchId}:{},...t.parentJobId!=null?{parentJobId:t.parentJobId}:{},...t.parentStepExecutionId!=null?{parentStepExecutionId:t.parentStepExecutionId}:{},...t.fanOutIndex!=null?{fanOutIndex:t.fanOutIndex}:{},...t.retryOf!=null?{retryOf:t.retryOf}:{},context:t.context,...t.worktreePath!=null?{worktreePath:t.worktreePath}:{},...t.branch!=null?{branch:t.branch}:{},...t.currentStepId!=null?{currentStepId:t.currentStepId}:{},...t.currentStepExecutionId!=null?{currentStepExecutionId:t.currentStepExecutionId}:{},stepHistory:r,createdAt:t.createdAt,updatedAt:t.updatedAt,...t.completedAt!=null?{completedAt:t.completedAt}:{}}}};x=Pa([ka(),Aa("design:paramtypes",[Object])],x)});import{Injectable as Ua}from"@nestjs/common";import{eq as Ma}from"drizzle-orm";var Ja,Fa,J,Fe=l(()=>{"use strict";qe();Ja=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},Fa=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},J=class{db;constructor(t){this.db=t}async create(t){return await this.db.insert(wt).values({id:t.id,workflowId:t.workflowId,selection:t.selection,resolvedSubjects:t.resolvedSubjects,status:t.status,triggeredBy:t.triggeredBy,scheduleId:t.scheduleId??null,notificationOverride:t.notificationOverride??null,notificationSent:t.notificationSent,createdAt:t.createdAt,completedAt:t.completedAt??null}),await this.get(t.id)}async get(t){let e=await this.db.query.jobBatches.findFirst({where:{id:t},with:{jobs:!0}});return e?this.toDomain(e,e.jobs.map(n=>n.id)):null}async update(t,e){let n=await this.get(t);return n?(await this.db.update(wt).set({workflowId:e.workflowId??n.workflowId,selection:e.selection??n.selection,resolvedSubjects:e.resolvedSubjects??n.resolvedSubjects,status:e.status??n.status,triggeredBy:e.triggeredBy??n.triggeredBy,scheduleId:e.scheduleId!==void 0?e.scheduleId??null:n.scheduleId??null,notificationOverride:e.notificationOverride!==void 0?e.notificationOverride??null:n.notificationOverride??null,notificationSent:e.notificationSent??n.notificationSent,createdAt:e.createdAt??n.createdAt,completedAt:e.completedAt!==void 0?e.completedAt??null:n.completedAt??null}).where(Ma(wt.id,t)),this.get(t)):null}async list(t={}){return(t.workflowId?await this.db.query.jobBatches.findMany({where:{workflowId:t.workflowId},with:{jobs:!0}}):await this.db.query.jobBatches.findMany({with:{jobs:!0}})).map(n=>this.toDomain(n,n.jobs.map(i=>i.id)))}toDomain(t,e){return{id:t.id,workflowId:t.workflowId,selection:t.selection,resolvedSubjects:t.resolvedSubjects,jobIds:e,status:t.status,triggeredBy:t.triggeredBy,...t.scheduleId!=null?{scheduleId:t.scheduleId}:{},...t.notificationOverride!=null?{notificationOverride:t.notificationOverride}:{},notificationSent:t.notificationSent,createdAt:t.createdAt,...t.completedAt!=null?{completedAt:t.completedAt}:{}}}};J=Ja([Ua(),Fa("design:paramtypes",[Object])],J)});import{Injectable as Xa}from"@nestjs/common";import{eq as lr}from"drizzle-orm";var Va,Ka,dt,Vo=l(()=>{"use strict";Bo();Va=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},Ka=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},dt=class{db;constructor(t){this.db=t}async create(t){return await this.db.insert(St).values({id:t.id,workflowId:t.workflowId,viewId:t.viewId,triggerType:t.trigger.type,cadence:t.trigger.cadence,notificationOverride:t.notificationOverride??null,missedFirePolicy:t.missedFirePolicy,enabled:t.enabled,lastFiredAt:t.lastFiredAt??null,createdAt:t.createdAt}),await this.get(t.id)}async get(t){let e=await this.db.query.schedules.findFirst({where:{id:t}});return e?this.toDomain(e):null}async update(t,e){let n=await this.get(t);if(!n)return null;let i=e.trigger??n.trigger;return await this.db.update(St).set({workflowId:e.workflowId??n.workflowId,viewId:e.viewId??n.viewId,triggerType:i.type,cadence:i.cadence,notificationOverride:e.notificationOverride!==void 0?e.notificationOverride??null:n.notificationOverride??null,missedFirePolicy:e.missedFirePolicy??n.missedFirePolicy,enabled:e.enabled??n.enabled,lastFiredAt:e.lastFiredAt!==void 0?e.lastFiredAt??null:n.lastFiredAt??null,createdAt:e.createdAt??n.createdAt}).where(lr(St.id,t)),this.get(t)}async list(t={}){return(t.enabled!==void 0?await this.db.query.schedules.findMany({where:{enabled:t.enabled}}):await this.db.query.schedules.findMany()).map(n=>this.toDomain(n))}async delete(t){return await this.get(t)?(await this.db.delete(St).where(lr(St.id,t)),!0):!1}async findDue(t){return(await this.list({enabled:!0})).filter(n=>n.lastFiredAt==null||n.lastFiredAt<t)}toDomain(t){return{id:t.id,workflowId:t.workflowId,viewId:t.viewId,trigger:{type:"cron",cadence:t.cadence},...t.notificationOverride!=null?{notificationOverride:t.notificationOverride}:{},missedFirePolicy:t.missedFirePolicy,enabled:t.enabled,...t.lastFiredAt!=null?{lastFiredAt:t.lastFiredAt}:{},createdAt:t.createdAt}}};dt=Va([Xa(),Ka("design:paramtypes",[Object])],dt)});import{Injectable as Ga}from"@nestjs/common";import{eq as za}from"drizzle-orm";function Ya(o,t){let e={...o.activeProviders,...t.activeProviders},n=t.jira!==void 0?{...o.jira,...t.jira}:o.jira,i=t.bitbucket!==void 0?{...o.bitbucket,...t.bitbucket}:o.bitbucket;return Ko({activeProviders:e,...n&&Object.keys(n).length>0?{jira:n}:{},...i&&Object.keys(i).length>0?{bitbucket:i}:{}})}function Ko(o){return{...o,activeProviders:{ticket:o.activeProviders?.ticket??"manual",repo:o.activeProviders?.repo??"manual",agent:o.activeProviders?.agent??"claude"},...o.jira?{jira:o.jira}:{},...o.bitbucket?{bitbucket:o.bitbucket}:{}}}function fr(o){return Object.prototype.hasOwnProperty.call(o,"activeProviders")}var Ha,Wa,D,Ue=l(()=>{"use strict";Jo();Ha=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},Wa=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},D=class{db;constructor(t){this.db=t}async get(){let t=await this.db.query.settings.findFirst({where:{id:ue}});return Ko(t?t.data:{})}async update(t){let e=Ya(await this.get(),t);return await this.db.query.settings.findFirst({where:{id:ue}})?await this.db.update(Ft).set({data:e}).where(za(Ft.id,ue)):await this.db.insert(Ft).values({id:ue,data:e}),e}};D=Ha([Ga(),Wa("design:paramtypes",[Object])],D)});import{Module as Za}from"@nestjs/common";var Qa,tc,it,de=l(()=>{"use strict";ar();Be();Je();Ut();Fe();Vo();Ue();Qa=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},tc=[L,B,x,J,dt,D],it=class{};it=Qa([Za({providers:[G,{provide:L,useFactory:o=>new L(o.getDb(),o.getSqlite()),inject:[G]},{provide:B,useFactory:o=>new B(o.getDb()),inject:[G]},{provide:x,useFactory:o=>new x(o.getDb()),inject:[G]},{provide:J,useFactory:o=>new J(o.getDb()),inject:[G]},{provide:dt,useFactory:o=>new dt(o.getDb()),inject:[G]},{provide:D,useFactory:o=>new D(o.getDb()),inject:[G]}],exports:[G,...tc]})],it)});function Xo(o){return o==null?"":typeof o=="string"?o:hr(o).replace(/\n+$/,"")}function mr(o){return{version:1,type:"doc",content:o.split(`
|
|
131
|
+
`).map(e=>({type:"paragraph",content:e.length===0?[]:[{type:"text",text:e}]}))}}function hr(o){if(o==null||typeof o!="object")return"";let t=o;if(t.type==="text")return t.text??"";if(t.type==="hardBreak")return`
|
|
132
|
+
`;let e=(t.content??[]).map(hr).join("");return t.type==="paragraph"||t.type==="heading"||t.type==="blockquote"||t.type==="listItem"?`${e}
|
|
133
|
+
`:e}var br=l(()=>{"use strict"});function nc(o){if(typeof o.jql=="string"&&o.jql.trim().length>0)return o.jql;let t=[];if(Ve(o.project)&&t.push(`project = ${Ke(o.project)}`),Ve(o.status)&&t.push(`status = ${Ke(o.status)}`),Ve(o.assignee)&&t.push(`assignee = ${Ke(o.assignee)}`),Ve(o.sprintId)){let e=o.sprintId;t.push(typeof e=="number"||/^\d+$/.test(String(e))?`sprint = ${Number(e)}`:`sprint = ${Ke(e)}`)}if(t.length===0)throw new Error("Jira query requires jql or at least one of project, status, assignee, sprintId");return t.join(" AND ")}function Ve(o){return o!=null&&o!==""}function Ke(o){return`"${String(o).replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function gr(o,t){let e=String(o.key??o.id??""),n=o.fields??{},i=Xo(n.description);return{id:e,source:"jira",title:String(n.summary??""),...i?{description:i}:{},status:String(n.status?.name??""),...n.assignee?.displayName?{assignee:String(n.assignee.displayName)}:{},url:`${t.replace(/\/$/,"")}/browse/${e}`,raw:o}}var Mt,ec,oc,Me,Xe,Ho=l(()=>{"use strict";br();Mt="kno.jira.apiToken",ec=50,oc=10,Me=500,Xe=class{secrets;settings;fetchFn;constructor(t,e,n=fetch){this.secrets=t,this.settings=e,this.fetchFn=n}async get(t){let{baseUrl:e}=await this.requireConfig(),n=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(t)}`);return gr(n,e)}async query(t){let{baseUrl:e}=await this.requireConfig(),n=nc(t),i=[],r,s=new Set;for(let a=0;a<oc&&i.length<Me;a++){let u={jql:n,maxResults:Math.min(ec,Me-i.length),fields:["summary","description","status","assignee"]};r&&(u.nextPageToken=r);let c=await this.request("POST","/rest/api/3/search/jql",{body:u}),f=Array.isArray(c.issues)?c.issues:[];for(let y of f){if(i.length>=Me)break;i.push(gr(y,e))}let m=typeof c.nextPageToken=="string"?c.nextPageToken:void 0;if(c.isLast===!0||!m||f.length===0||m===r||s.has(m))break;s.add(m),r=m}return i}async getComments(t){let e=[],n=0,i=100,r=Me;for(;e.length<r;){let s=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(t)}/comment?startAt=${n}&maxResults=${i}`),a=Array.isArray(s.comments)?s.comments:[];for(let u of a)e.push({id:String(u.id??""),subjectId:t,body:Xo(u.body),...u.author?.displayName?{author:u.author.displayName}:{},createdAt:u.created??"",raw:u});if(n+=a.length,a.length===0||typeof s.total=="number"&&n>=s.total||a.length<i)break}return e}async postComment(t,e){await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(t)}/comment`,{body:{body:mr(e)}})}async updateStatus(t,e){let n=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(t)}/transitions`),i=Array.isArray(n.transitions)?n.transitions:[],r=e.trim().toLowerCase(),s=i.find(a=>(a.to?.name??"").trim().toLowerCase()===r);if(!s?.id){let a=i.map(c=>c.to?.name).filter(c=>typeof c=="string"&&c.length>0),u=a.length>0?a.join(", "):"(none)";throw new Error(`No Jira transition to status '${e}' from the current state. Available: ${u}`)}await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(t)}/transitions`,{body:{transition:{id:s.id}}})}async requireConfig(){let t=(await this.settings.get()).jira,e=t?.baseUrl?.trim(),n=t?.email?.trim(),i=await this.secrets.get(Mt),r=[];if(e||r.push("settings.jira.baseUrl"),n||r.push("settings.jira.email"),i||r.push(`SecretStore '${Mt}'`),r.length>0)throw new Error(`Jira is not configured \u2014 missing ${r.join(", ")}. Set jira.baseUrl and jira.email via PATCH /api/settings, and store the API token with: POST /api/secrets/${Mt} or npm --workspace apps/engine run set-secret -- ${Mt} <value>`);return{baseUrl:e,email:n,token:i}}async request(t,e,n={}){let{baseUrl:i,email:r,token:s}=await this.requireConfig(),a=`${i.replace(/\/$/,"")}${e}`,u={Authorization:`Basic ${Buffer.from(`${r}:${s}`).toString("base64")}`,Accept:"application/json"};n.body!==void 0&&(u["Content-Type"]="application/json");let c=await this.fetchFn(a,{method:t,headers:u,...n.body!==void 0?{body:JSON.stringify(n.body)}:{}});if(!c.ok){let m=await c.text().catch(()=>"");throw new Error(`Jira ${t} ${e} failed (${c.status}): ${m||c.statusText}`)}if(c.status===204)return;let f=await c.text();if(f)return JSON.parse(f)}}});function He(o){let t=o.trim(),e=t.lastIndexOf("#");if(e<=0||e===t.length-1)throw new Error(`Bitbucket pull request id must be '{repoSlug}#{prNumber}' (e.g. 'kno-engine#42'), got '${o}'`);let n=t.slice(0,e),i=t.slice(e+1);if(!/^\d+$/.test(i))throw new Error(`Bitbucket pull request id must be '{repoSlug}#{prNumber}' with a numeric PR number, got '${o}'`);return{repoSlug:n,prNumber:i}}function ic(o,t){return`${o}#${t}`}function sc(o){let t=o.repoSlug;if(typeof t!="string"||t.trim().length===0)throw new Error("Bitbucket query requires filter.repoSlug \u2014 PR listing is scoped per repository");return t.trim()}function ac(o){if(typeof o.q=="string"&&o.q.trim().length>0)return o.q;if(uc(o.state)){let t=String(o.state).trim().toUpperCase();if(t!=="OPEN"&&t!=="MERGED"&&t!=="DECLINED")throw new Error(`Bitbucket query filter.state must be OPEN, MERGED, or DECLINED, got '${String(o.state)}'`);return`state="${t}"`}}function cc(o){let t=o.trim().toLowerCase();if(t==="approved")return"approve";if(t==="declined"||t==="rejected")return"decline";if(t==="merged")return"merge";throw new Error(`No Bitbucket action for status '${o}'. Accepted: approved, declined/rejected, merged`)}function uc(o){return o!=null&&o!==""}function yr(o,t){let e=String(o.id??""),n=typeof o.description=="string"?o.description:"";return{id:ic(t,e),source:"bitbucket",title:String(o.title??""),...n?{description:n}:{},sourceBranch:String(o.source?.branch?.name??""),targetBranch:String(o.destination?.branch?.name??""),...o.author?.display_name?{author:o.author.display_name}:{},...o.links?.html?.href?{url:o.links.html.href}:{},raw:o}}function dc(o,t){let e=o.user?.display_name??o.author?.display_name;return{id:String(o.id??""),subjectId:t,body:o.content?.raw??"",...e?{author:e}:{},createdAt:o.created_on??"",raw:o}}var Vt,rc,We,Wo=l(()=>{"use strict";Vt="kno.bitbucket.apiToken",rc="https://api.bitbucket.org/2.0",We=class{secrets;settings;fetchFn;constructor(t,e,n=fetch){this.secrets=t,this.settings=e,this.fetchFn=n}async get(t){let{repoSlug:e,prNumber:n}=He(t),{workspace:i}=await this.requireConfig(),r=await this.request("GET",this.prPath(i,e,n));return yr(r,e)}async query(t){let e=sc(t),{baseUrl:n,workspace:i}=await this.requireConfig(),r=ac(t),s=[],a=new Set,u=new URLSearchParams({pagelen:String(50)});r&&u.set("q",r);let c=`${n.replace(/\/$/,"")}/repositories/${encodeURIComponent(i)}/${encodeURIComponent(e)}/pullrequests?${u.toString()}`;for(let f=0;f<10&&s.length<500&&!(!c||a.has(c));f++){a.add(c);let m=await this.request("GET",c),y=Array.isArray(m.values)?m.values:[];for(let I of y){if(s.length>=500)break;s.push(yr(I,e))}let h=typeof m.next=="string"&&m.next.length>0?m.next:void 0;if(!h||y.length===0)break;c=h}return s}async getComments(t){let{repoSlug:e,prNumber:n}=He(t),{workspace:i}=await this.requireConfig(),r=[],s=new Set,a=`${this.prPath(i,e,n)}/comments?pagelen=50`;for(let u=0;u<10&&r.length<500&&!(!a||s.has(a));u++){s.add(a);let c=await this.request("GET",a),f=Array.isArray(c.values)?c.values:[];for(let y of f)r.push(dc(y,t));let m=typeof c.next=="string"&&c.next.length>0?c.next:void 0;if(!m||f.length===0)break;a=m}return r}async postComment(t,e){let{repoSlug:n,prNumber:i}=He(t),{workspace:r}=await this.requireConfig();await this.request("POST",`${this.prPath(r,n,i)}/comments`,{body:{content:{raw:e}}})}async updateStatus(t,e){let{repoSlug:n,prNumber:i}=He(t),{workspace:r}=await this.requireConfig(),s=cc(e);await this.request("POST",`${this.prPath(r,n,i)}/${s}`)}prPath(t,e,n){return`/repositories/${encodeURIComponent(t)}/${encodeURIComponent(e)}/pullrequests/${encodeURIComponent(n)}`}async requireConfig(){let t=(await this.settings.get()).bitbucket,e=(t?.baseUrl?.trim()||rc).replace(/\/$/,""),n=t?.email?.trim(),i=t?.workspace?.trim(),r=await this.secrets.get(Vt),s=[];if(n||s.push("settings.bitbucket.email"),i||s.push("settings.bitbucket.workspace"),r||s.push(`SecretStore '${Vt}'`),s.length>0)throw new Error(`Bitbucket is not configured \u2014 missing ${s.join(", ")}. Set bitbucket.email and bitbucket.workspace via PATCH /api/settings, and store the API token with: POST /api/secrets/${Vt} or npm --workspace apps/engine run set-secret -- ${Vt} <value>`);return{baseUrl:e,email:n,workspace:i,token:r}}async request(t,e,n={}){let{baseUrl:i,email:r,token:s}=await this.requireConfig(),a=e.startsWith("http://")||e.startsWith("https://")?e:`${i}${e.startsWith("/")?e:`/${e}`}`,u={Authorization:`Basic ${Buffer.from(`${r}:${s}`).toString("base64")}`,Accept:"application/json"};n.body!==void 0&&(u["Content-Type"]="application/json");let c=await this.fetchFn(a,{method:t,headers:u,...n.body!==void 0?{body:JSON.stringify(n.body)}:{}});if(!c.ok){let m=await c.text().catch(()=>"");throw new Error(`Bitbucket ${t} ${e} failed (${c.status}): ${m||c.statusText}`)}if(c.status===204)return;let f=await c.text();if(f)return JSON.parse(f)}}});import{Injectable as mc,Logger as hc,Inject as bc}from"@nestjs/common";async function wr(o){let t=[];for(let e of gc){let n=await o.get(e.secretKey);t.push({providerId:e.providerId,secretKey:e.secretKey,configured:typeof n=="string"&&n.length>0})}return t}async function yc(o,t){let e=await wr(o);for(let n of e)n.configured||t(`${n.providerId} API key not configured (looked up as '${n.secretKey}'). GET /api/providers/status lists what's missing; store a key with: POST /api/secrets/${n.secretKey} or npm --workspace apps/engine run set-secret -- ${n.secretKey} <value>`)}function Sr(o={}){let t=o.activeProviders?.agent;if(t==null)return"claude";if(t==="claude"||t==="cursor")return t;throw new Error(`Invalid activeProviders.agent '${String(t)}'. Expected 'claude' or 'cursor'.`)}function _r(o={}){let t=o.activeProviders?.ticket;if(t==null||t==="manual")return"manual";if(t==="jira")return"jira";throw new Error(`Invalid activeProviders.ticket '${String(t)}'. Expected 'jira' or 'manual'.`)}function jr(o={}){let t=o.activeProviders?.repo;if(t==null||t==="manual")return"manual";if(t==="bitbucket")return"bitbucket";throw new Error(`Invalid activeProviders.repo '${String(t)}'. Expected 'bitbucket' or 'manual'.`)}var pc,lc,fc,Go,gc,_t,zo=l(()=>{"use strict";yt();Ho();Wo();pc=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},lc=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},fc=function(o,t){return function(e,n){t(e,n,o)}},gc=[{providerId:"anthropic",secretKey:ct("anthropic")},{providerId:"cursor",secretKey:ct("cursor")},{providerId:"jira",secretKey:Mt},{providerId:"bitbucket",secretKey:Vt}];_t=Go=class{secrets;logger=new hc(Go.name);constructor(t){this.secrets=t}async onModuleInit(){await yc(this.secrets,t=>this.logger.warn(t))}list(){return wr(this.secrets)}};_t=Go=pc([mc(),fc(0,bc(H)),lc("design:paramtypes",[Function])],_t)});import{Module as Sc}from"@nestjs/common";import{fileURLToPath as _c}from"node:url";import{dirname as jc,join as Ic}from"node:path";var wc,xc,jt,Ge=l(()=>{"use strict";Ie();Nn();Ee();Cn();Te();Dn();Oo();Vn();Kn();No();Xn();Co();Wn();Do();yt();de();Ue();zo();Ho();Wo();wc=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},xc=Ic(jc(_c(import.meta.url)),"../../../knowledge"),jt=class{};jt=wc([Sc({imports:[Bt,it],providers:[{provide:Pt,useFactory:async(o,t)=>_r(await t.get())==="jira"?new Xe(o,t):new xe([]),inject:[H,D]},{provide:At,useFactory:async(o,t)=>jr(await t.get())==="bitbucket"?new We(o,t):new ve([]),inject:[H,D]},{provide:kt,useFactory:()=>new Oe([])},{provide:ee,useFactory:async(o,t)=>Sr(await t.get())==="cursor"?new Ne(o):new ke(o),inject:[H,D]},{provide:re,useClass:Ce},{provide:ie,useFactory:()=>new De(xc)},_t],exports:[Pt,At,kt,ee,re,ie,_t]})],jt)});import{Module as vc}from"@nestjs/common";var Ec,ze,Ir=l(()=>{"use strict";Ec=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},ze=class{};ze=Ec([vc({})],ze)});import{Injectable as Oc}from"@nestjs/common";var Tc,z,Ye=l(()=>{"use strict";Tc=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},z=class{listeners=new Set;emit(t){for(let e of this.listeners)e(t)}subscribe(t){return this.listeners.add(t),()=>this.listeners.delete(t)}};z=Tc([Oc()],z)});import{Global as Pc,Module as Ac}from"@nestjs/common";var Rc,It,Qe=l(()=>{"use strict";Ye();Rc=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},It=class{};It=Rc([Pc(),Ac({providers:[z],exports:[z]})],It)});import{Injectable as Cc}from"@nestjs/common";import{execFile as Dc}from"node:child_process";import{mkdirSync as xr}from"node:fs";import{join as Yo}from"node:path";import{promisify as $c}from"node:util";function Er(o){return o==null?"":typeof o=="string"?o:o.toString("utf8")}function vr(o){return Yo(o,"worktrees")}var kc,Nc,qc,pt,Qo=l(()=>{"use strict";kc=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},Nc=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},qc=$c(Dc),pt=class{worktreesRoot;constructor(t){this.worktreesRoot=t,xr(this.worktreesRoot,{recursive:!0})}async createWorktree(t,e){let n=e.worktreePath??Yo(this.worktreesRoot,t);return xr(Yo(n,".."),{recursive:!0}),await this.git(e.repoPath,["worktree","add","-b",e.branchName,n,e.baseBranch]),{worktreePath:n,branch:e.branchName}}async checkout(t,e){await this.git(t,["checkout",e.branch])}async createBranch(t,e){e.baseBranch?await this.git(t,["checkout","-b",e.branchName,e.baseBranch]):await this.git(t,["checkout","-b",e.branchName])}async commit(t,e){return e.addAll!==!1&&await this.git(t,["add","-A"]),await this.git(t,["commit","-m",e.message]),{sha:(await this.git(t,["rev-parse","HEAD"])).stdout.trim()}}async push(t,e={}){let n=e.remote??"origin";e.branch?await this.git(t,["push",n,e.branch]):await this.git(t,["push",n,"HEAD"])}async git(t,e){try{let n=await qc("git",e,{cwd:t,encoding:"utf8",windowsHide:!0});return{stdout:n.stdout??"",stderr:n.stderr??""}}catch(n){let i=n,r=Er(i.stderr),s=Er(i.stdout),a=r||s||i.message||"unknown git error";throw new Error(`git ${e.join(" ")} failed (cwd=${t}, code=${String(i.code??"?")}): ${a}`)}}};pt=kc([Cc(),Nc("design:paramtypes",[String])],pt)});import{Module as Bc}from"@nestjs/common";import{mkdirSync as Jc}from"node:fs";import{dirname as Fc,join as Uc}from"node:path";import{fileURLToPath as Mc}from"node:url";var Lc,Tr,Ze,Or=l(()=>{"use strict";Qo();Lc=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},Tr=Uc(Fc(Mc(import.meta.url)),"../../data");Jc(Tr,{recursive:!0});Ze=class{};Ze=Lc([Bc({providers:[{provide:pt,useFactory:()=>new pt(vr(Tr))}],exports:[pt]})],Ze)});var Ct,g,b,Dt,Y=l(()=>{"use strict";Ct=class extends Error{constructor(t){super(t),this.name=this.constructor.name}},g=class extends Ct{httpStatus=404},b=class extends Ct{httpStatus=400},Dt=class extends Ct{httpStatus=409}});function to(o,t){return o.replace(/\{\{\s*([^}]+?)\s*\}\}/g,(e,n)=>{let i=Vc(t,n.trim());return i==null?"":typeof i=="string"?i:JSON.stringify(i)})}function Vc(o,t){let e=t.split(".").filter(Boolean),n=o;for(let i of e){if(n==null||typeof n!="object")return;n=n[i]}return n}function pe(o,t){return typeof o=="string"?to(o,t):Array.isArray(o)?o.map(e=>pe(e,t)):o&&typeof o=="object"?Object.fromEntries(Object.entries(o).map(([e,n])=>[e,pe(n,t)])):o}var Rr=l(()=>{"use strict"});function Pr(o,t){switch(o){case"questionnaire":return Zo(t);case"confirmation":return Kc(t);case"conversation":return Xc(t);default:return o}}function Zo(o){if(typeof o=="string"&&o.trim())return[o.trim()];if(!o||typeof o!="object")return[];let t=o.questions;return Array.isArray(t)?t.map(e=>typeof e=="string"?e.trim():e&&typeof e=="object"&&"prompt"in e?String(e.prompt).trim():"").filter(Boolean):[]}function Kc(o){if(typeof o=="string"&&o.trim())return[o.trim()];if(!o||typeof o!="object")return[];let t=o;for(let e of["prompt","message","summary","question"]){let n=t[e];if(typeof n=="string"&&n.trim())return[n.trim()]}return"approved"in t&&!("questions"in t)?[]:Zo(o)}function Xc(o){if(typeof o=="string"&&o.trim())return[o.trim()];if(!o||typeof o!="object")return[];let t=o;for(let e of["prompt","message","text"]){let n=t[e];if(typeof n=="string"&&n.trim())return[n.trim()]}return"suggestions"in t?[]:"questions"in t?Zo(o):[]}var Ar=l(()=>{"use strict"});function Kt(o,t){for(let e of o){if(e.id===t)return e;if(e.iterations)for(let n of e.iterations){let i=Kt(n.stepExecutions,t);if(i)return i}}}function le(o,t,e,n){for(let i=0;i<o.length;i++){let r=o[i];if(r.id===t)return{execution:r,siblings:o,index:i,parentLoopExecutionId:e,iterationIndex:n};if(r.iterations)for(let s of r.iterations){let a=le(s.stepExecutions,t,r.id,s.index);if(a)return a}}}function $(o,t,e){return o.map(n=>n.id===t?e(n):n.iterations?{...n,iterations:n.iterations.map(i=>({...i,stepExecutions:$(i.stepExecutions,t,e)}))}:n)}function tn(o,t,e,n){return e==null?[...o,t]:o.map(i=>{if(i.id===e){let r=[...i.iterations??[]],s=r.find(a=>a.index===n);if(s){let a={...s,stepExecutions:[...s.stepExecutions,t]},u=r.findIndex(c=>c.index===n);r[u]=a}else{let a={index:n,stepExecutions:[t],startedAt:t.startedAt??new Date().toISOString()};r.push(a),r.sort((u,c)=>u.index-c.index)}return{...i,iterations:r}}return i.iterations?{...i,iterations:i.iterations.map(r=>({...r,stepExecutions:tn(r.stepExecutions,t,e,n)}))}:i})}function fe(o,t){for(let e of o){if(e.id===t)return e;if(e.type==="loop"){let n=fe(e.steps,t);if(n)return n}}}function kr(o,t,e){return $(o,t,n=>{let i=(n.iterations??[]).map(r=>{if(r.index!==e)return r;let s=r.stepExecutions.every(a=>a.completedAt)?r.stepExecutions.map(a=>a.completedAt).reduce((a,u)=>a>u?a:u):void 0;return{...r,...s?{completedAt:s}:{}}});return{...n,iterations:i}})}var Nr=l(()=>{"use strict"});import{z as F}from"zod";function Cr(o,t){let e=Yc[o].safeParse(t);if(!e.success){let n=e.error.issues.map(i=>`${i.path.length?i.path.join("."):"(root)"}: ${i.message}`).join("; ");throw new Error(`Agent output failed validation for format '${o}': ${n}`)}return e.data}var Hc,Wc,Gc,zc,Yc,Dr=l(()=>{"use strict";Hc=F.object({questions:F.array(F.object({id:F.string(),prompt:F.string()}))}),Wc=F.object({approved:F.boolean()}),Gc=F.object({suggestions:F.array(F.object({body:F.string()}))}),zc=F.string(),Yc={questionnaire:Hc,confirmation:Wc,comment_suggestions:Gc,free_text:zc}});function $r(o){return o==="completed"||o==="failed"||o==="cancelled"}function en(o,t){let e=new Map;for(let i of o){let r=t(i);if(r==null)continue;let s=e.get(r)??[];s.push(i),e.set(r,s)}if(e.size===0)return null;let n=[];for(let i of e.values()){let r=new Set(i.map(a=>a.retryOf).filter(a=>a!=null)),s=i.find(a=>!r.has(a.id));if(!s)return null;n.push(s)}return{activeJobs:n,allTerminal:n.every(i=>$r(i.status)),groupCount:e.size}}function qr(o){let t=o.every(n=>n.status==="completed"),e=o.every(n=>n.status==="failed"||n.status==="cancelled");return t?"completed":e?"failed":"completed_with_issues"}var Lr=l(()=>{"use strict"});async function eo(o,t,e){let n=await t.get(o);if(!n)throw new g(`SubjectView not found: ${o}`);if(n.subjectType==="ticket")return(await e.tickets.query(n.query)).map(r=>({subjectType:"ticket",...r}));if(n.subjectType==="pull_request")return(await e.repo.query(n.query)).map(r=>({subjectType:"pull_request",...r}));if(n.subjectType==="documentation")return(await e.documentation.query(n.query)).map(r=>({subjectType:"documentation",...r}));throw new b(`Unsupported subjectType on view: ${n.subjectType}`)}var on=l(()=>{"use strict";Y()});import{Inject as M,Injectable as tu}from"@nestjs/common";import{randomUUID as nn}from"node:crypto";import{exec as eu}from"node:child_process";import{promisify as ou}from"node:util";function Br(o,t){let e=t[o.stepId];if(e==null||typeof e!="object")return o.type==="field_empty";let n=e[o.field];return o.type==="field_empty"?n==null?!0:typeof n=="string"||Array.isArray(n)?n.length===0:!1:n===o.value}function iu(o,t){let e=i=>{let r=[];for(let s of i)r.push(s),s.type==="loop"&&r.push(...e(s.steps));return r},n=i=>{let r=i.findIndex(s=>s.id===t);if(r>=0){for(let s=r-1;s>=0;s--)if(i[s].type==="agent")return i[s].id;return}for(let s of i)if(s.type==="loop"){let a=n(s.steps);if(a!==void 0||s.steps.some(u=>u.id===t))return a}};return n(o.steps)}function oo(o){let t={...o.context};return o.subjectContext?.mode==="single"&&(t.subject=o.subjectContext.subject),o.worktreePath&&(t.worktreePath=o.worktreePath),o.branch&&(t.branch=o.branch),t}function no(o){if(!o.worktreePath)throw new Error(`Job ${o.id} has no worktreePath; run create_worktree first`);return o.worktreePath}function st(o,t){let e=o[t];if(typeof e!="string"||e.length===0)throw new Error(`Missing required string param '${t}'`);return e}function su(o){if(o==="none")throw new Error("normalizeAppliesTo called with none");if(Array.isArray(o)){if(o.length!==1)throw new Error(`Workflow Runner requires appliesTo to be a single SubjectType (got ${JSON.stringify(o)})`);return o[0]}return o}function Jr(o,t){for(let e of o)if(e.required&&(t[e.name]===void 0||t[e.name]===null))throw new b(`Missing required input: ${e.name}`)}var Qc,Zc,U,nu,ru,Q,ro=l(()=>{"use strict";Be();Ut();Fe();Je();Ye();Oo();Ie();Ee();Te();No();Co();Qo();Y();Rr();Ar();Nr();Dr();Lr();on();Qc=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},Zc=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},U=function(o,t){return function(e,n){t(e,n,o)}},nu=ou(eu),ru=["user","organization","project"],Q=class{workflows;jobs;batches;views;events;tickets;repo;documentation;agent;notifications;knowledge;git;childTerminalLocks=new Set;batchTerminalLocks=new Set;constructor(t,e,n,i,r,s,a,u,c,f,m,y){this.workflows=t,this.jobs=e,this.batches=n,this.views=i,this.events=r,this.tickets=s,this.repo=a,this.documentation=u,this.agent=c,this.notifications=f,this.knowledge=m,this.git=y,this.events.subscribe(h=>{let I=h;(I.type==="job_completed"||I.type==="job_failed")&&this.onChildTerminal(I.jobId)})}async start(t){let e=await this.createJob(t);return this.emit({type:"job_started",jobId:e.id,timestamp:new Date().toISOString()}),this.runJob(e.id)}async launch(t){let e=await this.requireWorkflow(t.workflowId);if(e.cardinality==="single")throw new b("launch() does not support cardinality 'single'; use start() with a subjectId");if(e.cardinality!=="batch"&&e.cardinality!=="aggregate")throw new b(`Unsupported cardinality: ${e.cardinality}`);Jr(e.inputSchema,t.inputValues);let n=await this.resolveSelection(t.selection);if(e.cardinality==="aggregate"){let a=await this.createJob({workflowId:e.id,subjectContext:{mode:"collection",subjects:n},selection:t.selection,inputValues:t.inputValues});return this.emit({type:"job_started",jobId:a.id,timestamp:new Date().toISOString()}),this.runJob(a.id)}let i=new Date().toISOString(),r=await this.batches.create({id:nn(),workflowId:e.id,selection:t.selection,resolvedSubjects:n,status:"running",triggeredBy:t.triggeredBy,...t.notificationOverride?{notificationOverride:t.notificationOverride}:{},notificationSent:!1,createdAt:i}),s=[];for(let a=0;a<n.length;a++){let u=n[a],c=await this.createJob({workflowId:e.id,subjectContext:{mode:"single",subject:u},selection:t.selection,batchId:r.id,fanOutIndex:a,inputValues:t.inputValues});s.push(c)}for(let a of s)this.emit({type:"job_started",jobId:a.id,timestamp:new Date().toISOString()}),await this.runJob(a.id);return await this.batches.get(r.id)}async createJob(t){let e=await this.workflows.get(t.workflowId);if(!e)throw new g(`Workflow not found: ${t.workflowId}`);if(!t.subjectContext&&e.cardinality!=="single")throw new b(`Workflow Runner only supports cardinality 'single' at start() without an explicit subjectContext (got '${e.cardinality}')`);Jr(e.inputSchema,t.inputValues);let n=t.subjectContext??await this.resolveSubjectContext(e,t.subjectId),i=new Date().toISOString();return this.jobs.create({id:nn(),workflowId:e.id,status:"pending",...n?{subjectContext:n}:{},...t.selection?{selection:t.selection}:{},...t.batchId?{batchId:t.batchId}:{},...t.parentJobId?{parentJobId:t.parentJobId}:{},...t.parentStepExecutionId?{parentStepExecutionId:t.parentStepExecutionId}:{},...t.fanOutIndex!=null?{fanOutIndex:t.fanOutIndex}:{},...t.retryOf?{retryOf:t.retryOf}:{},context:{...t.inputValues},stepHistory:[],createdAt:i,updatedAt:i})}async runJob(t){let e=await this.jobs.get(t);if(!e)throw new g(`Job not found: ${t}`);let n=await this.requireWorkflow(e.workflowId);e.status==="pending"&&(e=await this.persistJob({...e,status:"planning",updatedAt:new Date().toISOString()}));let i=await this.executeStepSequence(e,n,n.steps,void 0,void 0,0);return i.outcome==="paused"||i.outcome==="failed"?i.job:this.completeJob(i.job,n)}async resume(t,e){let n=await this.jobs.get(t);if(!n)throw new g(`Job not found: ${t}`);if(n.status!=="waiting_for_human")throw new Dt(`Job ${t} is not waiting for human input (status: ${n.status})`);let i=await this.requireWorkflow(n.workflowId),r=n.currentStepExecutionId;if(!r)throw new Error(`Job ${t} is waiting_for_human but has no currentStepExecutionId`);let s=Kt(n.stepHistory,r);if(!s)throw new Error(`Paused execution ${r} not found on job ${t}`);if(s.type==="loop")return this.resumeAskHuman(n,i,s,e);if(s.type!=="interaction")throw new Error(`Paused execution ${r} has type '${s.type}'; expected interaction or loop`);let a=new Date().toISOString(),u=$(n.stepHistory,r,I=>({...I,status:"completed",completedAt:a,output:e})),c=e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{response:e};n=await this.persistJob({...n,status:"planning",context:{...n.context,[s.stepDefinitionId]:e},stepHistory:u,currentStepId:void 0,currentStepExecutionId:void 0,updatedAt:a}),this.emit({type:"human_answered",jobId:n.id,answers:c,timestamp:a});let f=le(n.stepHistory,r);if(!f)throw new Error(`Could not locate frame for execution ${r}`);let m=this.sequenceForFrameOnJob(n,i,f),y=f.index+1,h=await this.executeStepSequence(n,i,m,f.parentLoopExecutionId,f.iterationIndex,y);return h.outcome==="paused"||h.outcome==="failed"?h.job:f.parentLoopExecutionId!=null&&f.iterationIndex!=null?this.continueLoopAfterBody(h.job,i,f.parentLoopExecutionId,f.iterationIndex):this.completeJob(h.job,i)}async retryFailedJob(t){let e=await this.jobs.get(t);if(!e)throw new g(`Job not found: ${t}`);if(e.status!=="failed")throw new Dt(`Job ${t} is not failed (status: ${e.status})`);let n=e.parentJobId!=null&&e.parentStepExecutionId!=null&&e.fanOutIndex!=null,i=e.batchId!=null&&e.fanOutIndex!=null;if(!n&&!i)throw new b(`Job ${t} is not a retryable sub_workflow child or batch member`);if(n){let a=await this.jobs.get(e.parentJobId);if(!a)throw new g(`Parent job not found: ${e.parentJobId}`);let u=await this.createJob({workflowId:e.workflowId,subjectContext:e.subjectContext,inputValues:{},parentJobId:e.parentJobId,parentStepExecutionId:e.parentStepExecutionId,fanOutIndex:e.fanOutIndex,retryOf:e.id}),c=$(a.stepHistory,e.parentStepExecutionId,f=>({...f,status:"waiting_for_children",error:void 0,completedAt:void 0,childJobIds:[...f.childJobIds??[],u.id]}));return a=await this.persistJob({...a,status:"waiting_for_children",stepHistory:c,completedAt:void 0,updatedAt:new Date().toISOString()}),this.emit({type:"job_started",jobId:u.id,timestamp:new Date().toISOString()}),this.emit({type:"job_retried",jobId:u.id,retryOf:e.id,timestamp:new Date().toISOString()}),this.runJob(u.id),u}let r=await this.batches.get(e.batchId);if(!r)throw new g(`JobBatch not found: ${e.batchId}`);r.status!=="running"&&await this.batches.update(r.id,{status:"running",completedAt:null,notificationSent:!1});let s=await this.createJob({workflowId:e.workflowId,subjectContext:e.subjectContext,selection:e.selection,batchId:e.batchId,fanOutIndex:e.fanOutIndex,inputValues:{},retryOf:e.id});return this.emit({type:"job_started",jobId:s.id,timestamp:new Date().toISOString()}),this.emit({type:"job_retried",jobId:s.id,retryOf:e.id,timestamp:new Date().toISOString()}),this.runJob(s.id),s}async executeStepSequence(t,e,n,i,r,s){let a=t;for(let u=s;u<n.length;u++){let c=n[u],f=new Date().toISOString(),m={id:nn(),stepDefinitionId:c.id,type:c.type,status:"running",startedAt:f},y=tn(a.stepHistory,m,i,r);a=await this.persistJob({...a,status:a.status==="pending"?"planning":a.status,currentStepId:c.id,currentStepExecutionId:m.id,stepHistory:y,updatedAt:f}),this.emit({type:"step_started",jobId:a.id,stepDefinitionId:c.id,timestamp:f});try{let h=await this.dispatchStep(a,e,c,m.id,i,r);if(a=h.job,h.outcome==="paused"||h.outcome==="failed")return h}catch(h){return{outcome:"failed",job:await this.failJob(a,e,m.id,c.id,h)}}}return i!=null&&r!=null&&(a=await this.persistJob({...a,stepHistory:kr(a.stepHistory,i,r),updatedAt:new Date().toISOString()})),{outcome:"completed",job:a}}async dispatchStep(t,e,n,i,r,s){switch(n.type){case"agent":return{outcome:"completed",job:await this.executeAgentStep(t,n,i)};case"interaction":return{outcome:"paused",job:await this.pauseForInteraction(t,e,n,i)};case"git":return{outcome:"completed",job:await this.executeGitStep(t,n,i)};case"provider_action":return{outcome:"completed",job:await this.executeProviderActionStep(t,n,i)};case"shell":return{outcome:"completed",job:await this.executeShellStep(t,n,i)};case"loop":return this.runLoopStep(t,e,n,i,r,s);case"sub_workflow":return this.runSubWorkflowStep(t,n,i);default:{let a=n;throw new b(`Step type '${a.type}' not yet supported by the Workflow Runner`)}}}async runLoopStep(t,e,n,i,r,s,a=0,u=n.maxIterations){let c=t,f=a;for(;;){if(f>=u)switch(n.onMaxIterations.action){case"fail":return c=await this.failExecution(c,e,i,n.id,`Loop '${n.id}' exceeded maxIterations (${u})`),{outcome:"failed",job:c};case"continue":return c=await this.finishExecution(c,i,n.id,{iterations:f,exitedOnMaxIterations:!0}),{outcome:"completed",job:c};case"ask_human":{let y={maxIterationsCheckpoint:!0,nextIteration:f,effectiveMaxIterations:u},h=new Date().toISOString(),I=$(c.stepHistory,i,E=>({...E,status:"pending",output:y}));return c=await this.persistJob({...c,status:"waiting_for_human",currentStepId:n.id,currentStepExecutionId:i,stepHistory:I,updatedAt:h}),this.emit({type:"waiting_for_human",jobId:c.id,stepDefinitionId:n.id,interaction:"confirmation",data:y,questions:[`Loop '${n.id}' reached maxIterations (${u}). Extend, continue, or cancel?`],timestamp:h}),e.notificationPolicy.triggers.includes("on_needs_input")&&await this.notifications.send({title:`Input needed: ${e.name}`,body:`Job ${c.id} hit max iterations on loop '${n.id}'`,jobId:c.id}),{outcome:"paused",job:c}}default:{let y=n.onMaxIterations;throw new Error(`Unknown onMaxIterations action: ${JSON.stringify(y)}`)}}let m=await this.executeStepSequence(c,e,n.steps,i,f,0);if(c=m.job,m.outcome==="paused")return m;if(m.outcome==="failed")return c=await this.failExecution(c,e,i,n.id,"Loop body failed"),{outcome:"failed",job:c};if(Br(n.until,c.context))return c=await this.finishExecution(c,i,n.id,{iterations:f+1}),{outcome:"completed",job:c};f+=1}}async resumeAskHuman(t,e,n,i){let r=i,s=n.output;if(!s?.maxIterationsCheckpoint)throw new Error(`Loop execution ${n.id} is not at an ask_human checkpoint`);let a=fe(e.steps,n.stepDefinitionId);if(!a||a.type!=="loop")throw new Error(`Loop step definition '${n.stepDefinitionId}' not found`);let u=le(t.stepHistory,n.id),c=new Date().toISOString();if(r.action==="cancel")return await this.failExecution({...t,status:"planning",currentStepId:void 0,currentStepExecutionId:void 0,updatedAt:c},e,n.id,a.id,"Loop cancelled by human at maxIterations checkpoint");if(r.action==="continue"){let I=await this.persistJob({...t,status:"planning",currentStepId:void 0,currentStepExecutionId:void 0,stepHistory:$(t.stepHistory,n.id,E=>({...E,status:"completed",completedAt:c,output:{iterations:s.nextIteration,exitedOnMaxIterations:!0,humanAction:"continue"}})),updatedAt:c});return this.emit({type:"human_answered",jobId:I.id,answers:r,timestamp:c}),this.emit({type:"step_completed",jobId:I.id,stepDefinitionId:a.id,timestamp:c}),u?.parentLoopExecutionId!=null&&u.iterationIndex!=null?this.continueLoopAfterBody(I,e,u.parentLoopExecutionId,u.iterationIndex):this.continueTopLevelAfter(I,e,a.id)}let f=typeof r.additionalIterations=="number"?r.additionalIterations:0,m=s.effectiveMaxIterations+f,y=await this.persistJob({...t,status:"planning",currentStepId:void 0,currentStepExecutionId:void 0,stepHistory:$(t.stepHistory,n.id,I=>({...I,status:"running",output:void 0})),updatedAt:c});this.emit({type:"human_answered",jobId:y.id,answers:r,timestamp:c});let h=await this.runLoopStep(y,e,a,n.id,u?.parentLoopExecutionId,u?.iterationIndex,s.nextIteration,m);return h.outcome==="paused"||h.outcome==="failed"?h.job:u?.parentLoopExecutionId!=null&&u.iterationIndex!=null?this.continueLoopAfterBody(h.job,e,u.parentLoopExecutionId,u.iterationIndex):this.continueTopLevelAfter(h.job,e,a.id)}async continueLoopAfterBody(t,e,n,i){let r=Kt(t.stepHistory,n);if(!r)throw new Error(`Loop execution ${n} not found`);let s=fe(e.steps,r.stepDefinitionId);if(!s||s.type!=="loop")throw new Error(`Loop step '${r.stepDefinitionId}' not found`);let a=le(t.stepHistory,n),u=r.output?.effectiveMaxIterations??s.maxIterations,c=t;if(Br(s.until,c.context))c=await this.finishExecution(c,n,s.id,{iterations:i+1});else{let f=i+1,m=await this.runLoopStep(c,e,s,n,a?.parentLoopExecutionId,a?.iterationIndex,f,u);if(m.outcome==="paused"||m.outcome==="failed")return m.job;c=m.job}return a?.parentLoopExecutionId!=null&&a.iterationIndex!=null?this.continueLoopAfterBody(c,e,a.parentLoopExecutionId,a.iterationIndex):this.continueTopLevelAfter(c,e,s.id)}async continueTopLevelAfter(t,e,n){let i=e.steps.findIndex(s=>s.id===n),r=await this.executeStepSequence(t,e,e.steps,void 0,void 0,i+1);return r.outcome==="paused"||r.outcome==="failed"?r.job:this.completeJob(r.job,e)}sequenceForFrameOnJob(t,e,n){if(n.parentLoopExecutionId==null)return e.steps;let i=Kt(t.stepHistory,n.parentLoopExecutionId);if(!i)throw new Error(`Parent loop execution ${n.parentLoopExecutionId} not found`);let r=fe(e.steps,i.stepDefinitionId);if(!r||r.type!=="loop")throw new Error(`Parent loop step '${i.stepDefinitionId}' not found`);return r.steps}async runSubWorkflowStep(t,e,n){if(!t.subjectContext||t.subjectContext.mode!=="collection")throw new b(`sub_workflow steps require subjectContext.mode === 'collection' (job ${t.id})`);let i=t.subjectContext.subjects,r=[];for(let f=0;f<i.length;f++){let m=i[f],y=await this.createJob({workflowId:e.workflowId,subjectContext:{mode:"single",subject:m},inputValues:{},parentJobId:t.id,parentStepExecutionId:n,fanOutIndex:f});r.push(y)}let s=r.map(f=>f.id),a=new Date().toISOString(),u=$(t.stepHistory,n,f=>({...f,status:"waiting_for_children",childJobIds:s})),c=await this.persistJob({...t,status:"waiting_for_children",currentStepId:e.id,currentStepExecutionId:n,stepHistory:u,updatedAt:a});for(let f of r)this.emit({type:"job_started",jobId:f.id,timestamp:a}),this.runJob(f.id);return{outcome:"paused",job:c}}async onChildTerminal(t){let e=await this.jobs.get(t);if(!e?.parentJobId||!e.parentStepExecutionId)return;let n=`${e.parentJobId}:${e.parentStepExecutionId}`;if(!this.childTerminalLocks.has(n)){this.childTerminalLocks.add(n);try{let i=(await this.jobs.list({parentJobId:e.parentJobId,parentStepExecutionId:e.parentStepExecutionId})).filter(E=>E.parentStepExecutionId===e.parentStepExecutionId),r=en(i,E=>E.fanOutIndex);if(!r?.allTerminal)return;let{activeJobs:s}=r,a=await this.jobs.get(e.parentJobId);if(!a||a.status!=="waiting_for_children"&&a.status!=="failed")return;let u=await this.requireWorkflow(a.workflowId),c=e.parentStepExecutionId,f=Kt(a.stepHistory,c);if(!f||f.type!=="sub_workflow")return;if(s.some(E=>E.status==="failed")){await this.failExecution(a,u,c,f.stepDefinitionId,"One or more child jobs failed");return}let y=s.slice().sort((E,hs)=>(E.fanOutIndex??0)-(hs.fanOutIndex??0)).map(E=>({fanOutIndex:E.fanOutIndex,jobId:E.id,output:E.context})),h=new Date().toISOString();a=await this.persistJob({...a,status:"planning",context:{...a.context,[f.stepDefinitionId]:y},currentStepId:void 0,currentStepExecutionId:void 0,stepHistory:$(a.stepHistory,c,E=>({...E,status:"completed",completedAt:h,output:y})),completedAt:void 0,updatedAt:h}),this.emit({type:"step_completed",jobId:a.id,stepDefinitionId:f.stepDefinitionId,timestamp:h});let I=await this.continueTopLevelAfter(a,u,f.stepDefinitionId)}finally{this.childTerminalLocks.delete(n)}}}async onBatchMemberTerminal(t){let e=await this.jobs.get(t);if(!e?.batchId)return;let n=e.batchId;if(!this.batchTerminalLocks.has(n)){this.batchTerminalLocks.add(n);try{let i=await this.batches.get(e.batchId);if(!i||i.status!=="running")return;let r=await this.jobs.list({batchId:i.id}),s=en(r,m=>m.fanOutIndex);if(!s||s.groupCount!==i.resolvedSubjects.length||!s.allTerminal)return;let{activeJobs:a}=s,u=qr(a),c=new Date().toISOString(),f=await this.batches.update(i.id,{status:u,completedAt:c});if(!f)return;if(this.emit({type:"batch_completed",batchId:f.id,summary:a.map(m=>({jobId:m.id,status:m.status})),timestamp:c}),!f.notificationSent){let m=await this.requireWorkflow(f.workflowId),y=f.notificationOverride??m.notificationPolicy,h=u==="completed"?"on_complete":"on_fail";y.triggers.includes(h)&&await this.notifications.send({title:`Batch ${u}: ${m.name}`,body:`JobBatch ${f.id} finished with status '${u}' (${a.length} members)`,batchId:f.id}),await this.batches.update(f.id,{notificationSent:!0})}}finally{this.batchTerminalLocks.delete(n)}}}async resolveSelection(t){if(t.mode==="view")return eo(t.viewId,this.views,{tickets:this.tickets,repo:this.repo,documentation:this.documentation});let e=[];for(let n of t.subjectIds)if(t.subjectType==="ticket"){let i=await this.tickets.get(n);e.push({subjectType:"ticket",...i})}else if(t.subjectType==="pull_request"){let i=await this.repo.get(n);e.push({subjectType:"pull_request",...i})}else if(t.subjectType==="documentation"){let i=await this.documentation.get(n);e.push({subjectType:"documentation",...i})}else throw new b(`Unsupported subjectType: ${t.subjectType}`);return e}async executeAgentStep(t,e,n){let i=e.knowledgeScope?.length?e.knowledgeScope:ru,r=await this.resolveKnowledge(i),s=oo(t),a=to(e.objective,s),u=await this.agent.run({objective:a,outputFormat:e.outputFormat,knowledge:r,context:{...s,stepId:e.id},...t.worktreePath?{cwd:t.worktreePath}:{}}),c=Cr(e.outputFormat,u.parsed);return this.finishExecution(t,n,e.id,c)}async executeGitStep(t,e,n){let i=pe(e.params,oo(t));switch(e.operation){case"create_worktree":{let r=await this.git.createWorktree(t.id,{repoPath:st(i,"repoPath"),baseBranch:st(i,"baseBranch"),branchName:st(i,"branchName"),...typeof i.worktreePath=="string"?{worktreePath:i.worktreePath}:{}});return this.finishExecution(t,n,e.id,r,{worktreePath:r.worktreePath,branch:r.branch})}case"create_branch":{let r=no(t),s=st(i,"branchName");return await this.git.createBranch(r,{branchName:s,...typeof i.baseBranch=="string"?{baseBranch:i.baseBranch}:{}}),this.finishExecution(t,n,e.id,{branch:s},{branch:s})}case"checkout":{let r=no(t),s=st(i,"branch");return await this.git.checkout(r,{branch:s}),this.finishExecution(t,n,e.id,{branch:s},{branch:s})}case"commit":{let r=no(t),s=await this.git.commit(r,{message:st(i,"message"),addAll:i.addAll!==!1});return this.finishExecution(t,n,e.id,s)}case"push":{let r=no(t);return await this.git.push(r,{...typeof i.remote=="string"?{remote:i.remote}:{},...typeof i.branch=="string"?{branch:i.branch}:{}}),this.finishExecution(t,n,e.id,{remote:typeof i.remote=="string"?i.remote:"origin",branch:typeof i.branch=="string"?i.branch:t.branch})}default:{let r=e.operation;throw new Error(`Unknown git operation: ${r}`)}}}async executeProviderActionStep(t,e,n){if(!t.subjectContext||t.subjectContext.mode!=="single")throw new b(`provider_action steps require subjectContext.mode === 'single' (job ${t.id})`);let i=t.subjectContext.subject,r=i.id,s=pe(e.params??{},oo(t))??{},a;if(i.subjectType==="documentation")switch(e.action){case"get_subject":a=await this.documentation.get(r);break;case"get_content":a=await this.documentation.getContent(r);break;case"get_comments":a=await this.documentation.getComments(r);break;case"post_comment":await this.documentation.postComment(r,st(s,"body")),a={posted:!0};break;case"update_status":throw new Error(`Provider action '${e.action}' is not valid for subject type 'documentation'`);default:{let u=e.action;throw new Error(`Unknown provider action: ${u}`)}}else{let u=i.subjectType==="ticket"?this.tickets:i.subjectType==="pull_request"?this.repo:null;if(!u)throw new Error(`Unsupported subjectType for provider_action: ${i.subjectType}`);switch(e.action){case"get_subject":a=await u.get(r);break;case"get_comments":a=await u.getComments(r);break;case"post_comment":await u.postComment(r,st(s,"body")),a={posted:!0};break;case"update_status":await u.updateStatus(r,st(s,"status")),a={status:st(s,"status")};break;case"get_content":throw new Error(`Provider action 'get_content' is not valid for subject type '${i.subjectType}'`);default:{let c=e.action;throw new Error(`Unknown provider action: ${c}`)}}}return this.finishExecution(t,n,e.id,a)}async executeShellStep(t,e,n){let i=to(e.command,oo(t)),r=t.worktreePath??process.cwd();try{let s=await nu(i,{cwd:r,windowsHide:!0});return this.finishExecution(t,n,e.id,{exitCode:0,stdout:String(s.stdout??""),stderr:String(s.stderr??"")})}catch(s){let a=s,u=a.stderr??"",c=a.stdout??"",f=typeof a.code=="number"?a.code:Number.parseInt(String(a.code??"1"),10)||1;throw new Error(`shell command failed (exit ${f}, cwd=${r}): ${u||c||a.message||i}`)}}async pauseForInteraction(t,e,n,i){let r=new Date().toISOString(),s=iu(e,n.id),a=s!=null?t.context[s]:void 0,u=$(t.stepHistory,i,y=>({...y,status:"pending"})),c=await this.persistJob({...t,status:"waiting_for_human",currentStepId:n.id,currentStepExecutionId:i,stepHistory:u,updatedAt:r}),f=Pr(n.interaction,a);return this.emit({type:"waiting_for_human",jobId:c.id,stepDefinitionId:n.id,interaction:n.interaction,data:a,questions:f,timestamp:r}),e.notificationPolicy.triggers.includes("on_needs_input")&&n.notify!==!1&&await this.notifications.send({title:`Input needed: ${e.name}`,body:`Job ${c.id} is waiting for human input on step '${n.id}'`,jobId:c.id}),c}async finishExecution(t,e,n,i,r={}){let s=new Date().toISOString(),a=$(t.stepHistory,e,c=>({...c,status:"completed",completedAt:s,output:i})),u=await this.persistJob({...t,...r,context:{...t.context,[n]:i},stepHistory:a,updatedAt:s});return this.emit({type:"step_completed",jobId:u.id,stepDefinitionId:n,timestamp:s}),u}async failExecution(t,e,n,i,r){return this.failJob(t,e,n,i,new Error(r))}async completeJob(t,e){let n=new Date().toISOString(),i=await this.persistJob({...t,status:"completed",currentStepId:void 0,currentStepExecutionId:void 0,completedAt:n,updatedAt:n});return this.emit({type:"job_completed",jobId:i.id,timestamp:n}),await this.onBatchMemberTerminal(i.id),!i.batchId&&e.notificationPolicy.triggers.includes("on_complete")&&await this.notifications.send({title:`Job completed: ${e.name}`,body:`Job ${i.id} completed successfully`,jobId:i.id}),i}async failJob(t,e,n,i,r){let s=r instanceof Error?r.message:String(r),a=new Date().toISOString(),u=$(t.stepHistory,n,f=>({...f,status:"failed",completedAt:a,error:s})),c=await this.persistJob({...t,status:"failed",stepHistory:u,completedAt:a,updatedAt:a});return this.emit({type:"step_failed",jobId:c.id,stepDefinitionId:i,error:s,timestamp:a}),this.emit({type:"job_failed",jobId:c.id,error:s,timestamp:a}),await this.onBatchMemberTerminal(c.id),!c.batchId&&e.notificationPolicy.triggers.includes("on_fail")&&await this.notifications.send({title:`Job failed: ${e.name}`,body:`Job ${c.id} failed on step '${i}': ${s}`,jobId:c.id}),c}async resolveSubjectContext(t,e){if(t.appliesTo==="none")return;let n=su(t.appliesTo);if(!e)throw new Error(`Workflow '${t.id}' applies to '${n}' but no subjectId was provided`);if(n==="ticket")return{mode:"single",subject:{subjectType:"ticket",...await this.tickets.get(e)}};if(n==="pull_request")return{mode:"single",subject:{subjectType:"pull_request",...await this.repo.get(e)}};if(n==="documentation")return{mode:"single",subject:{subjectType:"documentation",...await this.documentation.get(e)}};throw new Error(`Unsupported subjectType for workflow subject resolution: ${n}`)}async resolveKnowledge(t){let e=[];for(let n of t)e.push(...await this.knowledge.resolve(n));return e}async requireWorkflow(t){let e=await this.workflows.get(t);if(!e)throw new g(`Workflow not found: ${t}`);return e}async persistJob(t){let e=await this.jobs.update(t.id,{status:t.status,context:t.context,currentStepId:t.currentStepId,currentStepExecutionId:t.currentStepExecutionId,stepHistory:t.stepHistory,worktreePath:t.worktreePath,branch:t.branch,updatedAt:t.updatedAt,completedAt:t.completedAt});if(!e)throw new Error(`Failed to persist job ${t.id}`);return e}emit(t){this.events.emit(t)}};Q=Qc([tu(),U(0,M(L)),U(1,M(x)),U(2,M(J)),U(3,M(B)),U(4,M(z)),U(5,M(Pt)),U(6,M(At)),U(7,M(kt)),U(8,M(ee)),U(9,M(re)),U(10,M(ie)),U(11,M(pt)),Zc("design:paramtypes",[L,x,J,B,z,Object,Object,Object,Object,Object,Object,pt])],Q)});import{Module as cu}from"@nestjs/common";var au,Xt,rn=l(()=>{"use strict";de();Ge();Qe();Or();ro();au=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},Xt=class{};Xt=au([cu({imports:[it,jt,It,Ze],providers:[Q],exports:[Q]})],Xt)});import{Catch as du}from"@nestjs/common";var uu,io,Fr=l(()=>{"use strict";Y();uu=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},io=class{catch(t,e){e.switchToHttp().getResponse().status(t.httpStatus).json({error:t.message})}};io=uu([du(Ct)],io)});import{z as V}from"zod";var at,Ht,so,ao,sn=l(()=>{"use strict";at=V.enum(["ticket","pull_request","documentation"]),Ht=V.object({id:V.string().min(1),name:V.string().min(1),subjectType:at,query:V.record(V.string(),V.unknown()),description:V.string().optional(),order:V.number().int().nonnegative()}),so=Ht.omit({order:!0}),ao=V.object({viewIds:V.array(V.string().min(1)).min(1)})});var Ur=l(()=>{"use strict";sn()});function pu(o){let t=o.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"");return t.length>0?t:"step"}function Mr(o,t){let e=pu(o);if(!t.has(e))return e;let n=2;for(;t.has(`${e}-${n}`);)n+=1;return`${e}-${n}`}function Vr(o,t){for(let e of o)e.id&&t.push(e.id),e.type==="loop"&&Array.isArray(e.steps)&&Vr(e.steps,t)}function Kr(o){let t=[];Vr(o,t);let e=new Map;for(let n of t)e.set(n,(e.get(n)??0)+1);return[...e.entries()].filter(([,n])=>n>1).map(([n])=>n)}function Xr(o){let t=new Set,e=n=>{for(let i of n)i.id&&t.add(i.id),i.type==="loop"&&Array.isArray(i.steps)&&e(i.steps)};return e(o),t}var an=l(()=>{"use strict"});import{z as p}from"zod";var lu,me,fu,xt,Hr,Wr,Gr,zr,Yr,Qr,Zr,ti,mu,ei,oi,he,hu,bu,gu,yu,wu,Su,_u,ni,Wt,ri=l(()=>{"use strict";sn();an();lu=p.enum(["on_fail","on_complete","on_needs_input"]),me=p.object({triggers:p.array(lu),messageTemplate:p.string().optional()}),fu=p.object({name:p.string().min(1),label:p.string().min(1),type:p.enum(["string","number","boolean","select"]),options:p.array(p.string()).optional(),required:p.boolean(),defaultValue:p.unknown().optional()}),xt=p.string().min(1),Hr=p.object({type:p.literal("agent"),id:p.string().min(1),name:xt,objective:p.string().min(1),knowledgeScope:p.array(p.enum(["user","organization","project"])).optional(),outputFormat:p.enum(["questionnaire","confirmation","comment_suggestions","free_text"])}),Wr=p.object({type:p.literal("interaction"),id:p.string().min(1),name:xt,interaction:p.union([p.literal("questionnaire"),p.literal("confirmation"),p.literal("conversation")]),notify:p.boolean().optional()}),Gr=p.object({type:p.literal("shell"),id:p.string().min(1),name:xt,command:p.string().min(1)}),zr=p.object({type:p.literal("git"),id:p.string().min(1),name:xt,operation:p.enum(["create_worktree","checkout","create_branch","commit","push"]),params:p.record(p.string(),p.unknown())}),Yr=p.object({type:p.literal("provider_action"),id:p.string().min(1),name:xt,action:p.enum(["get_subject","get_comments","post_comment","update_status","get_content"]),params:p.record(p.string(),p.unknown()).optional()}),Qr=p.object({type:p.literal("sub_workflow"),id:p.string().min(1),name:xt,workflowId:p.string().min(1),forEach:p.literal("selection")}),Zr=p.discriminatedUnion("type",[p.object({type:p.literal("field_empty"),stepId:p.string().min(1),field:p.string().min(1)}),p.object({type:p.literal("field_equals"),stepId:p.string().min(1),field:p.string().min(1),value:p.unknown()})]),ti=p.discriminatedUnion("action",[p.object({action:p.literal("fail")}),p.object({action:p.literal("continue")}),p.object({action:p.literal("ask_human")})]),mu=p.object({type:p.literal("loop"),id:p.string().min(1),name:xt,steps:p.array(p.lazy(()=>ei)),until:Zr,maxIterations:p.number().int().nonnegative(),onMaxIterations:ti}),ei=p.lazy(()=>p.discriminatedUnion("type",[zr,Yr,Gr,Hr,Wr,Qr,mu])),oi=p.object({id:p.string().min(1),name:p.string().min(1),description:p.string().optional(),appliesTo:p.union([at,p.array(at),p.literal("none")]),cardinality:p.enum(["single","batch","aggregate"]),inputSchema:p.array(fu),steps:p.array(ei),notificationPolicy:me}),he=oi.superRefine((o,t)=>{let e=Kr(o.steps);e.length!==0&&t.addIssue({code:"custom",path:["steps"],message:`Duplicate step id(s): ${e.join(", ")}`})}),hu=Hr.extend({id:p.string().min(1).optional()}),bu=Wr.extend({id:p.string().min(1).optional()}),gu=Gr.extend({id:p.string().min(1).optional()}),yu=zr.extend({id:p.string().min(1).optional()}),wu=Yr.extend({id:p.string().min(1).optional()}),Su=Qr.extend({id:p.string().min(1).optional()}),_u=p.object({type:p.literal("loop"),id:p.string().min(1).optional(),name:xt,steps:p.array(p.lazy(()=>ni)),until:Zr,maxIterations:p.number().int().nonnegative(),onMaxIterations:ti}),ni=p.lazy(()=>p.discriminatedUnion("type",[yu,wu,gu,hu,bu,Su,_u])),Wt=oi.omit({id:!0,steps:!0}).extend({id:p.string().min(1).optional(),steps:p.array(ni)})});var ii=l(()=>{"use strict";ri();an()});var si=l(()=>{"use strict"});var ai=l(()=>{"use strict";si()});var ci=l(()=>{"use strict"});var ui=l(()=>{"use strict";ci()});var di=l(()=>{"use strict"});var pi=l(()=>{"use strict";di()});import{z as k}from"zod";var Gt,li=l(()=>{"use strict";Gt=k.object({id:k.string().min(1),workflowId:k.string().min(1),viewId:k.string().min(1),trigger:k.object({type:k.literal("cron"),cadence:k.string().min(1)}),notificationOverride:k.object({triggers:k.array(k.enum(["on_fail","on_complete","on_needs_input"])),messageTemplate:k.string().optional()}).optional(),missedFirePolicy:k.enum(["skip","catch_up"]),enabled:k.boolean(),lastFiredAt:k.string().optional(),createdAt:k.string()})});var fi=l(()=>{"use strict";li()});import{z as K}from"zod";var mi,hi,bi,gi,cn,co,yi=l(()=>{"use strict";mi=K.string().min(1).refine(o=>{try{let t=new URL(o);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}},{message:"Must be an http(s) URL"}).optional(),hi=K.object({ticket:K.enum(["jira","manual"]).optional(),repo:K.enum(["bitbucket","manual"]).optional(),agent:K.enum(["claude","cursor"]).optional()}),bi=K.object({baseUrl:mi,email:K.string().min(1).optional()}),gi=K.object({baseUrl:mi,email:K.string().min(1).optional(),workspace:K.string().min(1).optional()}),cn=K.object({activeProviders:hi.optional(),jira:bi.optional(),bitbucket:gi.optional()}),co=K.object({activeProviders:hi.optional(),jira:bi.partial().optional(),bitbucket:gi.partial().optional()})});var wi=l(()=>{"use strict";yi()});var Si=l(()=>{"use strict"});var _i=l(()=>{"use strict";Si()});var lt=l(()=>{"use strict";Ur();ii();ai();ui();pi();fi();wi();_i()});var j,Et=l(()=>{"use strict";Y();j=class{schema;constructor(t){this.schema=t}transform(t){let e=this.schema.safeParse(t);if(!e.success){let n=e.error.issues.map(i=>`${i.path.join(".")||"(root)"}: ${i.message}`).join("; ");throw new b(`Validation failed: ${n}`)}return e.data}}});import{randomUUID as ju}from"node:crypto";function Iu(){return ju()}function un(o){let t=o.id??Iu(),e=Xr(o.steps),n=ji(o.steps,e);return{...o,id:t,steps:n}}function ji(o,t){return o.map(e=>{let n=e.id;return n||(n=Mr(e.name,t),t.add(n)),e.type==="loop"?{...e,id:n,steps:ji(e.steps,t)}:{...e,id:n}})}var Ii=l(()=>{"use strict";lt()});import{Body as Ei,Controller as xu,Delete as Eu,Get as vi,HttpCode as vu,Inject as xi,Param as dn,Patch as Tu,Post as Ou,Query as Ru}from"@nestjs/common";var zt,T,vt,Pu,ft,Ti=l(()=>{"use strict";lt();Be();Ut();Y();Et();Ii();zt=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},T=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},vt=function(o,t){return function(e,n){t(e,n,o)}},Pu=new Set(["completed","failed","cancelled"]),ft=class{workflows;jobs;constructor(t,e){this.workflows=t,this.jobs=e}async list(t){if(t!=null&&t!==""&&t!=="single"&&t!=="batch"&&t!=="aggregate")throw new b(`Invalid cardinality filter: ${t}`);return this.workflows.list(t?{cardinality:t}:{})}async get(t){let e=await this.workflows.get(t);if(!e)throw new g(`Workflow not found: ${t}`);return e}async create(t){let e=un(t),n=he.safeParse(e);if(!n.success){let i=n.error.issues.map(r=>`${r.path.join(".")||"(root)"}: ${r.message}`).join("; ");throw new b(`Validation failed: ${i}`)}return this.workflows.create(n.data)}async update(t,e){let n=un({...e,id:t}),i=he.safeParse(n);if(!i.success){let u=i.error.issues.map(c=>`${c.path.join(".")||"(root)"}: ${c.message}`).join("; ");throw new b(`Validation failed: ${u}`)}let{id:r,...s}=i.data,a=await this.workflows.update(t,s);if(!a)throw new g(`Workflow not found: ${t}`);return a}async remove(t){if(!await this.workflows.get(t))throw new g(`Workflow not found: ${t}`);let i=(await this.jobs.list({workflowId:t})).filter(s=>!Pu.has(s.status));if(i.length>0){let s=i.length===1?"Job":"Jobs";throw new Dt(`Cannot delete workflow ${t}: ${i.length} non-terminal ${s} still reference it`)}if(!await this.workflows.delete(t))throw new g(`Workflow not found: ${t}`)}};zt([vi(),vt(0,Ru("cardinality")),T("design:type",Function),T("design:paramtypes",[String]),T("design:returntype",Promise)],ft.prototype,"list",null);zt([vi(":id"),vt(0,dn("id")),T("design:type",Function),T("design:paramtypes",[String]),T("design:returntype",Promise)],ft.prototype,"get",null);zt([Ou(),vt(0,Ei(new j(Wt))),T("design:type",Function),T("design:paramtypes",[Object]),T("design:returntype",Promise)],ft.prototype,"create",null);zt([Tu(":id"),vt(0,dn("id")),vt(1,Ei(new j(Wt))),T("design:type",Function),T("design:paramtypes",[String,Object]),T("design:returntype",Promise)],ft.prototype,"update",null);zt([Eu(":id"),vu(204),vt(0,dn("id")),T("design:type",Function),T("design:paramtypes",[String]),T("design:returntype",Promise)],ft.prototype,"remove",null);ft=zt([xu("workflows"),vt(0,xi(L)),vt(1,xi(x)),T("design:paramtypes",[L,x])],ft)});import{Body as pn,Controller as Au,Delete as ku,Get as ln,HttpCode as Nu,Inject as uo,Param as po,Patch as Oi,Post as Cu,Query as Du}from"@nestjs/common";var Tt,_,X,Z,Ri=l(()=>{"use strict";lt();Je();Y();Et();Ie();Ee();Te();on();Tt=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},_=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},X=function(o,t){return function(e,n){t(e,n,o)}},Z=class{views;tickets;repo;documentation;constructor(t,e,n,i){this.views=t,this.tickets=e,this.repo=n,this.documentation=i}async list(t){if(t!=null&&t!==""){let e=at.safeParse(t);if(!e.success)throw new b(`Invalid subjectType filter: ${t}`);return this.views.list({subjectType:e.data})}return this.views.list({})}async reorder(t){let e=[];for(let r of t.viewIds){let s=await this.views.get(r);if(!s)throw new b(`Unknown view id in reorder: ${r}`);e.push(s)}if(new Set(e.map(r=>r.subjectType)).size!==1)throw new b("All viewIds in a reorder request must share the same subjectType");return await this.views.reorder(t.viewIds)}async listSubjects(t){return eo(t,this.views,{tickets:this.tickets,repo:this.repo,documentation:this.documentation})}async get(t){let e=await this.views.get(t);if(!e)throw new g(`SubjectView not found: ${t}`);return e}async create(t){return this.views.create(t)}async update(t,e){let n=await this.views.update(t,e);if(!n)throw new g(`SubjectView not found: ${t}`);return n}async remove(t){if(!await this.views.delete(t))throw new g(`SubjectView not found: ${t}`)}};Tt([ln(),X(0,Du("subjectType")),_("design:type",Function),_("design:paramtypes",[String]),_("design:returntype",Promise)],Z.prototype,"list",null);Tt([Oi("reorder"),X(0,pn(new j(ao))),_("design:type",Function),_("design:paramtypes",[Object]),_("design:returntype",Promise)],Z.prototype,"reorder",null);Tt([ln(":id/subjects"),X(0,po("id")),_("design:type",Function),_("design:paramtypes",[String]),_("design:returntype",Promise)],Z.prototype,"listSubjects",null);Tt([ln(":id"),X(0,po("id")),_("design:type",Function),_("design:paramtypes",[String]),_("design:returntype",Promise)],Z.prototype,"get",null);Tt([Cu(),X(0,pn(new j(so))),_("design:type",Function),_("design:paramtypes",[Object]),_("design:returntype",Promise)],Z.prototype,"create",null);Tt([Oi(":id"),X(0,po("id")),X(1,pn(new j(Ht.partial().omit({id:!0,order:!0})))),_("design:type",Function),_("design:paramtypes",[String,Object]),_("design:returntype",Promise)],Z.prototype,"update",null);Tt([ku(":id"),Nu(204),X(0,po("id")),_("design:type",Function),_("design:paramtypes",[String]),_("design:returntype",Promise)],Z.prototype,"remove",null);Z=Tt([Au("views"),X(0,uo(B)),X(1,uo(Pt)),X(2,uo(At)),X(3,uo(kt)),_("design:paramtypes",[B,Object,Object,Object])],Z)});function lo(o,t,e=50){let n=o!=null&&o!==""?Number(o):e,i=t!=null&&t!==""?Number(t):0;return!Number.isFinite(n)||n<1?{limit:e,offset:Math.max(0,i||0)}:!Number.isFinite(i)||i<0?{limit:n,offset:0}:{limit:Math.floor(n),offset:Math.floor(i)}}function fo(o,t,e){return o.slice(e,e+t)}var fn=l(()=>{"use strict"});import{z as Ot}from"zod";var mo,ho,mn=l(()=>{"use strict";mo=Ot.object({workflowId:Ot.string().min(1),subjectId:Ot.string().min(1).optional(),inputValues:Ot.record(Ot.string(),Ot.unknown())}),ho=Ot.object({response:Ot.unknown()})});import{Body as Ai,Controller as $u,Get as ki,Inject as Pi,Param as hn,Post as bn,Query as $t}from"@nestjs/common";import"zod";var Yt,O,N,qu,mt,Ni=l(()=>{"use strict";ro();Ut();Y();Et();fn();mn();Yt=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},O=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},N=function(o,t){return function(e,n){t(e,n,o)}},qu=["pending","planning","waiting_for_human","waiting_for_children","implementing","testing","completed","failed","cancelled"],mt=class{jobs;runner;constructor(t,e){this.jobs=t,this.runner=e}async list(t,e,n,i,r,s,a){if(e!=null&&e!==""&&!qu.includes(e))throw new b(`Invalid status filter: ${e}`);if(r!=null&&r!==""&&r!=="true"&&r!=="false")throw new b(`Invalid topLevelOnly filter: ${r}`);let{limit:u,offset:c}=lo(s,a),f=await this.jobs.list({...t?{workflowId:t}:{},...e?{status:e}:{},...n?{batchId:n}:{},...i?{parentJobId:i}:{},...r==="true"?{topLevelOnly:!0}:{}});return fo(f,u,c)}async get(t){let e=await this.jobs.get(t);if(!e)throw new g(`Job not found: ${t}`);return e}async create(t){return this.runner.start({workflowId:t.workflowId,...t.subjectId?{subjectId:t.subjectId}:{},inputValues:t.inputValues})}async resume(t,e){return this.runner.resume(t,e.response)}async retry(t){return this.runner.retryFailedJob(t)}};Yt([ki(),N(0,$t("workflowId")),N(1,$t("status")),N(2,$t("batchId")),N(3,$t("parentJobId")),N(4,$t("topLevelOnly")),N(5,$t("limit")),N(6,$t("offset")),O("design:type",Function),O("design:paramtypes",[String,String,String,String,String,String,String]),O("design:returntype",Promise)],mt.prototype,"list",null);Yt([ki(":id"),N(0,hn("id")),O("design:type",Function),O("design:paramtypes",[String]),O("design:returntype",Promise)],mt.prototype,"get",null);Yt([bn(),N(0,Ai(new j(mo))),O("design:type",Function),O("design:paramtypes",[Object]),O("design:returntype",Promise)],mt.prototype,"create",null);Yt([bn(":id/resume"),N(0,hn("id")),N(1,Ai(new j(ho))),O("design:type",Function),O("design:paramtypes",[String,Object]),O("design:returntype",Promise)],mt.prototype,"resume",null);Yt([bn(":id/retry"),N(0,hn("id")),O("design:type",Function),O("design:paramtypes",[String]),O("design:returntype",Promise)],mt.prototype,"retry",null);mt=Yt([$u("jobs"),N(0,Pi(x)),N(1,Pi(Q)),O("design:paramtypes",[x,Q])],mt)});import{z as C}from"zod";var bo,go,gn=l(()=>{"use strict";lt();bo=C.discriminatedUnion("mode",[C.object({mode:C.literal("view"),viewId:C.string().min(1)}),C.object({mode:C.literal("manual"),subjectType:at,subjectIds:C.array(C.string().min(1))})]),go=C.object({workflowId:C.string().min(1),selection:bo,triggeredBy:C.enum(["schedule","view_bulk","multiselect"]),notificationOverride:me.optional(),inputValues:C.record(C.string(),C.unknown())})});import{Body as Lu,Controller as Bu,Get as Sn,Inject as yn,Param as Ci,Post as Ju,Query as wn}from"@nestjs/common";import"zod";var be,q,ht,Rt,Di=l(()=>{"use strict";ro();Fe();Ut();Y();Et();fn();gn();be=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},q=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},ht=function(o,t){return function(e,n){t(e,n,o)}},Rt=class{batches;jobs;runner;constructor(t,e,n){this.batches=t,this.jobs=e,this.runner=n}async list(t,e,n){let{limit:i,offset:r}=lo(e,n),s=await this.batches.list(t?{workflowId:t}:{});return fo(s,i,r)}async get(t){let e=await this.batches.get(t);if(!e)throw new g(`JobBatch not found: ${t}`);return e}async listJobs(t){if(!await this.batches.get(t))throw new g(`JobBatch not found: ${t}`);return this.jobs.list({batchId:t})}async launch(t){let e=await this.runner.launch({workflowId:t.workflowId,selection:t.selection,triggeredBy:t.triggeredBy,...t.notificationOverride?{notificationOverride:t.notificationOverride}:{},inputValues:t.inputValues});return"resolvedSubjects"in e&&"jobIds"in e?{kind:"batch",batch:e}:{kind:"job",job:e}}};be([Sn(),ht(0,wn("workflowId")),ht(1,wn("limit")),ht(2,wn("offset")),q("design:type",Function),q("design:paramtypes",[String,String,String]),q("design:returntype",Promise)],Rt.prototype,"list",null);be([Sn(":id"),ht(0,Ci("id")),q("design:type",Function),q("design:paramtypes",[String]),q("design:returntype",Promise)],Rt.prototype,"get",null);be([Sn(":id/jobs"),ht(0,Ci("id")),q("design:type",Function),q("design:paramtypes",[String]),q("design:returntype",Promise)],Rt.prototype,"listJobs",null);be([Ju(),ht(0,Lu(new j(go))),q("design:type",Function),q("design:paramtypes",[Object]),q("design:returntype",Promise)],Rt.prototype,"launch",null);Rt=be([Bu("batches"),ht(0,yn(J)),ht(1,yn(x)),ht(2,yn(Q)),q("design:paramtypes",[J,x,Q])],Rt)});import{Body as $i,Controller as Fu,Delete as Uu,Get as qi,HttpCode as Mu,Inject as Vu,Param as _n,Patch as Ku,Post as Xu,Query as Hu}from"@nestjs/common";var Qt,R,qt,bt,Li=l(()=>{"use strict";lt();Vo();Y();Et();Qt=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},R=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},qt=function(o,t){return function(e,n){t(e,n,o)}},bt=class{schedules;constructor(t){this.schedules=t}async list(t){if(t==null||t==="")return this.schedules.list();if(t!=="true"&&t!=="false")throw new b(`Invalid enabled filter: ${t}`);return this.schedules.list({enabled:t==="true"})}async get(t){let e=await this.schedules.get(t);if(!e)throw new g(`Schedule not found: ${t}`);return e}async create(t){return this.schedules.create(t)}async update(t,e){let n=await this.schedules.update(t,e);if(!n)throw new g(`Schedule not found: ${t}`);return n}async remove(t){if(!await this.schedules.delete(t))throw new g(`Schedule not found: ${t}`)}};Qt([qi(),qt(0,Hu("enabled")),R("design:type",Function),R("design:paramtypes",[String]),R("design:returntype",Promise)],bt.prototype,"list",null);Qt([qi(":id"),qt(0,_n("id")),R("design:type",Function),R("design:paramtypes",[String]),R("design:returntype",Promise)],bt.prototype,"get",null);Qt([Xu(),qt(0,$i(new j(Gt))),R("design:type",Function),R("design:paramtypes",[Object]),R("design:returntype",Promise)],bt.prototype,"create",null);Qt([Ku(":id"),qt(0,_n("id")),qt(1,$i(new j(Gt.partial().omit({id:!0})))),R("design:type",Function),R("design:paramtypes",[String,Object]),R("design:returntype",Promise)],bt.prototype,"update",null);Qt([Uu(":id"),Mu(204),qt(0,_n("id")),R("design:type",Function),R("design:paramtypes",[String]),R("design:returntype",Promise)],bt.prototype,"remove",null);bt=Qt([Fu("schedules"),qt(0,Vu(dt)),R("design:paramtypes",[dt])],bt)});import{Controller as Wu,Inject as Gu,Query as Bi,Sse as zu}from"@nestjs/common";import{Observable as Fi}from"rxjs";var Ji,yo,jn,ge,Ui=l(()=>{"use strict";Ye();Ji=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},yo=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},jn=function(o,t){return function(e,n){t(e,n,o)}},ge=class{events;constructor(t){this.events=t}stream(t,e){return new Fi(n=>{let i=this.events.subscribe(r=>{let s=r;t!=null&&t!==""&&(!("jobId"in s)||s.jobId!==t)||e!=null&&e!==""&&(!("batchId"in s)||s.batchId!==e)||n.next({data:s})});return()=>{i()}})}};Ji([zu(),jn(0,Bi("jobId")),jn(1,Bi("batchId")),yo("design:type",Function),yo("design:paramtypes",[String,String]),yo("design:returntype",Fi)],ge.prototype,"stream",null);ge=Ji([Wu("events"),jn(0,Gu(z)),yo("design:paramtypes",[z])],ge)});import{extendZodWithOpenApi as Yu}from"@asteasolutions/zod-to-openapi";import{z as Qu}from"zod";var Mi=l(()=>{"use strict";Yu(Qu)});import{z as Vi}from"zod";var wo,In=l(()=>{"use strict";wo=Vi.object({value:Vi.string().min(1)})});import{z as d}from"zod";function hd(o){let t=d.toJSONSchema(o),{$schema:e,...n}=t;return n}function Hi(o){let t=(e,n)=>o.registerComponent("schemas",e,hd(n)).ref;return{WorkflowDefinition:t("WorkflowDefinition",he),WorkflowDefinitionInput:t("WorkflowDefinitionInput",Wt),UpdateWorkflowBody:t("UpdateWorkflowBody",dd),SubjectView:t("SubjectView",Ht),CreateSubjectViewBody:t("CreateSubjectViewBody",so),ReorderViewsBody:t("ReorderViewsBody",ao),UpdateViewBody:t("UpdateViewBody",pd),Schedule:t("Schedule",Gt),UpdateScheduleBody:t("UpdateScheduleBody",ld),EngineSettings:t("EngineSettings",cn),UpdateSettingsBody:t("UpdateSettingsBody",fd),SettingsPatchResponse:t("SettingsPatchResponse",md),SetSecretBody:t("SetSecretBody",wo),CreateJobBody:t("CreateJobBody",mo),ResumeJobBody:t("ResumeJobBody",ho),LaunchBody:t("LaunchBody",go),Job:t("Job",Ki),JobBatch:t("JobBatch",Xi),LaunchResponse:t("LaunchResponse",id),HealthResponse:t("HealthResponse",sd),ProviderStatus:t("ProviderStatus",ad),ErrorResponse:t("ErrorResponse",cd),EngineEvent:t("EngineEvent",ud),Subject:t("Subject",So)}}var Zu,td,ed,od,So,nd,rd,Ki,Xi,id,sd,ad,cd,ud,dd,pd,ld,fd,md,P,xn,En=l(()=>{"use strict";Mi();lt();mn();gn();In();Zu=d.enum(["pending","planning","waiting_for_human","waiting_for_children","implementing","testing","completed","failed","cancelled"]),td=d.object({subjectType:d.literal("ticket"),id:d.string(),source:d.enum(["jira","azure-devops","manual"]),title:d.string(),description:d.string().optional(),status:d.string(),assignee:d.string().optional(),url:d.string().optional(),raw:d.record(d.string(),d.unknown()).optional()}),ed=d.object({subjectType:d.literal("pull_request"),id:d.string(),source:d.enum(["bitbucket","github","manual"]),title:d.string(),description:d.string().optional(),sourceBranch:d.string(),targetBranch:d.string(),author:d.string().optional(),url:d.string().optional(),raw:d.record(d.string(),d.unknown()).optional()}),od=d.object({subjectType:d.literal("documentation"),id:d.string(),source:d.enum(["confluence","notion","github_wiki","gitlab_wiki","azure_wiki","web","manual"]),title:d.string(),url:d.string().optional(),raw:d.record(d.string(),d.unknown()).optional()}),So=d.discriminatedUnion("subjectType",[td,ed,od]),nd=d.discriminatedUnion("mode",[d.object({mode:d.literal("single"),subject:So}),d.object({mode:d.literal("collection"),subjects:d.array(So)})]),rd=d.object({id:d.string(),stepDefinitionId:d.string(),type:d.string(),status:d.enum(["pending","running","waiting_for_children","completed","failed","skipped"]),startedAt:d.string().optional(),completedAt:d.string().optional(),output:d.unknown().optional(),error:d.string().optional(),childJobIds:d.array(d.string()).optional(),iterations:d.array(d.object({index:d.number().int(),stepExecutions:d.array(d.record(d.string(),d.unknown())),startedAt:d.string(),completedAt:d.string().optional()})).optional()}),Ki=d.object({id:d.string(),workflowId:d.string(),status:Zu,subjectContext:nd.optional(),selection:bo.optional(),batchId:d.string().optional(),parentJobId:d.string().optional(),parentStepExecutionId:d.string().optional(),fanOutIndex:d.number().int().optional(),retryOf:d.string().optional(),context:d.record(d.string(),d.unknown()),worktreePath:d.string().optional(),branch:d.string().optional(),currentStepId:d.string().optional(),currentStepExecutionId:d.string().optional(),stepHistory:d.array(rd),createdAt:d.string(),updatedAt:d.string(),completedAt:d.string().optional()}),Xi=d.object({id:d.string(),workflowId:d.string(),selection:bo,resolvedSubjects:d.array(So),jobIds:d.array(d.string()),status:d.enum(["running","completed","completed_with_issues","failed"]),triggeredBy:d.enum(["schedule","view_bulk","multiselect"]),scheduleId:d.string().optional(),notificationOverride:me.optional(),notificationSent:d.boolean(),createdAt:d.string(),completedAt:d.string().optional()}),id=d.discriminatedUnion("kind",[d.object({kind:d.literal("job"),job:Ki}),d.object({kind:d.literal("batch"),batch:Xi})]),sd=d.object({ok:d.boolean(),service:d.string(),timestamp:d.string()}),ad=d.object({providerId:d.string(),secretKey:d.string(),configured:d.boolean()}),cd=d.object({error:d.string()}),ud=d.object({type:d.string(),timestamp:d.string()}).passthrough(),dd=Wt,pd=Ht.partial().omit({id:!0,order:!0}),ld=Gt.partial().omit({id:!0}),fd=co,md=d.object({settings:cn,restartRequired:d.boolean()}),P=d.object({id:d.string().min(1)}),xn=d.object({limit:d.string().optional().openapi({description:"Max items to return (default 50)"}),offset:d.string().optional().openapi({description:"Number of items to skip (default 0)"})})});import{z as A}from"zod";function w(o,t){return{description:t,content:{"application/json":{schema:o}}}}function gt(o){return{type:"array",items:o}}function S(o,...t){let e={400:"Validation error",404:"Resource not found",409:"Conflict"};return Object.fromEntries(t.map(n=>[String(n),w(o.ErrorResponse,e[n]??"Error")]))}function Wi(o,t){o.registerPath({method:"get",path:"/health",tags:["Health"],summary:"Health check",responses:{200:w(t.HealthResponse,"Service is healthy")}}),o.registerPath({method:"get",path:"/workflows",tags:["Workflows"],summary:"List workflow definitions",request:{query:A.object({cardinality:A.enum(["single","batch","aggregate"]).optional()})},responses:{200:w(gt(t.WorkflowDefinition),"Workflow definitions"),...S(t,400)}}),o.registerPath({method:"get",path:"/workflows/{id}",tags:["Workflows"],summary:"Get a workflow definition",request:{params:P},responses:{200:w(t.WorkflowDefinition,"Workflow definition"),...S(t,404)}}),o.registerPath({method:"post",path:"/workflows",tags:["Workflows"],summary:"Create a workflow definition",request:{body:{required:!0,content:{"application/json":{schema:t.WorkflowDefinitionInput}}}},responses:{201:w(t.WorkflowDefinition,"Created workflow definition"),...S(t,400)}}),o.registerPath({method:"patch",path:"/workflows/{id}",tags:["Workflows"],summary:"Update a workflow definition",request:{params:P,body:{required:!0,content:{"application/json":{schema:t.UpdateWorkflowBody}}}},responses:{200:w(t.WorkflowDefinition,"Updated workflow definition"),...S(t,400,404)}}),o.registerPath({method:"delete",path:"/workflows/{id}",tags:["Workflows"],summary:"Delete a workflow definition",description:"Rejected with 409 if any non-terminal Job still references the workflow. Terminal Jobs (completed, failed, cancelled) do not block deletion.",request:{params:P},responses:{204:{description:"Workflow deleted"},...S(t,404,409)}}),o.registerPath({method:"get",path:"/views",tags:["Views"],summary:"List subject views",request:{query:A.object({subjectType:at.optional()})},responses:{200:w(gt(t.SubjectView),"Subject views"),...S(t,400)}}),o.registerPath({method:"get",path:"/views/{id}",tags:["Views"],summary:"Get a subject view",request:{params:P},responses:{200:w(t.SubjectView,"Subject view"),...S(t,404)}}),o.registerPath({method:"get",path:"/views/{id}/subjects",tags:["Views"],summary:"Preview subjects matching a view",description:"Live provider query for the View's saved filter. Same resolution path as launch() for { mode: 'view' }. Does not create Jobs or snapshots.",request:{params:P},responses:{200:w(gt(t.Subject),"Matching subjects"),...S(t,404,400)}}),o.registerPath({method:"patch",path:"/views/reorder",tags:["Views"],summary:"Reorder views within a subject type group",request:{body:{required:!0,content:{"application/json":{schema:t.ReorderViewsBody}}}},responses:{200:w(gt(t.SubjectView),"Reordered views for the subject type"),...S(t,400)}}),o.registerPath({method:"post",path:"/views",tags:["Views"],summary:"Create a subject view",request:{body:{required:!0,content:{"application/json":{schema:t.CreateSubjectViewBody}}}},responses:{201:w(t.SubjectView,"Created subject view"),...S(t,400)}}),o.registerPath({method:"patch",path:"/views/{id}",tags:["Views"],summary:"Update a subject view",request:{params:P,body:{required:!0,content:{"application/json":{schema:t.UpdateViewBody}}}},responses:{200:w(t.SubjectView,"Updated subject view"),...S(t,400,404)}}),o.registerPath({method:"delete",path:"/views/{id}",tags:["Views"],summary:"Delete a subject view",request:{params:P},responses:{204:{description:"Subject view deleted"},...S(t,404)}}),o.registerPath({method:"get",path:"/jobs",tags:["Jobs"],summary:"List jobs",request:{query:xn.extend({workflowId:A.string().optional(),status:A.enum(["pending","planning","waiting_for_human","waiting_for_children","implementing","testing","completed","failed","cancelled"]).optional(),batchId:A.string().optional(),parentJobId:A.string().optional(),topLevelOnly:A.enum(["true","false"]).optional().openapi({description:"When true, exclude jobs that belong to a batch or a parent (sub_workflow) job"})})},responses:{200:w(gt(t.Job),"Jobs"),...S(t,400)}}),o.registerPath({method:"get",path:"/jobs/{id}",tags:["Jobs"],summary:"Get a job",request:{params:P},responses:{200:w(t.Job,"Job"),...S(t,404)}}),o.registerPath({method:"post",path:"/jobs",tags:["Jobs"],summary:"Start a single job",request:{body:{required:!0,content:{"application/json":{schema:t.CreateJobBody}}}},responses:{201:w(t.Job,"Started job"),...S(t,400,404)}}),o.registerPath({method:"post",path:"/jobs/{id}/resume",tags:["Jobs"],summary:"Resume a job waiting for human input",request:{params:P,body:{required:!0,content:{"application/json":{schema:t.ResumeJobBody}}}},responses:{200:w(t.Job,"Resumed job"),...S(t,400,404,409)}}),o.registerPath({method:"post",path:"/jobs/{id}/retry",tags:["Jobs"],summary:"Retry a failed job",request:{params:P},responses:{200:w(t.Job,"Retry job"),...S(t,404,409)}}),o.registerPath({method:"get",path:"/batches",tags:["Batches"],summary:"List job batches",request:{query:xn.extend({workflowId:A.string().optional()})},responses:{200:w(gt(t.JobBatch),"Job batches")}}),o.registerPath({method:"get",path:"/batches/{id}",tags:["Batches"],summary:"Get a job batch",request:{params:P},responses:{200:w(t.JobBatch,"Job batch"),...S(t,404)}}),o.registerPath({method:"get",path:"/batches/{id}/jobs",tags:["Batches"],summary:"List jobs in a batch",request:{params:P},responses:{200:w(gt(t.Job),"Jobs in the batch"),...S(t,404)}}),o.registerPath({method:"post",path:"/batches",tags:["Batches"],summary:"Launch a batch or aggregate run",description:"Resolves subject selection and starts either a JobBatch (batch cardinality) or a single Job (aggregate cardinality).",request:{body:{required:!0,content:{"application/json":{schema:t.LaunchBody}}}},responses:{201:w(t.LaunchResponse,"Launch result"),...S(t,400,404)}}),o.registerPath({method:"get",path:"/schedules",tags:["Schedules"],summary:"List schedules",request:{query:A.object({enabled:A.enum(["true","false"]).optional()})},responses:{200:w(gt(t.Schedule),"Schedules"),...S(t,400)}}),o.registerPath({method:"get",path:"/schedules/{id}",tags:["Schedules"],summary:"Get a schedule",request:{params:P},responses:{200:w(t.Schedule,"Schedule"),...S(t,404)}}),o.registerPath({method:"post",path:"/schedules",tags:["Schedules"],summary:"Create a schedule",description:"CRUD only \u2014 creating or enabling a schedule does not cause it to fire yet.",request:{body:{required:!0,content:{"application/json":{schema:t.Schedule}}}},responses:{201:w(t.Schedule,"Created schedule"),...S(t,400)}}),o.registerPath({method:"patch",path:"/schedules/{id}",tags:["Schedules"],summary:"Update a schedule",request:{params:P,body:{required:!0,content:{"application/json":{schema:t.UpdateScheduleBody}}}},responses:{200:w(t.Schedule,"Updated schedule"),...S(t,400,404)}}),o.registerPath({method:"delete",path:"/schedules/{id}",tags:["Schedules"],summary:"Delete a schedule",request:{params:P},responses:{204:{description:"Schedule deleted"},...S(t,404)}}),o.registerPath({method:"get",path:"/providers/status",tags:["Providers"],summary:"Provider secret configuration status",description:"Reports whether each known provider API key is set. Returns key *names* only \u2014 never secret values.",responses:{200:w(gt(t.ProviderStatus),"Provider configuration status")}}),o.registerPath({method:"get",path:"/settings",tags:["Settings"],summary:"Get engine settings",description:"Persisted provider configuration. Never includes secret values \u2014 those live in SecretStore.",responses:{200:w(t.EngineSettings,"Current engine settings")}}),o.registerPath({method:"patch",path:"/settings",tags:["Settings"],summary:"Update engine settings",description:"Partial merge. restartRequired is true only when activeProviders was in the patch (implementation binding is a boot-time decision). Jira/Bitbucket config fields take effect on the next provider call with no restart.",request:{body:{required:!0,content:{"application/json":{schema:t.UpdateSettingsBody}}}},responses:{200:w(t.SettingsPatchResponse,"Updated settings"),...S(t,400)}}),o.registerPath({method:"post",path:"/secrets/{key}",tags:["Settings"],summary:"Store a secret",description:"Writes to SecretStore. The response never includes the secret value.",request:{params:A.object({key:A.string().min(1)}),body:{required:!0,content:{"application/json":{schema:t.SetSecretBody}}}},responses:{204:{description:"Secret stored"},...S(t,400)}}),o.registerPath({method:"get",path:"/events",tags:["Events"],summary:"Subscribe to engine events (SSE)",description:"Server-Sent Events stream. Each event `data` field is a JSON EngineEvent. Optionally filter by jobId and/or batchId.",request:{query:A.object({jobId:A.string().optional(),batchId:A.string().optional()})},responses:{200:{description:"SSE stream of engine events",content:{"text/event-stream":{schema:t.EngineEvent}}}}})}var Gi=l(()=>{"use strict";lt();En()});import{OpenAPIRegistry as bd,OpenApiGeneratorV31 as gd}from"@asteasolutions/zod-to-openapi";function zi(){if(_o)return _o;let o=new bd,t=Hi(o);return Wi(o,t),_o=new gd(o.definitions).generateDocument({openapi:"3.1.0",info:{title:"Kno Engine API",version:"0.1.0",description:"REST API for workflow definitions, jobs, batches, schedules, views, and live events."},servers:[{url:"/api"}]}),_o}var _o,Yi=l(()=>{"use strict";En();Gi()});import{Controller as yd,Get as wd,Header as Sd}from"@nestjs/common";var Qi,vn,ye,Zi=l(()=>{"use strict";Yi();Qi=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},vn=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},ye=class{getOpenApiDocument(){return zi()}};Qi([wd("openapi.json"),Sd("Content-Type","application/json"),vn("design:type",Function),vn("design:paramtypes",[]),vn("design:returntype",void 0)],ye.prototype,"getOpenApiDocument",null);ye=Qi([yd()],ye)});import{Controller as jd,Get as Id,Inject as xd}from"@nestjs/common";var ts,jo,_d,we,es=l(()=>{"use strict";zo();ts=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},jo=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},_d=function(o,t){return function(e,n){t(e,n,o)}},we=class{providerStatus;constructor(t){this.providerStatus=t}async status(){return this.providerStatus.list()}};ts([Id("status"),jo("design:type",Function),jo("design:paramtypes",[]),jo("design:returntype",Promise)],we.prototype,"status",null);we=ts([jd("providers"),_d(0,xd(_t)),jo("design:paramtypes",[_t])],we)});import{Body as Ed,Controller as vd,Get as Td,Inject as Od,Patch as Rd}from"@nestjs/common";var Tn,Lt,os,Zt,ns=l(()=>{"use strict";lt();Ue();Et();Tn=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},Lt=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},os=function(o,t){return function(e,n){t(e,n,o)}},Zt=class{settings;constructor(t){this.settings=t}get(){return this.settings.get()}async update(t){return{settings:await this.settings.update(t),restartRequired:fr(t)}}};Tn([Td(),Lt("design:type",Function),Lt("design:paramtypes",[]),Lt("design:returntype",Promise)],Zt.prototype,"get",null);Tn([Rd(),os(0,Ed(new j(co))),Lt("design:type",Function),Lt("design:paramtypes",[Object]),Lt("design:returntype",Promise)],Zt.prototype,"update",null);Zt=Tn([vd("settings"),os(0,Od(D)),Lt("design:paramtypes",[D])],Zt)});import{Body as Pd,Controller as Ad,HttpCode as kd,Inject as Nd,Param as Cd,Post as Dd}from"@nestjs/common";var rs,Io,On,Se,is=l(()=>{"use strict";yt();Y();Et();In();rs=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},Io=function(o,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,t)},On=function(o,t){return function(e,n){t(e,n,o)}},Se=class{secrets;constructor(t){this.secrets=t}async set(t,e){let n=t.trim();if(!n)throw new b("Secret key must not be empty");await this.secrets.set(n,e.value)}};rs([Dd(":key"),kd(204),On(0,Cd("key")),On(1,Pd(new j(wo))),Io("design:type",Function),Io("design:paramtypes",[String,Object]),Io("design:returntype",Promise)],Se.prototype,"set",null);Se=rs([Ad("secrets"),On(0,Nd(H)),Io("design:paramtypes",[Function])],Se)});import{Module as qd}from"@nestjs/common";import{APP_FILTER as Ld}from"@nestjs/core";var $d,xo,ss=l(()=>{"use strict";de();rn();Qe();Fr();Ti();Ri();Ni();Di();Li();Ui();Zi();es();ns();is();Ge();Do();$d=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},xo=class{};xo=$d([qd({imports:[it,Xt,It,jt,Bt],controllers:[ft,Z,mt,Rt,bt,ge,ye,we,Zt,Se],providers:[{provide:Ld,useClass:io}]})],xo)});import{Module as Jd}from"@nestjs/common";var Bd,Eo,as=l(()=>{"use strict";Pn();An();kn();Ge();Ir();Qe();de();rn();ss();Bd=function(o,t,e,n){var i=arguments.length,r=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(o,t,e,n);else for(var a=o.length-1;a>=0;a--)(s=o[a])&&(r=(i<3?s(r):i>3?s(t,e,r):s(t,e))||r);return i>3&&r&&Object.defineProperty(t,e,r),r},Eo=class{};Eo=Bd([Jd({imports:[_e,je,jt,ze,It,it,Xt,xo],controllers:[te]})],Eo)});import{apiReference as Fd}from"@scalar/nestjs-api-reference";function cs(o){o.use("/api/docs",Fd({url:"/api/openapi.json",pageTitle:"Kno Engine API"}))}var us=l(()=>{"use strict"});import{existsSync as Ud}from"node:fs";import{dirname as Md,join as ds}from"node:path";import{fileURLToPath as Vd}from"node:url";function ps(){let o=Md(Vd(import.meta.url)),t=[ds(o,"../../static"),ds(o,"../static")];for(let e of t)if(Ud(e))return e;return null}var ls=l(()=>{"use strict"});var Wd={};import"reflect-metadata";import{existsSync as Kd}from"node:fs";import{join as fs}from"node:path";import{NestFactory as Xd}from"@nestjs/core";async function Hd(){let o=await Xd.create(Eo);o.enableCors(),o.setGlobalPrefix("api"),cs(o);let t=ps();t&&Kd(fs(t,"index.html"))&&(o.useStaticAssets(t),o.use((n,i,r)=>{if(n.method!=="GET"&&n.method!=="HEAD"||n.path.startsWith("/api"))return r();i.sendFile(fs(t,"index.html"))}));let e=Number(process.env.PORT??3e3);await o.listen(e)}var ms=l(()=>{"use strict";as();us();ls();Hd()});import{readFileSync as Gd}from"node:fs";function zd(){let o=Gd(new URL("../package.json",import.meta.url),"utf8");return JSON.parse(o).version}var vo=process.argv.slice(2);vo.includes("--version")||vo.includes("-v")?console.log(zd()):vo.includes("--help")||vo.includes("-h")?console.log(["Usage: kno [options]","","Starts the knoflows engine (REST API + bundled web client).","","Options:"," -v, --version Print the engine version and exit"," -h, --help Print this message and exit","","Environment:"," PORT HTTP port to listen on (default 3000)"," KNO_SQLITE_PATH SQLite file path, or :memory: for an ephemeral database"].join(`
|
|
134
|
+
`)):await Promise.resolve().then(()=>(ms(),Wd));
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@knoflows/engine",
|
|
3
|
-
"version": "0.1.0-alpha.
|
|
3
|
+
"version": "0.1.0-alpha.2",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"license": "UNLICENSED",
|
|
6
6
|
"bin": {
|
|
@@ -40,24 +40,25 @@
|
|
|
40
40
|
"@anthropic-ai/claude-agent-sdk": "^0.3.243",
|
|
41
41
|
"@asteasolutions/zod-to-openapi": "^9.1.0",
|
|
42
42
|
"@cursor/sdk": "^1.0.28",
|
|
43
|
-
"@knoflows/shared": "^0.1.0",
|
|
44
43
|
"@napi-rs/keyring": "^1.3.0",
|
|
45
44
|
"@nestjs/common": "^11.1.0",
|
|
46
45
|
"@nestjs/core": "^11.1.0",
|
|
47
46
|
"@nestjs/platform-express": "^11.1.0",
|
|
48
|
-
"@nestjs/testing": "^11.1.28",
|
|
49
47
|
"@scalar/nestjs-api-reference": "^1.2.12",
|
|
50
48
|
"drizzle-orm": "^1.0.0-rc.4",
|
|
51
49
|
"reflect-metadata": "^0.2.0",
|
|
52
50
|
"rxjs": "^7.0.0",
|
|
53
|
-
"
|
|
51
|
+
"zod": "^4.0.0"
|
|
54
52
|
},
|
|
55
53
|
"devDependencies": {
|
|
54
|
+
"@knoflows/shared": "^0.1.0",
|
|
56
55
|
"@nestjs/cli": "^11.0.0",
|
|
56
|
+
"@nestjs/testing": "^11.1.28",
|
|
57
57
|
"@types/node": "^22.0.0",
|
|
58
58
|
"@types/supertest": "^7.2.1",
|
|
59
59
|
"drizzle-kit": "^1.0.0-rc.4",
|
|
60
60
|
"esbuild": "^0.25.12",
|
|
61
|
+
"supertest": "^7.2.2",
|
|
61
62
|
"tsx": "^4.19.0",
|
|
62
63
|
"typescript": "^6.0.0"
|
|
63
64
|
}
|