@knoflows/engine 0.1.0-alpha.10 → 0.1.0-alpha.12
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 +12 -12
- package/package.json +2 -2
- package/static/assets/i18n/en.json +34 -0
- package/static/assets/i18n/es.json +34 -0
- package/static/{chunk-CgqRVtSF.js → chunk--F2Y9kLC.js} +1 -1
- package/static/{chunk-jct1_zOr.js → chunk-A3t8CipM.js} +1 -1
- package/static/{chunk-2KSNHCgb.js → chunk-BAgwFLbm.js} +1 -1
- package/static/{chunk-B2hO-qT3.js → chunk-BLSuZA6j.js} +1 -1
- package/static/{chunk-W5GAgssE.js → chunk-Bc9kVhav.js} +1 -1
- package/static/{chunk-BUuwGTt7.js → chunk-BdrifDCS.js} +7 -7
- package/static/{chunk-CJDp11v5.js → chunk-BkJuaRUH.js} +1 -1
- package/static/chunk-BmP-Xct3.js +1 -0
- package/static/{chunk-XLpSkczx.js → chunk-BqB1I-vg.js} +1 -1
- package/static/{chunk-eSxb3-OU.js → chunk-BquoV7tV.js} +1 -1
- package/static/{chunk-BVw7xkK9.js → chunk-C3Ej8Ue9.js} +1 -1
- package/static/chunk-C5T1qa5G.js +1 -0
- package/static/{chunk-DNOjVPY0.js → chunk-CK-2DsDH.js} +1 -1
- package/static/{chunk-cHfOiAJm.js → chunk-CKFZoQzp.js} +1 -1
- package/static/{chunk-DblClAqu.js → chunk-CLNhyiRm.js} +1 -1
- package/static/{chunk-A4AkMf2s.js → chunk-CN5_Adst.js} +1 -1
- package/static/{chunk-DQnMulwi.js → chunk-COSsVdG3.js} +1 -1
- package/static/chunk-Cj-KtAk-.js +1 -0
- package/static/{chunk-3mppll1n.js → chunk-CrD5w72_.js} +1 -1
- package/static/chunk-D5Bqg3D5.js +7 -0
- package/static/chunk-DAfnL0eP.js +1 -0
- package/static/{chunk-Cd8F2jeN.js → chunk-Dc3mv2RT.js} +1 -1
- package/static/chunk-Dc7Nho4-.js +1 -0
- package/static/{chunk-BjZIiizu.js → chunk-Df_jRm7U.js} +1 -1
- package/static/{chunk-mzyds3TS.js → chunk-Dl9xoaKd.js} +1 -1
- package/static/{chunk-Ojn34cvU.js → chunk-DqECIHE5.js} +1 -1
- package/static/{chunk-B8MrNxxk.js → chunk-Dtfc5XNc.js} +1 -1
- package/static/chunk-DxtF2GQ1.js +1 -0
- package/static/{chunk-CJRNatUw.js → chunk-KhdCYqqN.js} +1 -1
- package/static/{chunk-BAc0DRm8.js → chunk-TkjFi8lV.js} +1 -1
- package/static/{chunk-DjibVmY7.js → chunk-UArWmYDU.js} +1 -1
- package/static/{chunk-CWbxWv5I.js → chunk-WGWZEfc0.js} +1 -1
- package/static/{chunk-CEcbtdnK.js → chunk-hEYSTlD1.js} +1 -1
- package/static/{chunk-Cf_xd8ER.js → chunk-jg6TAN9F.js} +1 -1
- package/static/{chunk-CDWIMt6y.js → chunk-mb666CWY.js} +1 -1
- package/static/{chunk-hZzW00VR.js → chunk-nXCKNQUo.js} +1 -1
- package/static/{chunk-wbdetocK.js → chunk-ndsN8K7Q.js} +3 -3
- package/static/{chunk-tYnBYi0l.js → chunk-tnTBlRRN.js} +1 -1
- package/static/index.html +1 -1
- package/static/{main-MNK6ZYDO.js → main-RRKPLQCF.js} +1 -1
- package/static/chunk-6BQlxALO.js +0 -1
- package/static/chunk-BFkZ796p.js +0 -7
- package/static/chunk-BNOYZq-b.js +0 -1
- package/static/chunk-BbcTWKT2.js +0 -1
- package/static/chunk-BhGgxvgu.js +0 -1
- package/static/chunk-D6YfO72h.js +0 -1
- package/static/chunk-DoXxOh8j.js +0 -1
package/dist/engine.js
CHANGED
|
@@ -1,26 +1,26 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var l=(r,e)=>()=>(r&&(e=r(r=0)),e);import{Controller as ql,Get as Bl}from"@nestjs/common";var cs,wo,Xt,us=l(()=>{"use strict";cs=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},wo=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},Xt=class{getHealth(){return{ok:!0,service:"kno-engine",timestamp:new Date().toISOString()}}};cs([Bl(),wo("design:type",Function),wo("design:paramtypes",[]),wo("design:returntype",Object)],Xt.prototype,"getHealth",null);Xt=cs([ql("health")],Xt)});import{Module as Fl}from"@nestjs/common";var Dl,Pr,ls=l(()=>{"use strict";Dl=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Pr=class{};Pr=Dl([Fl({})],Pr)});import{Module as Jl}from"@nestjs/common";var Nl,Rr,ps=l(()=>{"use strict";Nl=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Rr=class{};Rr=Nl([Jl({})],Rr)});var Yt,go=l(()=>{"use strict";Yt=Symbol("NOTIFICATION_PROVIDER")});var Er,ds=l(()=>{"use strict";Er=class{async send(e){console.log("[notification]",JSON.stringify(e))}}});import{existsSync as fs}from"node:fs";import{dirname as Ll,join as Zt}from"node:path";import{fileURLToPath as Ul}from"node:url";function er(){let r=Ll(Ul(import.meta.url)),e=Zt(r,"../data"),t=Zt(r,"../../data");return fs(Zt(e,"kno.db"))?e:fs(Zt(t,"kno.db"))?t:e}function ms(){return Zt(er(),"kno.db")}var kr=l(()=>{"use strict"});import{createCipheriv as Ml,createDecipheriv as Wl,randomBytes as hs}from"node:crypto";import{mkdir as ys,readFile as ws,writeFile as gs}from"node:fs/promises";import{join as So}from"node:path";function Rt(r){return`kno.${r}.apiKey`}function Gl(r){return So(r,"secrets")}function Ss(r){return new xo(Gl(r.dataDir),r.keyring)}function zl(r){try{return r(Ar,"__kno_probe__").getPassword(),!0}catch(e){return vo(e)}}function vo(r){let e=r instanceof Error?r.message:String(r);return/noentry|no matching entry|not found|no such/i.test(e)}var Ar,bs,Hl,bo,Vl,Kl,xo,fe,Te=l(()=>{"use strict";Ar="kno-flows";bs="aes-256-gcm",Hl=12,bo=32,Vl="master.key",Kl="store.json",xo=class{secretsDir;keyring;keyringResolved=!1;masterKey=null;constructor(e,t){this.secretsDir=e,this.keyring=t,t!==void 0&&(this.keyringResolved=!0)}async get(e){let t=await this.resolveKeyring();if(t)try{let n=t(Ar,e).getPassword();if(n!=null)return n}catch(n){vo(n)||this.disableKeyring()}return this.fileGet(e)}async set(e,t){let n=await this.resolveKeyring();if(n)try{n(Ar,e).setPassword(t),await this.fileDelete(e);return}catch{this.disableKeyring()}await this.fileSet(e,t)}async delete(e){let t=await this.resolveKeyring();if(t)try{t(Ar,e).deletePassword()}catch(n){vo(n)||this.disableKeyring()}await this.fileDelete(e)}disableKeyring(){this.keyring=null,this.keyringResolved=!0}async resolveKeyring(){if(this.keyringResolved)return this.keyring??null;this.keyringResolved=!0;try{let{Entry:e}=await import("@napi-rs/keyring"),t=(n,o)=>new e(n,o);return zl(t)?(this.keyring=t,t):(this.keyring=null,null)}catch{return this.keyring=null,null}}async fileGet(e){let n=(await this.readStore())[e];return n?this.decrypt(n):null}async fileSet(e,t){let n=await this.readStore();n[e]=await this.encrypt(t),await this.writeStore(n)}async fileDelete(e){let t=await this.readStore();e in t&&(delete t[e],await this.writeStore(t))}async readStore(){try{let e=await ws(this.storePath(),"utf8"),t=JSON.parse(e);if(t==null||typeof t!="object"||Array.isArray(t))throw new Error(`Corrupt secret store at ${this.storePath()}`);return t}catch(e){if(e.code==="ENOENT")return{};throw e}}async writeStore(e){await ys(this.secretsDir,{recursive:!0}),await gs(this.storePath(),JSON.stringify(e,null,2),{encoding:"utf8",mode:384})}async encrypt(e){let t=await this.loadOrCreateMasterKey(),n=hs(Hl),o=Ml(bs,t,n),i=Buffer.concat([o.update(e,"utf8"),o.final()]);return{iv:n.toString("base64"),tag:o.getAuthTag().toString("base64"),ciphertext:i.toString("base64")}}async decrypt(e){let t=await this.loadOrCreateMasterKey(),n=Wl(bs,t,Buffer.from(e.iv,"base64"));return n.setAuthTag(Buffer.from(e.tag,"base64")),Buffer.concat([n.update(Buffer.from(e.ciphertext,"base64")),n.final()]).toString("utf8")}async loadOrCreateMasterKey(){if(this.masterKey)return this.masterKey;await ys(this.secretsDir,{recursive:!0});let e=this.masterKeyPath();try{let n=(await ws(e,"utf8")).trim(),o=Buffer.from(n,"hex");if(o.length!==bo)throw new Error(`Secret store master key at ${e} is not ${bo} bytes`);return this.masterKey=o,o}catch(n){if(n.code!=="ENOENT")throw n}let t=hs(bo);return await gs(e,t.toString("hex"),{encoding:"utf8",mode:384}),this.masterKey=t,t}storePath(){return So(this.secretsDir,Kl)}masterKeyPath(){return So(this.secretsDir,Vl)}};fe=Symbol("SECRET_STORE")});import{Module as Xl}from"@nestjs/common";import{mkdirSync as Yl}from"node:fs";var Ql,xs,Et,jo=l(()=>{"use strict";kr();Te();Ql=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},xs=er();Yl(xs,{recursive:!0});Et=class{};Et=Ql([Xl({providers:[{provide:fe,useFactory:()=>Ss({dataDir:xs})}],exports:[fe]})],Et)});import{index as Zl,sqliteTable as ep,text as xe}from"drizzle-orm/sqlite-core";var Ve,Io=l(()=>{"use strict";Ve=ep("workflow_definitions",{id:xe("id").primaryKey(),name:xe("name").notNull(),description:xe("description"),appliesTo:xe("applies_to",{mode:"json"}).$type().notNull(),subjectHandling:xe("subject_handling",{enum:["per-subject","collection"]}).notNull(),inputSchema:xe("input_schema",{mode:"json"}).$type().notNull(),steps:xe("steps",{mode:"json"}).$type().notNull(),notificationPolicy:xe("notification_policy",{mode:"json"}).$type().notNull(),createdAt:xe("created_at").notNull(),updatedAt:xe("updated_at").notNull()},r=>[Zl("workflow_definitions_subject_handling_idx").on(r.subjectHandling)])});import{index as vs,integer as tp,sqliteTable as rp,text as Ke}from"drizzle-orm/sqlite-core";var ve,_o=l(()=>{"use strict";ve=rp("subject_views",{id:Ke("id").primaryKey(),name:Ke("name").notNull(),subjectType:Ke("subject_type").$type().notNull(),workflowId:Ke("workflow_id").notNull(),query:Ke("query",{mode:"json"}).$type().notNull(),description:Ke("description"),queryTemplate:Ke("query_template",{mode:"json"}).$type(),providerInstanceId:Ke("provider_instance_id").notNull().default(""),order:tp("order").notNull().default(0)},r=>[vs("subject_views_subject_type_idx").on(r.subjectType),vs("subject_views_subject_type_order_idx").on(r.subjectType,r.order)])});import{index as js,integer as np,sqliteTable as op,text as je}from"drizzle-orm/sqlite-core";var Ge,Cr=l(()=>{"use strict";Ge=op("job_batches",{id:je("id").primaryKey(),workflowId:je("workflow_id").notNull(),selection:je("selection",{mode:"json"}).$type().notNull(),resolvedSubjects:je("resolved_subjects",{mode:"json"}).$type().notNull(),status:je("status",{enum:["running","completed","completed_with_issues","failed","cancelled"]}).notNull(),triggeredBy:je("triggered_by",{enum:["schedule","view_bulk","multiselect"]}).notNull(),scheduleId:je("schedule_id"),notificationOverride:je("notification_override",{mode:"json"}).$type(),notificationSent:np("notification_sent",{mode:"boolean"}).notNull(),createdAt:je("created_at").notNull(),completedAt:je("completed_at")},r=>[js("job_batches_workflow_id_idx").on(r.workflowId),js("job_batches_schedule_id_idx").on(r.scheduleId)])});import{index as Tr,integer as ip,sqliteTable as sp,text as D}from"drizzle-orm/sqlite-core";var L,tr=l(()=>{"use strict";Cr();L=sp("jobs",{id:D("id").primaryKey(),workflowId:D("workflow_id").notNull(),status:D("status").$type().notNull(),selection:D("selection",{mode:"json"}).$type(),batchId:D("batch_id").references(()=>Ge.id),parentJobId:D("parent_job_id"),parentStepExecutionId:D("parent_step_execution_id"),fanOutIndex:ip("fan_out_index"),retryOf:D("retry_of"),workflowSnapshot:D("workflow_snapshot",{mode:"json"}).$type(),context:D("context",{mode:"json"}).$type().notNull(),worktreePath:D("worktree_path"),branch:D("branch"),worktreeDeletedAt:D("worktree_deleted_at"),currentStepId:D("current_step_id"),currentStepExecutionId:D("current_step_execution_id"),createdAt:D("created_at").notNull(),updatedAt:D("updated_at").notNull(),completedAt:D("completed_at")},r=>[Tr("jobs_workflow_id_idx").on(r.workflowId),Tr("jobs_status_idx").on(r.status),Tr("jobs_batch_id_idx").on(r.batchId),Tr("jobs_parent_job_id_idx").on(r.parentJobId)])});import{index as Is,sqliteTable as ap,text as rr}from"drizzle-orm/sqlite-core";var Ie,Po=l(()=>{"use strict";tr();Ie=ap("job_subjects",{id:rr("id").primaryKey(),jobId:rr("job_id").notNull().references(()=>L.id),subjectType:rr("subject_type").$type().notNull(),subjectId:rr("subject_id").notNull(),snapshot:rr("snapshot",{mode:"json"}).$type().notNull()},r=>[Is("job_subjects_job_id_idx").on(r.jobId),Is("job_subjects_subject_lookup_idx").on(r.subjectType,r.subjectId)])});import{index as _s,integer as cp,sqliteTable as up,text as me}from"drizzle-orm/sqlite-core";var pt,Ro=l(()=>{"use strict";tr();pt=up("job_step_executions",{id:me("id").primaryKey(),jobId:me("job_id").notNull().references(()=>L.id),stepDefinitionId:me("step_definition_id").notNull(),type:me("type").$type().notNull(),status:me("status").$type().notNull(),startedAt:me("started_at"),completedAt:me("completed_at"),output:me("output",{mode:"json"}).$type(),error:me("error"),childJobIds:me("child_job_ids",{mode:"json"}).$type(),parentStepExecutionId:me("parent_step_execution_id").references(()=>pt.id),iterationIndex:cp("iteration_index")},r=>[_s("job_step_executions_job_id_idx").on(r.jobId),_s("job_step_executions_parent_idx").on(r.parentStepExecutionId)])});import{index as lp,integer as pp,sqliteTable as dp,text as ze}from"drizzle-orm/sqlite-core";var Qe,Eo=l(()=>{"use strict";Qe=dp("schedules",{id:ze("id").primaryKey(),viewId:ze("view_id").notNull(),triggerType:ze("trigger_type",{enum:["cron"]}).notNull(),cadence:ze("cadence").notNull(),notificationOverride:ze("notification_override",{mode:"json"}).$type(),missedFirePolicy:ze("missed_fire_policy",{enum:["skip","catch_up"]}).notNull(),enabled:pp("enabled",{mode:"boolean"}).notNull(),lastFiredAt:ze("last_fired_at"),createdAt:ze("created_at").notNull()},r=>[lp("schedules_enabled_idx").on(r.enabled)])});import{integer as fp,sqliteTable as mp,text as nr}from"drizzle-orm/sqlite-core";var _e,ko=l(()=>{"use strict";_e=mp("workflow_shortcuts",{id:nr("id").primaryKey(),name:nr("name").notNull(),workflowId:nr("workflow_id").notNull(),inputValues:nr("input_values",{mode:"json"}).$type().notNull(),lastJobId:nr("last_job_id"),order:fp("order").notNull().default(0)})});import{sqliteTable as hp,text as or}from"drizzle-orm/sqlite-core";var Xe,Ao=l(()=>{"use strict";Xe=hp("context_files",{id:or("id").primaryKey(),name:or("name").notNull(),description:or("description"),tier:or("tier").$type().notNull(),path:or("path").notNull()})});import{sqliteTable as yp,text as Or}from"drizzle-orm/sqlite-core";var Ye,Co=l(()=>{"use strict";Ye=yp("local_repositories",{id:Or("id").primaryKey(),name:Or("name").notNull(),localPath:Or("local_path").notNull(),worktreeBasePath:Or("worktree_base_path")})});import{sqliteTable as wp,text as Ps}from"drizzle-orm/sqlite-core";var ir,kt,To=l(()=>{"use strict";ir="default",kt=wp("settings",{id:Ps("id").primaryKey(),data:Ps("data",{mode:"json"}).$type().notNull()})});import{defineRelations as gp}from"drizzle-orm";var bp,Rs,Es=l(()=>{"use strict";Io();_o();tr();Po();Ro();Cr();Eo();ko();Ao();Co();To();bp={workflowDefinitions:Ve,subjectViews:ve,jobs:L,jobSubjects:Ie,jobStepExecutions:pt,jobBatches:Ge,schedules:Qe,workflowShortcuts:_e,contextFiles:Xe,localRepositories:Ye,settings:kt},Rs=gp(bp,r=>({workflowDefinitions:{},subjectViews:{},schedules:{},workflowShortcuts:{},contextFiles:{},localRepositories:{},settings:{},jobs:{subjects:r.many.jobSubjects({from:r.jobs.id,to:r.jobSubjects.jobId}),stepExecutions:r.many.jobStepExecutions({from:r.jobs.id,to:r.jobStepExecutions.jobId}),batch:r.one.jobBatches({from:r.jobs.batchId,to:r.jobBatches.id})},jobSubjects:{job:r.one.jobs({from:r.jobSubjects.jobId,to:r.jobs.id})},jobStepExecutions:{job:r.one.jobs({from:r.jobStepExecutions.jobId,to:r.jobs.id}),parent:r.one.jobStepExecutions({from:r.jobStepExecutions.parentStepExecutionId,to:r.jobStepExecutions.id,alias:"job_step_executions_parent"}),children:r.many.jobStepExecutions({from:r.jobStepExecutions.id,to:r.jobStepExecutions.parentStepExecutionId,alias:"job_step_executions_children"})},jobBatches:{jobs:r.many.jobs({from:r.jobBatches.id,to:r.jobs.batchId})}}))});import{drizzle as Sp}from"drizzle-orm/node-sqlite";import{DatabaseSync as Vg}from"node:sqlite";function ks(r){return r.exec("PRAGMA foreign_keys = ON;"),Sp({client:r,relations:Rs})}var As=l(()=>{"use strict";Es()});import{existsSync as Cs,readdirSync as xp}from"node:fs";import{dirname as vp,join as Oo}from"node:path";import{fileURLToPath as jp}from"node:url";function Ts(){let r=vp(jp(import.meta.url)),e=[Oo(r,"persistence/migrations"),Oo(r,"migrations")];for(let t of e)if(Ip(t))return t;throw new Error(`Engine SQL migrations not found. Looked in: ${e.join(", ")}`)}function Ip(r){return Cs(r)?xp(r,{withFileTypes:!0}).some(e=>e.isDirectory()&&Cs(Oo(r,e.name,"migration.sql"))):!1}var Os=l(()=>{"use strict"});import{migrate as $s}from"drizzle-orm/node-sqlite/migrator";import{readMigrationFiles as _p}from"drizzle-orm/migrator";function qo(r,e,t={}){let n=t.log??(()=>{}),o=Ts(),i=_p({migrationsFolder:o});if(i.length===0)throw new he(`No SQL migrations in ${o}`);let s=Rp(i),a=cr(r,dt),u=Pp.filter(S=>cr(r,S));if(!a&&u.length===0){$s(e,{migrationsFolder:o}),$o(r,s);return}if(!a){Cp(r,s,n),Op(r,i),$o(r,s);return}Tp(r,i);let c=Bs(r,s),d=Ds(r);if(d.length===0&&u.length>0)throw new he("migrations table exists but is empty while application tables are present \u2014 treating this as an interrupted update");let m=new Set(d.map(S=>S.name).filter(S=>S!=null&&S!==""));if(i.filter(S=>!m.has(S.name)).length===0&&c.length>0)throw new he(`migrations journal is present but the schema is incomplete (${c.join("; ")}) \u2014 treating this as an interrupted update`);$s(e,{migrationsFolder:o}),$o(r,s)}function Rp(r){let e=[],t=[],n=[];for(let o of r)for(let i of o.sql){let s=i.trim().replace(/;+\s*$/,"");if(!s)continue;let a=Ep(s);if(a){e.push(a);continue}let u=kp(s);if(u){n.push(u);continue}let c=Ap(s);c&&t.push(c)}return{tables:e,indexes:t,alterColumns:n}}function Ep(r){let e=r.match(/^CREATE TABLE\s+(`[^`]+`|"[^"]+"|\w+)\s*\(/i);if(!e)return null;let t=r.indexOf("("),n=r.lastIndexOf(")");if(t<0||n<t)return null;let o=[];for(let i of r.slice(t+1,n).split(`
|
|
3
|
-
`)){let s=i.trim().replace(/,+\s*$/,"");if(!s||/^(CONSTRAINT|PRIMARY KEY|UNIQUE|FOREIGN KEY|CHECK)\b/i.test(s))continue;let a=s.match(/^(`[^`]+`|"[^"]+"|\w+)\s+(\w+)/);a&&o.push({name:
|
|
4
|
-
CREATE TABLE IF NOT EXISTS ${
|
|
2
|
+
var l=(r,e)=>()=>(r&&(e=r(r=0)),e);import{Controller as Gl,Get as zl}from"@nestjs/common";var fs,go,Zt,ms=l(()=>{"use strict";fs=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},go=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},Zt=class{getHealth(){return{ok:!0,service:"kno-engine",timestamp:new Date().toISOString()}}};fs([zl(),go("design:type",Function),go("design:paramtypes",[]),go("design:returntype",Object)],Zt.prototype,"getHealth",null);Zt=fs([Gl("health")],Zt)});import{Module as Xl}from"@nestjs/common";var Ql,Er,hs=l(()=>{"use strict";Ql=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Er=class{};Er=Ql([Xl({})],Er)});import{Module as Zl}from"@nestjs/common";var Yl,Pr,ys=l(()=>{"use strict";Yl=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Pr=class{};Pr=Yl([Zl({})],Pr)});var er,wo=l(()=>{"use strict";er=Symbol("NOTIFICATION_PROVIDER")});var Rr,gs=l(()=>{"use strict";Rr=class{async send(e){console.log("[notification]",JSON.stringify(e))}}});import{existsSync as ws}from"node:fs";import{dirname as ed,join as tr}from"node:path";import{fileURLToPath as td}from"node:url";function rr(){let r=ed(td(import.meta.url)),e=tr(r,"../data"),t=tr(r,"../../data");return ws(tr(e,"kno.db"))?e:ws(tr(t,"kno.db"))?t:e}function bs(){return tr(rr(),"kno.db")}var kr=l(()=>{"use strict"});import{createCipheriv as rd,createDecipheriv as nd,randomBytes as Ss}from"node:crypto";import{mkdir as xs,readFile as vs,writeFile as Is}from"node:fs/promises";import{join as So}from"node:path";function kt(r){return`kno.${r}.apiKey`}function ad(r){return So(r,"secrets")}function _s(r){return new xo(ad(r.dataDir),r.keyring)}function cd(r){try{return r(Ar,"__kno_probe__").getPassword(),!0}catch(e){return vo(e)}}function vo(r){let e=r instanceof Error?r.message:String(r);return/noentry|no matching entry|not found|no such/i.test(e)}var Ar,js,od,bo,id,sd,xo,fe,Oe=l(()=>{"use strict";Ar="kno-flows";js="aes-256-gcm",od=12,bo=32,id="master.key",sd="store.json",xo=class{secretsDir;keyring;keyringResolved=!1;masterKey=null;constructor(e,t){this.secretsDir=e,this.keyring=t,t!==void 0&&(this.keyringResolved=!0)}async get(e){let t=await this.resolveKeyring();if(t)try{let n=t(Ar,e).getPassword();if(n!=null)return n}catch(n){vo(n)||this.disableKeyring()}return this.fileGet(e)}async set(e,t){let n=await this.resolveKeyring();if(n)try{n(Ar,e).setPassword(t),await this.fileDelete(e);return}catch{this.disableKeyring()}await this.fileSet(e,t)}async delete(e){let t=await this.resolveKeyring();if(t)try{t(Ar,e).deletePassword()}catch(n){vo(n)||this.disableKeyring()}await this.fileDelete(e)}disableKeyring(){this.keyring=null,this.keyringResolved=!0}async resolveKeyring(){if(this.keyringResolved)return this.keyring??null;this.keyringResolved=!0;try{let{Entry:e}=await import("@napi-rs/keyring"),t=(n,o)=>new e(n,o);return cd(t)?(this.keyring=t,t):(this.keyring=null,null)}catch{return this.keyring=null,null}}async fileGet(e){let n=(await this.readStore())[e];return n?this.decrypt(n):null}async fileSet(e,t){let n=await this.readStore();n[e]=await this.encrypt(t),await this.writeStore(n)}async fileDelete(e){let t=await this.readStore();e in t&&(delete t[e],await this.writeStore(t))}async readStore(){try{let e=await vs(this.storePath(),"utf8"),t=JSON.parse(e);if(t==null||typeof t!="object"||Array.isArray(t))throw new Error(`Corrupt secret store at ${this.storePath()}`);return t}catch(e){if(e.code==="ENOENT")return{};throw e}}async writeStore(e){await xs(this.secretsDir,{recursive:!0}),await Is(this.storePath(),JSON.stringify(e,null,2),{encoding:"utf8",mode:384})}async encrypt(e){let t=await this.loadOrCreateMasterKey(),n=Ss(od),o=rd(js,t,n),i=Buffer.concat([o.update(e,"utf8"),o.final()]);return{iv:n.toString("base64"),tag:o.getAuthTag().toString("base64"),ciphertext:i.toString("base64")}}async decrypt(e){let t=await this.loadOrCreateMasterKey(),n=nd(js,t,Buffer.from(e.iv,"base64"));return n.setAuthTag(Buffer.from(e.tag,"base64")),Buffer.concat([n.update(Buffer.from(e.ciphertext,"base64")),n.final()]).toString("utf8")}async loadOrCreateMasterKey(){if(this.masterKey)return this.masterKey;await xs(this.secretsDir,{recursive:!0});let e=this.masterKeyPath();try{let n=(await vs(e,"utf8")).trim(),o=Buffer.from(n,"hex");if(o.length!==bo)throw new Error(`Secret store master key at ${e} is not ${bo} bytes`);return this.masterKey=o,o}catch(n){if(n.code!=="ENOENT")throw n}let t=Ss(bo);return await Is(e,t.toString("hex"),{encoding:"utf8",mode:384}),this.masterKey=t,t}storePath(){return So(this.secretsDir,sd)}masterKeyPath(){return So(this.secretsDir,id)}};fe=Symbol("SECRET_STORE")});import{Module as ld}from"@nestjs/common";import{mkdirSync as dd}from"node:fs";var ud,Es,At,Io=l(()=>{"use strict";kr();Oe();ud=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Es=rr();dd(Es,{recursive:!0});At=class{};At=ud([ld({providers:[{provide:fe,useFactory:()=>_s({dataDir:Es})}],exports:[fe]})],At)});import{index as pd,sqliteTable as fd,text as ve}from"drizzle-orm/sqlite-core";var Ge,jo=l(()=>{"use strict";Ge=fd("workflow_definitions",{id:ve("id").primaryKey(),name:ve("name").notNull(),description:ve("description"),appliesTo:ve("applies_to",{mode:"json"}).$type().notNull(),subjectHandling:ve("subject_handling",{enum:["per-subject","collection"]}).notNull(),inputSchema:ve("input_schema",{mode:"json"}).$type().notNull(),steps:ve("steps",{mode:"json"}).$type().notNull(),notificationPolicy:ve("notification_policy",{mode:"json"}).$type().notNull(),createdAt:ve("created_at").notNull(),updatedAt:ve("updated_at").notNull()},r=>[pd("workflow_definitions_subject_handling_idx").on(r.subjectHandling)])});import{index as Ps,integer as md,sqliteTable as hd,text as ze}from"drizzle-orm/sqlite-core";var Ie,_o=l(()=>{"use strict";Ie=hd("subject_views",{id:ze("id").primaryKey(),name:ze("name").notNull(),subjectType:ze("subject_type").$type().notNull(),workflowId:ze("workflow_id").notNull(),query:ze("query",{mode:"json"}).$type().notNull(),description:ze("description"),queryTemplate:ze("query_template",{mode:"json"}).$type(),providerInstanceId:ze("provider_instance_id").notNull().default(""),order:md("order").notNull().default(0)},r=>[Ps("subject_views_subject_type_idx").on(r.subjectType),Ps("subject_views_subject_type_order_idx").on(r.subjectType,r.order)])});import{index as Rs,integer as yd,sqliteTable as gd,text as je}from"drizzle-orm/sqlite-core";var Qe,Cr=l(()=>{"use strict";Qe=gd("job_batches",{id:je("id").primaryKey(),workflowId:je("workflow_id").notNull(),selection:je("selection",{mode:"json"}).$type().notNull(),resolvedSubjects:je("resolved_subjects",{mode:"json"}).$type().notNull(),status:je("status",{enum:["running","completed","completed_with_issues","failed","cancelled"]}).notNull(),triggeredBy:je("triggered_by",{enum:["schedule","view_bulk","multiselect"]}).notNull(),scheduleId:je("schedule_id"),notificationOverride:je("notification_override",{mode:"json"}).$type(),notificationSent:yd("notification_sent",{mode:"boolean"}).notNull(),createdAt:je("created_at").notNull(),completedAt:je("completed_at")},r=>[Rs("job_batches_workflow_id_idx").on(r.workflowId),Rs("job_batches_schedule_id_idx").on(r.scheduleId)])});import{index as Tr,integer as wd,sqliteTable as bd,text as D}from"drizzle-orm/sqlite-core";var L,nr=l(()=>{"use strict";Cr();L=bd("jobs",{id:D("id").primaryKey(),workflowId:D("workflow_id").notNull(),status:D("status").$type().notNull(),selection:D("selection",{mode:"json"}).$type(),batchId:D("batch_id").references(()=>Qe.id),parentJobId:D("parent_job_id"),parentStepExecutionId:D("parent_step_execution_id"),fanOutIndex:wd("fan_out_index"),retryOf:D("retry_of"),workflowSnapshot:D("workflow_snapshot",{mode:"json"}).$type(),context:D("context",{mode:"json"}).$type().notNull(),worktreePath:D("worktree_path"),branch:D("branch"),worktreeDeletedAt:D("worktree_deleted_at"),currentStepId:D("current_step_id"),currentStepExecutionId:D("current_step_execution_id"),createdAt:D("created_at").notNull(),updatedAt:D("updated_at").notNull(),completedAt:D("completed_at")},r=>[Tr("jobs_workflow_id_idx").on(r.workflowId),Tr("jobs_status_idx").on(r.status),Tr("jobs_batch_id_idx").on(r.batchId),Tr("jobs_parent_job_id_idx").on(r.parentJobId)])});import{index as ks,sqliteTable as Sd,text as or}from"drizzle-orm/sqlite-core";var _e,Eo=l(()=>{"use strict";nr();_e=Sd("job_subjects",{id:or("id").primaryKey(),jobId:or("job_id").notNull().references(()=>L.id),subjectType:or("subject_type").$type().notNull(),subjectId:or("subject_id").notNull(),snapshot:or("snapshot",{mode:"json"}).$type().notNull()},r=>[ks("job_subjects_job_id_idx").on(r.jobId),ks("job_subjects_subject_lookup_idx").on(r.subjectType,r.subjectId)])});import{index as As,integer as xd,sqliteTable as vd,text as me}from"drizzle-orm/sqlite-core";var pt,Po=l(()=>{"use strict";nr();pt=vd("job_step_executions",{id:me("id").primaryKey(),jobId:me("job_id").notNull().references(()=>L.id),stepDefinitionId:me("step_definition_id").notNull(),type:me("type").$type().notNull(),status:me("status").$type().notNull(),startedAt:me("started_at"),completedAt:me("completed_at"),output:me("output",{mode:"json"}).$type(),error:me("error"),childJobIds:me("child_job_ids",{mode:"json"}).$type(),parentStepExecutionId:me("parent_step_execution_id").references(()=>pt.id),iterationIndex:xd("iteration_index")},r=>[As("job_step_executions_job_id_idx").on(r.jobId),As("job_step_executions_parent_idx").on(r.parentStepExecutionId)])});import{index as Id,integer as jd,sqliteTable as _d,text as Xe}from"drizzle-orm/sqlite-core";var Ye,Ro=l(()=>{"use strict";Ye=_d("schedules",{id:Xe("id").primaryKey(),viewId:Xe("view_id").notNull(),triggerType:Xe("trigger_type",{enum:["cron"]}).notNull(),cadence:Xe("cadence").notNull(),notificationOverride:Xe("notification_override",{mode:"json"}).$type(),missedFirePolicy:Xe("missed_fire_policy",{enum:["skip","catch_up"]}).notNull(),enabled:jd("enabled",{mode:"boolean"}).notNull(),lastFiredAt:Xe("last_fired_at"),createdAt:Xe("created_at").notNull()},r=>[Id("schedules_enabled_idx").on(r.enabled)])});import{integer as Ed,sqliteTable as Pd,text as ir}from"drizzle-orm/sqlite-core";var Ee,ko=l(()=>{"use strict";Ee=Pd("workflow_shortcuts",{id:ir("id").primaryKey(),name:ir("name").notNull(),workflowId:ir("workflow_id").notNull(),inputValues:ir("input_values",{mode:"json"}).$type().notNull(),lastJobId:ir("last_job_id"),order:Ed("order").notNull().default(0)})});import{sqliteTable as Rd,text as sr}from"drizzle-orm/sqlite-core";var Ze,Ao=l(()=>{"use strict";Ze=Rd("context_files",{id:sr("id").primaryKey(),name:sr("name").notNull(),description:sr("description"),tier:sr("tier").$type().notNull(),path:sr("path").notNull()})});import{sqliteTable as kd,text as Or}from"drizzle-orm/sqlite-core";var et,Co=l(()=>{"use strict";et=kd("local_repositories",{id:Or("id").primaryKey(),name:Or("name").notNull(),localPath:Or("local_path").notNull(),worktreeBasePath:Or("worktree_base_path")})});import{sqliteTable as Ad,text as Cs}from"drizzle-orm/sqlite-core";var ar,Ct,To=l(()=>{"use strict";ar="default",Ct=Ad("settings",{id:Cs("id").primaryKey(),data:Cs("data",{mode:"json"}).$type().notNull()})});import{defineRelations as Cd}from"drizzle-orm";var Td,Ts,Os=l(()=>{"use strict";jo();_o();nr();Eo();Po();Cr();Ro();ko();Ao();Co();To();Td={workflowDefinitions:Ge,subjectViews:Ie,jobs:L,jobSubjects:_e,jobStepExecutions:pt,jobBatches:Qe,schedules:Ye,workflowShortcuts:Ee,contextFiles:Ze,localRepositories:et,settings:Ct},Ts=Cd(Td,r=>({workflowDefinitions:{},subjectViews:{},schedules:{},workflowShortcuts:{},contextFiles:{},localRepositories:{},settings:{},jobs:{subjects:r.many.jobSubjects({from:r.jobs.id,to:r.jobSubjects.jobId}),stepExecutions:r.many.jobStepExecutions({from:r.jobs.id,to:r.jobStepExecutions.jobId}),batch:r.one.jobBatches({from:r.jobs.batchId,to:r.jobBatches.id})},jobSubjects:{job:r.one.jobs({from:r.jobSubjects.jobId,to:r.jobs.id})},jobStepExecutions:{job:r.one.jobs({from:r.jobStepExecutions.jobId,to:r.jobs.id}),parent:r.one.jobStepExecutions({from:r.jobStepExecutions.parentStepExecutionId,to:r.jobStepExecutions.id,alias:"job_step_executions_parent"}),children:r.many.jobStepExecutions({from:r.jobStepExecutions.id,to:r.jobStepExecutions.parentStepExecutionId,alias:"job_step_executions_children"})},jobBatches:{jobs:r.many.jobs({from:r.jobBatches.id,to:r.jobs.batchId})}}))});import{drizzle as Od}from"drizzle-orm/node-sqlite";import{DatabaseSync as ab}from"node:sqlite";function $s(r){return r.exec("PRAGMA foreign_keys = ON;"),Od({client:r,relations:Ts})}var qs=l(()=>{"use strict";Os()});import{existsSync as Bs,readdirSync as $d}from"node:fs";import{dirname as qd,join as Oo}from"node:path";import{fileURLToPath as Bd}from"node:url";function Ds(){let r=qd(Bd(import.meta.url)),e=[Oo(r,"persistence/migrations"),Oo(r,"migrations")];for(let t of e)if(Dd(t))return t;throw new Error(`Engine SQL migrations not found. Looked in: ${e.join(", ")}`)}function Dd(r){return Bs(r)?$d(r,{withFileTypes:!0}).some(e=>e.isDirectory()&&Bs(Oo(r,e.name,"migration.sql"))):!1}var Fs=l(()=>{"use strict"});import{migrate as Ns}from"drizzle-orm/node-sqlite/migrator";import{readMigrationFiles as Fd}from"drizzle-orm/migrator";function qo(r,e,t={}){let n=t.log??(()=>{}),o=Ds(),i=Fd({migrationsFolder:o});if(i.length===0)throw new he(`No SQL migrations in ${o}`);let s=Jd(i),a=lr(r,ft),u=Nd.filter(S=>lr(r,S));if(!a&&u.length===0){Ns(e,{migrationsFolder:o}),$o(r,s);return}if(!a){Wd(r,s,n),Vd(r,i),$o(r,s);return}Hd(r,i);let c=Ls(r,s),p=Us(r);if(p.length===0&&u.length>0)throw new he("migrations table exists but is empty while application tables are present \u2014 treating this as an interrupted update");let m=new Set(p.map(S=>S.name).filter(S=>S!=null&&S!==""));if(i.filter(S=>!m.has(S.name)).length===0&&c.length>0)throw new he(`migrations journal is present but the schema is incomplete (${c.join("; ")}) \u2014 treating this as an interrupted update`);Ns(e,{migrationsFolder:o}),$o(r,s)}function Jd(r){let e=[],t=[],n=[];for(let o of r)for(let i of o.sql){let s=i.trim().replace(/;+\s*$/,"");if(!s)continue;let a=Ld(s);if(a){e.push(a);continue}let u=Ud(s);if(u){n.push(u);continue}let c=Md(s);c&&t.push(c)}return{tables:e,indexes:t,alterColumns:n}}function Ld(r){let e=r.match(/^CREATE TABLE\s+(`[^`]+`|"[^"]+"|\w+)\s*\(/i);if(!e)return null;let t=r.indexOf("("),n=r.lastIndexOf(")");if(t<0||n<t)return null;let o=[];for(let i of r.slice(t+1,n).split(`
|
|
3
|
+
`)){let s=i.trim().replace(/,+\s*$/,"");if(!s||/^(CONSTRAINT|PRIMARY KEY|UNIQUE|FOREIGN KEY|CHECK)\b/i.test(s))continue;let a=s.match(/^(`[^`]+`|"[^"]+"|\w+)\s+(\w+)/);a&&o.push({name:ur(a[1]),type:a[2]})}return{name:ur(e[1]),createSql:`${r};`,columns:o}}function Ud(r){let e=r.match(/^ALTER TABLE\s+(`[^`]+`|"[^"]+"|\w+)\s+ADD(?:\s+COLUMN)?\s+(`[^`]+`|"[^"]+"|\w+)\s+(\w+)/i);return e?{table:ur(e[1]),name:ur(e[2]),type:e[3]}:null}function Md(r){let e=r.match(/^CREATE INDEX\s+(?:IF NOT EXISTS\s+)?(`[^`]+`|"[^"]+"|\w+)/i);if(!e)return null;let t=/^CREATE INDEX\s+IF NOT EXISTS\b/i.test(r)?r:r.replace(/^CREATE INDEX\b/i,"CREATE INDEX IF NOT EXISTS");return{name:ur(e[1]),sql:`${t};`}}function ur(r){return r.replace(/^["`]|["`]$/g,"")}function cr(r){return`\`${r.replace(/`/g,"")}\``}function Wd(r,e,t){t("Legacy push-mode database detected (application tables present, no migration journal). Reconciling schema in place.");let n=[],o=[],i=[];r.exec("BEGIN");try{for(let s of e.tables){if(!lr(r,s.name)){r.exec(s.createSql),n.push(s.name);continue}let a=new Set($r(r,s.name));for(let u of s.columns)a.has(u.name)||(r.exec(`ALTER TABLE ${cr(s.name)} ADD COLUMN ${cr(u.name)} ${u.type}`),a.add(u.name),o.push(`${s.name}.${u.name}`))}for(let s of e.alterColumns)lr(r,s.table)&&($r(r,s.table).includes(s.name)||(r.exec(`ALTER TABLE ${cr(s.table)} ADD COLUMN ${cr(s.name)} ${s.type}`),o.push(`${s.table}.${s.name}`)));for(let s of e.indexes)Js(r,s.name)||(r.exec(s.sql),i.push(s.name));r.exec("COMMIT")}catch(s){throw r.exec("ROLLBACK"),s}for(let s of n)t(`Reconciliation: created table '${s}'`);for(let s of o)t(`Reconciliation: added column ${s}`);for(let s of i)t(`Reconciliation: created index '${s}'`);n.length===0&&o.length===0&&i.length===0&&t("Reconciliation: schema already matched the current baseline; nothing to add."),t("Reconciliation complete. Recording baseline as applied; future startups use normal migrations.")}function lr(r,e){return r.prepare("SELECT 1 AS ok FROM sqlite_master WHERE type = 'table' AND name = ?").get(e)!=null}function Js(r,e){return r.prepare("SELECT 1 AS ok FROM sqlite_master WHERE type = 'index' AND name = ?").get(e)!=null}function $r(r,e){return r.prepare(`PRAGMA table_info(${cr(e)})`).all().map(n=>n.name)}function Ls(r,e){let t=[],n=new Map;for(let o of e.tables)n.set(o.name,new Set(o.columns.map(i=>i.name)));for(let o of e.alterColumns){let i=n.get(o.table)??new Set;i.add(o.name),n.set(o.table,i)}for(let[o,i]of n){if(!lr(r,o)){t.push(`missing table '${o}'`);continue}let s=new Set($r(r,o));for(let a of i)s.has(a)||t.push(`table '${o}' is missing column '${a}'`)}for(let o of e.indexes)Js(r,o.name)||t.push(`missing index '${o.name}'`);return t}function $o(r,e){let t=Ls(r,e);if(t.length>0)throw new he(`schema is incomplete after migrate (${t.join("; ")})`)}function Us(r){let e=new Set($r(r,ft));if(!e.has("hash"))throw new he(`migrations table '${ft}' is missing required columns`);if(!e.has("name"))throw new he(`migrations table '${ft}' is missing column 'name' \u2014 journal is from an interrupted upgrade`);return r.prepare(`SELECT name, hash FROM ${ft}`).all()}function Hd(r,e){let t=new Map(e.map(n=>[n.name,n]));for(let n of Us(r)){if(n.name==null||n.name==="")throw new he("migrations journal has a row with no name \u2014 treating this as an interrupted update");let o=t.get(n.name);if(!o)throw new he(`database has unknown migration '${n.name}' that is not in this Engine build`);if(n.hash!=null&&n.hash!==o.hash)throw new he(`migration '${n.name}' hash does not match this Engine build \u2014 treating this as a corrupt or interrupted update`)}}function Vd(r,e){r.exec(`
|
|
4
|
+
CREATE TABLE IF NOT EXISTS ${ft} (
|
|
5
5
|
id INTEGER PRIMARY KEY,
|
|
6
6
|
hash text NOT NULL,
|
|
7
7
|
created_at numeric,
|
|
8
8
|
name text,
|
|
9
9
|
applied_at TEXT
|
|
10
10
|
)
|
|
11
|
-
`);let t=r.prepare(`INSERT INTO ${dt} (hash, created_at, name, applied_at) VALUES (?, ?, ?, ?)`),n=new Date().toISOString();r.exec("BEGIN");try{for(let o of e)t.run(o.hash,o.folderMillis,o.name,n);r.exec("COMMIT")}catch(o){throw r.exec("ROLLBACK"),o}}var dt,he,Pp,Fs=l(()=>{"use strict";Os();dt="__drizzle_migrations",he=class extends Error{constructor(e){super(`Engine database migration failed: ${e}`),this.name="DatabaseMigrationError"}},Pp=["workflow_definitions","subject_views","job_batches","jobs","job_subjects","job_step_executions","schedules","workflow_shortcuts","context_files","local_repositories","settings"]});import{Injectable as Bp,Logger as Dp}from"@nestjs/common";import{mkdirSync as Fp}from"node:fs";import{dirname as Np}from"node:path";import{DatabaseSync as Ns}from"node:sqlite";var $p,qp,Bo,X,Js=l(()=>{"use strict";kr();As();Fs();$p=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},qp=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},X=Bo=class{logger=new Dp(Bo.name);sqlite;db;constructor(){let t=process.env.KNO_SQLITE_PATH??ms();t===":memory:"?this.sqlite=new Ns(":memory:"):(Fp(Np(t),{recursive:!0}),this.sqlite=new Ns(t)),this.db=ks(this.sqlite),qo(this.sqlite,this.db,{log:n=>this.logger.log(n)})}async onModuleInit(){qo(this.sqlite,this.db,{log:e=>this.logger.log(e)})}getDb(){return this.db}getSqlite(){return this.sqlite}};X=Bo=$p([Bp(),qp("design:paramtypes",[])],X)});import{Injectable as Up}from"@nestjs/common";import{eq as Ls}from"drizzle-orm";var Jp,Lp,O,ft=l(()=>{"use strict";Io();Jp=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Lp=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},O=class{db;sqlite;constructor(e,t){this.db=e,this.sqlite=t}async create(e){let t=new Date().toISOString();return await this.db.insert(Ve).values({id:e.id,name:e.name,description:e.description??null,appliesTo:e.appliesTo,subjectHandling:e.subjectHandling,inputSchema:e.inputSchema,steps:e.steps,notificationPolicy:e.notificationPolicy,createdAt:t,updatedAt:t}),await this.get(e.id)}async get(e){let t=await this.db.query.workflowDefinitions.findFirst({where:{id:e}});return t?this.toDomain(t):null}async update(e,t){let n=await this.get(e);return n?(await this.db.update(Ve).set({name:t.name??n.name,description:t.description!==void 0?t.description??null:n.description??null,appliesTo:t.appliesTo??n.appliesTo,subjectHandling:t.subjectHandling??n.subjectHandling,inputSchema:t.inputSchema??n.inputSchema,steps:t.steps??n.steps,notificationPolicy:t.notificationPolicy??n.notificationPolicy,updatedAt:new Date().toISOString()}).where(Ls(Ve.id,e)),this.get(e)):null}async list(e={}){return(e.subjectHandling?await this.db.query.workflowDefinitions.findMany({where:{subjectHandling:e.subjectHandling}}):await this.db.query.workflowDefinitions.findMany()).map(n=>this.toDomain(n))}async delete(e){if(!await this.get(e))return!1;try{this.sqlite?.exec("PRAGMA foreign_keys = OFF"),await this.db.delete(Ve).where(Ls(Ve.id,e))}finally{this.sqlite?.exec("PRAGMA foreign_keys = ON")}return!0}toDomain(e){return{id:e.id,name:e.name,...e.description!=null?{description:e.description}:{},appliesTo:e.appliesTo,subjectHandling:e.subjectHandling,inputSchema:e.inputSchema,steps:e.steps,notificationPolicy:e.notificationPolicy}}};O=Jp([Up(),Lp("design:paramtypes",[Object,Function])],O)});import{Injectable as Hp}from"@nestjs/common";import{eq as Do}from"drizzle-orm";var Mp,Wp,Us,ie,qr=l(()=>{"use strict";_o();Mp=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Wp=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},Us=["ticket","pull_request","documentation"],ie=class{db;constructor(e){this.db=e}async create(e){let t=await this.nextOrder(e.subjectType);return await this.db.insert(ve).values({id:e.id,name:e.name,subjectType:e.subjectType,workflowId:e.workflowId,query:e.query,description:e.description??null,queryTemplate:e.queryTemplate??null,providerInstanceId:e.providerInstanceId,order:t}),await this.get(e.id)}async get(e){let t=await this.db.query.subjectViews.findFirst({where:{id:e}});return t?this.toDomain(t):null}async update(e,t){let n=await this.get(e);if(!n)return null;let o=t.queryTemplate!==void 0?t.queryTemplate:t.query!==void 0?void 0:n.queryTemplate;return await this.db.update(ve).set({name:t.name??n.name,subjectType:t.subjectType??n.subjectType,workflowId:t.workflowId??n.workflowId,query:t.query??n.query,description:t.description!==void 0?t.description??null:n.description??null,queryTemplate:o??null,providerInstanceId:t.providerInstanceId??n.providerInstanceId}).where(Do(ve.id,e)),this.get(e)}async list(e={}){let t=e.subjectType?await this.db.query.subjectViews.findMany({where:{subjectType:e.subjectType}}):await this.db.query.subjectViews.findMany();return this.sortViews(t.map(n=>this.toDomain(n)))}async reorder(e){let t=[];for(let o of e){let i=await this.get(o);if(!i)return[];t.push(i)}let n=t[0].subjectType;if(!t.every(o=>o.subjectType===n))return[];for(let o=0;o<e.length;o+=1)await this.db.update(ve).set({order:o}).where(Do(ve.id,e[o]));return this.list({subjectType:n})}async delete(e){return await this.get(e)?(await this.db.delete(ve).where(Do(ve.id,e)),!0):!1}async nextOrder(e){let t=await this.db.query.subjectViews.findMany({where:{subjectType:e}});return t.length===0?0:Math.max(...t.map(n=>n.order))+1}sortViews(e){return[...e].sort((t,n)=>{let o=Us.indexOf(t.subjectType)-Us.indexOf(n.subjectType);return o!==0?o:t.order-n.order})}toDomain(e){return{id:e.id,name:e.name,subjectType:e.subjectType,workflowId:e.workflowId,providerInstanceId:e.providerInstanceId,query:e.query,order:e.order,...e.description!=null?{description:e.description}:{},...e.queryTemplate!=null?{queryTemplate:e.queryTemplate}:{}}}};ie=Mp([Hp(),Wp("design:paramtypes",[Object])],ie)});import{Injectable as Gp}from"@nestjs/common";import{and as zp,desc as Qp,eq as ur,inArray as Xp}from"drizzle-orm";import{randomUUID as Yp}from"node:crypto";function Zp(r){return r?r.mode==="single"?[r.subject]:r.subjects:[]}function ed(r){if(r.length!==0)return r.length===1?{mode:"single",subject:r[0]}:{mode:"collection",subjects:r}}function Ws(r,e,t=null,n=null){let o=[];for(let i of e)if(o.push({id:i.id,jobId:r,stepDefinitionId:i.stepDefinitionId,type:i.type,status:i.status,startedAt:i.startedAt??null,completedAt:i.completedAt??null,output:i.output??null,error:i.error??null,childJobIds:i.childJobIds??null,parentStepExecutionId:t,iterationIndex:n}),i.iterations)for(let s of i.iterations)o.push(...Ws(r,s.stepExecutions,i.id,s.index));return o}function td(r){let e=new Map;for(let o of r){let i=o.parentStepExecutionId,s=e.get(i)??[];s.push(o),e.set(i,s)}let t=o=>{let i=e.get(o)??[];if(i.length===0)return;let s=new Map;for(let a of i){if(a.iterationIndex==null)continue;let u=s.get(a.iterationIndex)??[];u.push(a),s.set(a.iterationIndex,u)}if(s.size!==0)return[...s.entries()].sort(([a],[u])=>a-u).map(([a,u])=>{let c=u.map(d=>Ms(d,t(d.id)));return{index:a,stepExecutions:c,startedAt:rd(c),...od(c)?{completedAt:nd(c)}:{}}})};return(e.get(null)??[]).filter(o=>o.iterationIndex==null).map(o=>Ms(o,t(o.id)))}function Ms(r,e){return{id:r.id,stepDefinitionId:r.stepDefinitionId,type:r.type,status:r.status,...r.startedAt!=null?{startedAt:r.startedAt}:{},...r.completedAt!=null?{completedAt:r.completedAt}:{},...r.output!==null&&r.output!==void 0?{output:r.output}:{},...r.error!=null?{error:r.error}:{},...r.childJobIds!=null?{childJobIds:r.childJobIds}:{},...e&&e.length>0?{iterations:e}:{}}}function rd(r){let e=r.map(t=>t.startedAt).filter(t=>t!=null);return e.length===0?"":e.reduce((t,n)=>t<n?t:n)}function nd(r){return r.map(t=>t.completedAt).filter(t=>t!=null).reduce((t,n)=>t>n?t:n)}function od(r){return r.length>0&&r.every(e=>e.completedAt!=null)}function id(r){return r==="completed"||r==="failed"||r==="cancelled"}var Vp,Kp,z,lr=l(()=>{"use strict";tr();Po();Ro();Vp=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Kp=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},z=class{db;sqlite;constructor(e,t){this.db=e,this.sqlite=t}async create(e){return await this.withoutForeignKeys(async()=>{await this.db.insert(L).values(this.jobToRow(e)),await this.replaceSubjects(e.id,e.subjectContext),await this.replaceStepExecutions(e.id,e.stepHistory)}),await this.get(e.id)}async get(e){let t=await this.db.query.jobs.findFirst({where:{id:e},with:{subjects:!0,stepExecutions:!0}});return t?this.toDomain(t,t.subjects,t.stepExecutions):null}async update(e,t){let n=await this.get(e);if(!n)return null;let o={...n,...t,id:e,context:t.context??n.context,stepHistory:t.stepHistory??n.stepHistory,updatedAt:t.updatedAt??new Date().toISOString()};return await this.withoutForeignKeys(async()=>{await this.db.update(L).set({workflowId:o.workflowId,status:o.status,selection:o.selection??null,batchId:o.batchId??null,parentJobId:o.parentJobId??null,parentStepExecutionId:o.parentStepExecutionId??null,fanOutIndex:o.fanOutIndex??null,retryOf:o.retryOf??null,workflowSnapshot:o.workflowSnapshot??null,context:o.context,worktreePath:o.worktreePath??null,branch:o.branch??null,worktreeDeletedAt:o.worktreeDeletedAt??null,currentStepId:o.currentStepId??null,currentStepExecutionId:o.currentStepExecutionId??null,createdAt:o.createdAt,updatedAt:o.updatedAt,completedAt:o.completedAt??null}).where(ur(L.id,e)),t.subjectContext!==void 0&&await this.replaceSubjects(e,t.subjectContext),t.stepHistory!==void 0&&await this.replaceStepExecutions(e,t.stepHistory)}),this.get(e)}async list(e={}){let t={};e.workflowId!==void 0&&(t.workflowId=e.workflowId),e.status!==void 0&&(t.status=e.status),e.batchId!==void 0&&(t.batchId=e.batchId),e.parentJobId!==void 0&&(t.parentJobId=e.parentJobId),e.parentStepExecutionId!==void 0&&(t.parentStepExecutionId=e.parentStepExecutionId);let o=(Object.keys(t).length>0?await this.db.query.jobs.findMany({where:t,with:{subjects:!0,stepExecutions:!0}}):await this.db.query.jobs.findMany({with:{subjects:!0,stepExecutions:!0}})).map(s=>this.toDomain(s,s.subjects,s.stepExecutions)),i=e.topLevelOnly?o.filter(s=>s.batchId==null&&s.parentJobId==null):o;return e.liveWorktree&&(i=i.filter(s=>s.worktreePath!=null&&s.worktreeDeletedAt==null)),e.terminal===void 0?i:i.filter(s=>id(s.status)===e.terminal)}async latestBySubject(e,t){let n={};for(let c of t)n[c]=null;if(t.length===0)return n;let o=await this.db.select({subjectId:Ie.subjectId,jobId:L.id,createdAt:L.createdAt}).from(Ie).innerJoin(L,ur(Ie.jobId,L.id)).where(zp(ur(L.workflowId,e),Xp(Ie.subjectId,t))).orderBy(Qp(L.createdAt)),i=new Map;for(let c of o)i.has(c.subjectId)||i.set(c.subjectId,c.jobId);let s=[...new Set(i.values())],a=await Promise.all(s.map(c=>this.get(c))),u=new Map(a.filter(c=>c!=null).map(c=>[c.id,c]));for(let[c,d]of i)n[c]=u.get(d)??null;return n}async withoutForeignKeys(e){if(!this.sqlite){await e();return}try{this.sqlite.exec("PRAGMA foreign_keys = OFF"),await e()}finally{this.sqlite.exec("PRAGMA foreign_keys = ON")}}jobToRow(e){return{id:e.id,workflowId:e.workflowId,status:e.status,selection:e.selection??null,batchId:e.batchId??null,parentJobId:e.parentJobId??null,parentStepExecutionId:e.parentStepExecutionId??null,fanOutIndex:e.fanOutIndex??null,retryOf:e.retryOf??null,workflowSnapshot:e.workflowSnapshot??null,context:e.context,worktreePath:e.worktreePath??null,branch:e.branch??null,worktreeDeletedAt:e.worktreeDeletedAt??null,currentStepId:e.currentStepId??null,currentStepExecutionId:e.currentStepExecutionId??null,createdAt:e.createdAt,updatedAt:e.updatedAt,completedAt:e.completedAt??null}}async replaceSubjects(e,t){await this.db.delete(Ie).where(ur(Ie.jobId,e));let n=Zp(t);n.length!==0&&await this.db.insert(Ie).values(n.map(o=>({id:Yp(),jobId:e,subjectType:o.subjectType,subjectId:o.id,snapshot:o})))}async replaceStepExecutions(e,t){await this.db.delete(pt).where(ur(pt.jobId,e));let n=Ws(e,t);n.length!==0&&await this.db.insert(pt).values(n)}toDomain(e,t,n){let o=ed(t.map(s=>s.snapshot)),i=td(n);return{id:e.id,workflowId:e.workflowId,status:e.status,...o?{subjectContext:o}:{},...e.selection!=null?{selection:e.selection}:{},...e.batchId!=null?{batchId:e.batchId}:{},...e.parentJobId!=null?{parentJobId:e.parentJobId}:{},...e.parentStepExecutionId!=null?{parentStepExecutionId:e.parentStepExecutionId}:{},...e.fanOutIndex!=null?{fanOutIndex:e.fanOutIndex}:{},...e.retryOf!=null?{retryOf:e.retryOf}:{},...e.workflowSnapshot!=null?{workflowSnapshot:e.workflowSnapshot}:{},context:e.context,...e.worktreePath!=null?{worktreePath:e.worktreePath}:{},...e.branch!=null?{branch:e.branch}:{},...e.worktreeDeletedAt!=null?{worktreeDeletedAt:e.worktreeDeletedAt}:{},...e.currentStepId!=null?{currentStepId:e.currentStepId}:{},...e.currentStepExecutionId!=null?{currentStepExecutionId:e.currentStepExecutionId}:{},stepHistory:i,createdAt:e.createdAt,updatedAt:e.updatedAt,...e.completedAt!=null?{completedAt:e.completedAt}:{}}}};z=Vp([Gp(),Kp("design:paramtypes",[Object,Function])],z)});import{Injectable as cd}from"@nestjs/common";import{eq as ud}from"drizzle-orm";var sd,ad,se,Br=l(()=>{"use strict";Cr();sd=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},ad=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},se=class{db;constructor(e){this.db=e}async create(e){return await this.db.insert(Ge).values({id:e.id,workflowId:e.workflowId,selection:e.selection,resolvedSubjects:e.resolvedSubjects,status:e.status,triggeredBy:e.triggeredBy,scheduleId:e.scheduleId??null,notificationOverride:e.notificationOverride??null,notificationSent:e.notificationSent,createdAt:e.createdAt,completedAt:e.completedAt??null}),await this.get(e.id)}async get(e){let t=await this.db.query.jobBatches.findFirst({where:{id:e},with:{jobs:!0}});return t?this.toDomain(t,t.jobs.map(n=>n.id)):null}async update(e,t){let n=await this.get(e);return n?(await this.db.update(Ge).set({workflowId:t.workflowId??n.workflowId,selection:t.selection??n.selection,resolvedSubjects:t.resolvedSubjects??n.resolvedSubjects,status:t.status??n.status,triggeredBy:t.triggeredBy??n.triggeredBy,scheduleId:t.scheduleId!==void 0?t.scheduleId??null:n.scheduleId??null,notificationOverride:t.notificationOverride!==void 0?t.notificationOverride??null:n.notificationOverride??null,notificationSent:t.notificationSent??n.notificationSent,createdAt:t.createdAt??n.createdAt,completedAt:t.completedAt!==void 0?t.completedAt??null:n.completedAt??null}).where(ud(Ge.id,e)),this.get(e)):null}async list(e={}){return(e.workflowId?await this.db.query.jobBatches.findMany({where:{workflowId:e.workflowId},with:{jobs:!0}}):await this.db.query.jobBatches.findMany({with:{jobs:!0}})).map(n=>this.toDomain(n,n.jobs.map(o=>o.id)))}toDomain(e,t){return{id:e.id,workflowId:e.workflowId,selection:e.selection,resolvedSubjects:e.resolvedSubjects,jobIds:t,status:e.status,triggeredBy:e.triggeredBy,...e.scheduleId!=null?{scheduleId:e.scheduleId}:{},...e.notificationOverride!=null?{notificationOverride:e.notificationOverride}:{},notificationSent:e.notificationSent,createdAt:e.createdAt,...e.completedAt!=null?{completedAt:e.completedAt}:{}}}};se=sd([cd(),ad("design:paramtypes",[Object])],se)});import{Injectable as dd}from"@nestjs/common";import{eq as Hs}from"drizzle-orm";var ld,pd,Oe,Fo=l(()=>{"use strict";Eo();ld=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},pd=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},Oe=class{db;constructor(e){this.db=e}async create(e){return await this.db.insert(Qe).values({id:e.id,viewId:e.viewId,triggerType:e.trigger.type,cadence:e.trigger.cadence,notificationOverride:e.notificationOverride??null,missedFirePolicy:e.missedFirePolicy,enabled:e.enabled,lastFiredAt:e.lastFiredAt??null,createdAt:e.createdAt}),await this.get(e.id)}async get(e){let t=await this.db.query.schedules.findFirst({where:{id:e}});return t?this.toDomain(t):null}async update(e,t){let n=await this.get(e);if(!n)return null;let o=t.trigger??n.trigger;return await this.db.update(Qe).set({viewId:t.viewId??n.viewId,triggerType:o.type,cadence:o.cadence,notificationOverride:t.notificationOverride!==void 0?t.notificationOverride??null:n.notificationOverride??null,missedFirePolicy:t.missedFirePolicy??n.missedFirePolicy,enabled:t.enabled??n.enabled,lastFiredAt:t.lastFiredAt!==void 0?t.lastFiredAt??null:n.lastFiredAt??null,createdAt:t.createdAt??n.createdAt}).where(Hs(Qe.id,e)),this.get(e)}async list(e={}){return(e.enabled!==void 0?await this.db.query.schedules.findMany({where:{enabled:e.enabled}}):await this.db.query.schedules.findMany()).map(n=>this.toDomain(n))}async delete(e){return await this.get(e)?(await this.db.delete(Qe).where(Hs(Qe.id,e)),!0):!1}async findDue(e){return(await this.list({enabled:!0})).filter(n=>n.lastFiredAt==null||n.lastFiredAt<e)}toDomain(e){return{id:e.id,viewId:e.viewId,trigger:{type:"cron",cadence:e.cadence},...e.notificationOverride!=null?{notificationOverride:e.notificationOverride}:{},missedFirePolicy:e.missedFirePolicy,enabled:e.enabled,...e.lastFiredAt!=null?{lastFiredAt:e.lastFiredAt}:{},createdAt:e.createdAt}}};Oe=ld([dd(),pd("design:paramtypes",[Object])],Oe)});import{Injectable as hd}from"@nestjs/common";import{eq as No}from"drizzle-orm";var fd,md,$e,Jo=l(()=>{"use strict";ko();fd=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},md=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},$e=class{db;constructor(e){this.db=e}async create(e){let t=await this.nextOrder();return await this.db.insert(_e).values({id:e.id,name:e.name,workflowId:e.workflowId,inputValues:e.inputValues,lastJobId:e.lastJobId??null,order:t}),await this.get(e.id)}async get(e){let t=await this.db.query.workflowShortcuts.findFirst({where:{id:e}});return t?this.toDomain(t):null}async update(e,t){let n=await this.get(e);return n?(await this.db.update(_e).set({name:t.name??n.name,workflowId:t.workflowId??n.workflowId,inputValues:t.inputValues??n.inputValues,lastJobId:t.lastJobId!==void 0?t.lastJobId??null:n.lastJobId??null}).where(No(_e.id,e)),this.get(e)):null}async list(){return(await this.db.query.workflowShortcuts.findMany()).map(t=>this.toDomain(t)).sort((t,n)=>t.order-n.order)}async reorder(e){let t=[];for(let n of e){let o=await this.get(n);if(!o)return[];t.push(o)}for(let n=0;n<e.length;n+=1)await this.db.update(_e).set({order:n}).where(No(_e.id,e[n]));return this.list()}async delete(e){return await this.get(e)?(await this.db.delete(_e).where(No(_e.id,e)),!0):!1}async nextOrder(){let e=await this.db.query.workflowShortcuts.findMany();return e.length===0?0:Math.max(...e.map(t=>t.order))+1}toDomain(e){return{id:e.id,name:e.name,workflowId:e.workflowId,inputValues:e.inputValues,order:e.order,...e.lastJobId!=null?{lastJobId:e.lastJobId}:{}}}};$e=fd([hd(),md("design:paramtypes",[Object])],$e)});import{Injectable as gd}from"@nestjs/common";import{eq as Vs}from"drizzle-orm";var yd,wd,ae,Dr=l(()=>{"use strict";Ao();yd=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},wd=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},ae=class{db;constructor(e){this.db=e}async create(e){return await this.db.insert(Xe).values({id:e.id,name:e.name,description:e.description??null,tier:e.tier,path:e.path}),await this.get(e.id)}async get(e){let t=await this.db.query.contextFiles.findFirst({where:{id:e}});return t?this.toDomain(t):null}async update(e,t){let n=await this.get(e);return n?(await this.db.update(Xe).set({name:t.name??n.name,description:t.description!==void 0?t.description??null:n.description??null,tier:t.tier??n.tier,path:t.path??n.path}).where(Vs(Xe.id,e)),this.get(e)):null}async list(){return(await this.db.query.contextFiles.findMany()).map(t=>this.toDomain(t)).sort((t,n)=>t.name.localeCompare(n.name))}async delete(e){return await this.get(e)?(await this.db.delete(Xe).where(Vs(Xe.id,e)),!0):!1}toDomain(e){return{id:e.id,name:e.name,tier:e.tier,path:e.path,...e.description!=null&&e.description!==""?{description:e.description}:{}}}};ae=yd([gd(),wd("design:paramtypes",[Object])],ae)});import{Injectable as xd}from"@nestjs/common";import{eq as Ks}from"drizzle-orm";var bd,Sd,ce,Fr=l(()=>{"use strict";Co();bd=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Sd=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},ce=class{db;constructor(e){this.db=e}async create(e){return await this.db.insert(Ye).values({id:e.id,name:e.name,localPath:e.localPath,worktreeBasePath:e.worktreeBasePath??null}),await this.get(e.id)}async get(e){let t=await this.db.query.localRepositories.findFirst({where:{id:e}});return t?this.toDomain(t):null}async findByLocalPath(e){let n=(await this.db.query.localRepositories.findMany()).find(o=>o.localPath===e);return n?this.toDomain(n):null}async update(e,t){let n=await this.get(e);return n?(await this.db.update(Ye).set({name:t.name??n.name,localPath:t.localPath??n.localPath,worktreeBasePath:t.worktreeBasePath!==void 0?t.worktreeBasePath??null:n.worktreeBasePath??null}).where(Ks(Ye.id,e)),this.get(e)):null}async list(){return(await this.db.query.localRepositories.findMany()).map(t=>this.toDomain(t)).sort((t,n)=>t.name.localeCompare(n.name))}async delete(e){return await this.get(e)?(await this.db.delete(Ye).where(Ks(Ye.id,e)),!0):!1}toDomain(e){return{id:e.id,name:e.name,localPath:e.localPath,...e.worktreeBasePath!=null&&e.worktreeBasePath!==""?{worktreeBasePath:e.worktreeBasePath}:{}}}};ce=bd([xd(),Sd("design:paramtypes",[Object])],ce)});import{z as P}from"zod";var Gs,zs,Qs,Lo,Nr,Xs,Uo=l(()=>{"use strict";Gs=P.object({name:P.string().min(1),label:P.string().min(1),type:P.enum(["string","select"]),options:P.array(P.string()).optional(),required:P.boolean()}),zs=P.object({id:P.string().min(1),label:P.string().min(1),params:P.array(Gs)}),Qs=P.object({actionId:P.string().min(1),label:P.string().min(1),params:P.array(Gs)}),Lo=P.object({templateId:P.string().min(1),params:P.record(P.string(),P.unknown())}),Nr=P.object({params:P.record(P.string(),P.unknown())}),Xs=P.object({query:P.record(P.string(),P.unknown())})});import{z as Y}from"zod";var re,Jr,Lr,Ur,Mr,Wr=l(()=>{"use strict";Uo();re=Y.enum(["ticket","pull_request","documentation"]),Jr=Y.object({id:Y.string().min(1),name:Y.string().min(1),subjectType:re,workflowId:Y.string().min(1),providerInstanceId:Y.string().min(1),query:Y.record(Y.string(),Y.unknown()),description:Y.string().optional(),queryTemplate:Lo.optional(),order:Y.number().int().nonnegative()}),Lr=Jr.omit({order:!0}),Ur=Jr.partial().omit({id:!0,order:!0}).extend({queryTemplate:Lo.nullable().optional()}),Mr=Y.object({viewIds:Y.array(Y.string().min(1)).min(1)})});var Ys=l(()=>{"use strict";Wr()});var Zs=l(()=>{"use strict";Uo()});function vd(r){let e=r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"");return e.length>0?e:"step"}function ea(r,e){let t=e instanceof Set?e:new Set(e),n=vd(r);if(!t.has(n))return n;let o=2;for(;t.has(`${n}-${o}`);)o+=1;return`${n}-${o}`}function ta(r,e){for(let t of r)t.id&&e.push(t.id),t.type==="loop"&&Array.isArray(t.steps)&&ta(t.steps,e)}function ra(r){let e=[];ta(r,e);let t=new Map;for(let n of e)t.set(n,(t.get(n)??0)+1);return[...t.entries()].filter(([,n])=>n>1).map(([n])=>n)}function na(r){let e=new Set,t=n=>{for(let o of n)o.id&&e.add(o.id),o.type==="loop"&&Array.isArray(o.steps)&&t(o.steps)};return t(r),e}var Mo=l(()=>{"use strict"});import{z as f}from"zod";var jd,pr,Id,Ze,oa,ia,sa,aa,ca,ua,la,pa,_d,da,fa,mt,Pd,Rd,Ed,kd,Ad,Cd,Td,ma,et,ha=l(()=>{"use strict";Wr();Mo();jd=f.enum(["on_fail","on_complete","on_needs_input"]),pr=f.object({triggers:f.array(jd),messageTemplate:f.string().optional()}),Id=f.object({name:f.string().min(1),label:f.string().min(1),type:f.enum(["string","number","boolean","select","localRepository"]),options:f.array(f.string()).optional(),required:f.boolean(),defaultValue:f.unknown().optional()}),Ze=f.string().min(1),oa=f.object({type:f.literal("agent"),id:f.string().min(1),name:Ze,objective:f.string().min(1),contextFileIds:f.array(f.string().min(1)).optional(),outputFormat:f.enum(["questionnaire","confirmation","comment_suggestions","free_text"]),agentInstanceId:f.string().min(1).optional()}),ia=f.object({type:f.literal("interaction"),id:f.string().min(1),name:Ze,interaction:f.union([f.literal("questionnaire"),f.literal("confirmation"),f.literal("conversation")]),notify:f.boolean().optional()}),sa=f.object({type:f.literal("shell"),id:f.string().min(1),name:Ze,command:f.string().min(1)}),aa=f.object({type:f.literal("git"),id:f.string().min(1),name:Ze,operation:f.enum(["create_worktree","checkout","create_branch","commit","push"]),params:f.record(f.string(),f.unknown())}),ca=f.object({type:f.literal("provider_action"),id:f.string().min(1),name:Ze,action:f.enum(["get_subject","get_comments","post_comment","update_status","get_content"]),params:f.record(f.string(),f.unknown()).optional(),extendedAction:f.object({providerId:f.string().min(1),actionId:f.string().min(1),params:f.record(f.string(),f.unknown()).optional()}).optional(),target:f.object({subjectType:re,source:f.string().min(1),subjectId:f.string().min(1)}).optional()}),ua=f.object({type:f.literal("sub_workflow"),id:f.string().min(1),name:Ze,workflowId:f.string().min(1),forEach:f.literal("selection")}),la=f.discriminatedUnion("type",[f.object({type:f.literal("field_empty"),stepId:f.string().min(1),field:f.string().min(1)}),f.object({type:f.literal("field_equals"),stepId:f.string().min(1),field:f.string().min(1),value:f.unknown()})]),pa=f.discriminatedUnion("action",[f.object({action:f.literal("fail")}),f.object({action:f.literal("continue")}),f.object({action:f.literal("ask_human")})]),_d=f.object({type:f.literal("loop"),id:f.string().min(1),name:Ze,steps:f.array(f.lazy(()=>da)),until:la,maxIterations:f.number().int().nonnegative(),onMaxIterations:pa}),da=f.lazy(()=>f.discriminatedUnion("type",[aa,ca,sa,oa,ia,ua,_d])),fa=f.object({id:f.string().min(1),name:f.string().min(1),description:f.string().optional(),appliesTo:f.union([re,f.array(re),f.literal("none")]),subjectHandling:f.enum(["per-subject","collection"]),inputSchema:f.array(Id),steps:f.array(da),notificationPolicy:pr}),mt=fa.superRefine((r,e)=>{let t=ra(r.steps);t.length!==0&&e.addIssue({code:"custom",path:["steps"],message:`Duplicate step id(s): ${t.join(", ")}`})}),Pd=oa.extend({id:f.string().min(1).optional()}),Rd=ia.extend({id:f.string().min(1).optional()}),Ed=sa.extend({id:f.string().min(1).optional()}),kd=aa.extend({id:f.string().min(1).optional()}),Ad=ca.extend({id:f.string().min(1).optional()}),Cd=ua.extend({id:f.string().min(1).optional()}),Td=f.object({type:f.literal("loop"),id:f.string().min(1).optional(),name:Ze,steps:f.array(f.lazy(()=>ma)),until:la,maxIterations:f.number().int().nonnegative(),onMaxIterations:pa}),ma=f.lazy(()=>f.discriminatedUnion("type",[kd,Ad,Ed,Pd,Rd,Cd,Td])),et=fa.omit({id:!0,steps:!0}).extend({id:f.string().min(1).optional(),steps:f.array(ma)})});function Od(r){return r==="none"?[]:Array.isArray(r)?r:[r]}function ya(r,e){return Od(r).includes(e)}var wa=l(()=>{"use strict"});var ga=l(()=>{"use strict"});var ba=l(()=>{"use strict";ha();Mo();wa();ga()});import{z as ht}from"zod";var $d,Hr,Vr,Kr,Sa=l(()=>{"use strict";$d=ht.enum(["user","organization","project"]),Hr=ht.object({id:ht.string().min(1),name:ht.string().min(1),description:ht.string().optional(),tier:$d,path:ht.string().min(1)}),Vr=Hr.omit({id:!0}).extend({id:ht.string().min(1).optional()}),Kr=Hr.partial().omit({id:!0})});var xa=l(()=>{"use strict";Sa()});import{z as At}from"zod";var Gr,zr,Qr,va=l(()=>{"use strict";Gr=At.object({id:At.string().min(1),name:At.string().min(1),localPath:At.string().min(1),worktreeBasePath:At.string().min(1).optional()}),zr=Gr.omit({id:!0}).extend({id:At.string().min(1).optional()}),Qr=Gr.partial().omit({id:!0})});var ja=l(()=>{"use strict";va()});var Ia=l(()=>{"use strict"});var _a=l(()=>{"use strict";Ia()});var Pa=l(()=>{"use strict"});var Ra=l(()=>{"use strict";Pa()});import{z as Z}from"zod";var Ct,Ea=l(()=>{"use strict";Ct=Z.object({id:Z.string().min(1),viewId:Z.string().min(1),trigger:Z.object({type:Z.literal("cron"),cadence:Z.string().min(1)}),notificationOverride:Z.object({triggers:Z.array(Z.enum(["on_fail","on_complete","on_needs_input"])),messageTemplate:Z.string().optional()}).optional(),missedFirePolicy:Z.enum(["skip","catch_up"]),enabled:Z.boolean(),lastFiredAt:Z.string().optional(),createdAt:Z.string()})});var ka=l(()=>{"use strict";Ea()});import{z as ue}from"zod";var Xr,Yr,Zr,en,Aa=l(()=>{"use strict";Xr=ue.object({id:ue.string().min(1),name:ue.string().min(1),workflowId:ue.string().min(1),inputValues:ue.record(ue.string(),ue.unknown()),lastJobId:ue.string().min(1).optional(),order:ue.number().int().nonnegative()}),Yr=Xr.omit({order:!0}),Zr=Xr.partial().omit({id:!0,order:!0}),en=ue.object({shortcutIds:ue.array(ue.string().min(1)).min(1)})});var Ca=l(()=>{"use strict";Aa()});import{z as x}from"zod";function yt(r){return r.kind==="subject"}function Tt(r){return r.kind==="agent"}var qd,Ta,Oa,$a,qa,tn,rn,nn,on,sn,an,Ba,Da,Fa=l(()=>{"use strict";Wr();qd=x.enum(["jira","bitbucket","github","confluence","manual"]),Ta=x.enum(["claude","cursor"]),Oa={id:x.string().min(1),displayName:x.string().min(1),config:x.record(x.string(),x.unknown()),secretKey:x.string().min(1),expiresOn:x.string().min(1).optional()},$a=x.object({...Oa,kind:x.literal("subject"),type:qd,subjectType:re}),qa=x.object({...Oa,kind:x.literal("agent"),type:Ta}),tn=x.discriminatedUnion("kind",[$a,qa]),rn=x.object({providerInstances:x.array(tn).default([]),defaultAgentInstanceId:x.string().min(1).optional()}),nn=x.object({providerInstances:x.array(tn).optional(),defaultAgentInstanceId:x.string().min(1).nullable().optional()}),on=x.discriminatedUnion("kind",[$a.extend({defaultAgent:x.boolean().optional()}),qa.extend({defaultAgent:x.boolean().optional()})]),sn=x.object({displayName:x.string().min(1).optional(),config:x.record(x.string(),x.unknown()).optional(),secretKey:x.string().min(1).optional(),expiresOn:x.union([x.string().min(1),x.null()]).optional(),defaultAgent:x.boolean().optional()}),an=x.object({type:Ta,apiKey:x.string().min(1).optional(),instanceId:x.string().min(1).optional()}),Ba=x.object({id:x.string().min(1),displayName:x.string().min(1)}),Da={providerInstances:[]}});var Na=l(()=>{"use strict";Fa()});var Ja=l(()=>{"use strict"});var La=l(()=>{"use strict";Ja()});var C=l(()=>{"use strict";Ys();Zs();ba();xa();ja();_a();Ra();ka();Ca();Na();La()});import{Injectable as Fd}from"@nestjs/common";import{eq as Nd}from"drizzle-orm";function Jd(r,e){let t=e.providerInstances!==void 0?e.providerInstances:r.providerInstances,n=e.defaultAgentInstanceId===null?void 0:e.defaultAgentInstanceId!==void 0?e.defaultAgentInstanceId:r.defaultAgentInstanceId;return Wo({providerInstances:t,...n?{defaultAgentInstanceId:n}:{}})}function Wo(r){return{providerInstances:r.providerInstances??Da.providerInstances,...r.defaultAgentInstanceId?{defaultAgentInstanceId:r.defaultAgentInstanceId}:{}}}function Ua(r){return r.providerInstances!==void 0}var Bd,Dd,R,Pe=l(()=>{"use strict";C();To();Bd=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Dd=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},R=class{db;constructor(e){this.db=e}async get(){let e=await this.db.query.settings.findFirst({where:{id:ir}});return Wo(e?e.data:{})}async update(e){let t=Jd(await this.get(),e);return await this.db.query.settings.findFirst({where:{id:ir}})?await this.db.update(kt).set({data:t}).where(Nd(kt.id,ir)):await this.db.insert(kt).values({id:ir,data:t}),t}async replaceProviderInstances(e){return this.update({providerInstances:e})}};R=Bd([Fd(),Dd("design:paramtypes",[Object])],R)});import{Module as Ud}from"@nestjs/common";var Ld,Md,Re,dr=l(()=>{"use strict";Js();ft();qr();lr();Br();Fo();Jo();Dr();Fr();Pe();Ld=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Md=[O,ie,z,se,Oe,$e,ae,ce,R],Re=class{};Re=Ld([Ud({providers:[X,{provide:O,useFactory:r=>new O(r.getDb(),r.getSqlite()),inject:[X]},{provide:ie,useFactory:r=>new ie(r.getDb()),inject:[X]},{provide:z,useFactory:r=>new z(r.getDb(),r.getSqlite()),inject:[X]},{provide:se,useFactory:r=>new se(r.getDb()),inject:[X]},{provide:Oe,useFactory:r=>new Oe(r.getDb()),inject:[X]},{provide:$e,useFactory:r=>new $e(r.getDb()),inject:[X]},{provide:ae,useFactory:r=>new ae(r.getDb()),inject:[X]},{provide:ce,useFactory:r=>new ce(r.getDb()),inject:[X]},{provide:R,useFactory:r=>new R(r.getDb()),inject:[X]}],exports:[X,...Md]})],Re)});import{Injectable as Vd,Logger as Kd,Inject as Wa}from"@nestjs/common";async function Ha(r,e){let t=[];for(let n of e){let o=await r.get(n.secretKey);t.push({providerId:n.id,secretKey:n.secretKey,configured:typeof o=="string"&&o.length>0})}return t}async function Gd(r,e,t){let n=await Ha(r,e);for(let o of n)o.configured||t(`Provider instance '${o.providerId}' API key not configured (looked up as '${o.secretKey}'). GET /api/providers/status lists what's missing; store a key with: POST /api/secrets/${o.secretKey} or npm --workspace apps/engine run set-secret -- ${o.secretKey} <value>`)}var Wd,Hd,Ma,Ho,tt,Vo=l(()=>{"use strict";Pe();Te();Wd=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Hd=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},Ma=function(r,e){return function(t,n){e(t,n,r)}};tt=Ho=class{secrets;settings;logger=new Kd(Ho.name);constructor(e,t){this.secrets=e,this.settings=t}async onModuleInit(){let e=await this.settings.get();await Gd(this.secrets,e.providerInstances??[],t=>this.logger.warn(t))}async list(){let e=await this.settings.get();return Ha(this.secrets,e.providerInstances??[])}};tt=Ho=Wd([Vd(),Ma(0,Wa(fe)),Ma(1,Wa(R)),Hd("design:paramtypes",[Function,R])],tt)});function cn(r,e=Rt(r)){let t=Yd[r]??r;return new Error(`${t} API key not configured \u2014 set '${e}' via the setup script`)}function Va(r){let e=new Map;for(let n of r){let o=n.content.trim();if(!o)continue;let i=e.get(n.tier)??[];i.push(o),e.set(n.tier,i)}let t=[];for(let n of Qd){let o=e.get(n);o?.length&&t.push(`## ${zd[n]}
|
|
11
|
+
`);let t=r.prepare(`INSERT INTO ${ft} (hash, created_at, name, applied_at) VALUES (?, ?, ?, ?)`),n=new Date().toISOString();r.exec("BEGIN");try{for(let o of e)t.run(o.hash,o.folderMillis,o.name,n);r.exec("COMMIT")}catch(o){throw r.exec("ROLLBACK"),o}}var ft,he,Nd,Ms=l(()=>{"use strict";Fs();ft="__drizzle_migrations",he=class extends Error{constructor(e){super(`Engine database migration failed: ${e}`),this.name="DatabaseMigrationError"}},Nd=["workflow_definitions","subject_views","job_batches","jobs","job_subjects","job_step_executions","schedules","workflow_shortcuts","context_files","local_repositories","settings"]});import{Injectable as zd,Logger as Qd}from"@nestjs/common";import{mkdirSync as Xd}from"node:fs";import{dirname as Yd}from"node:path";import{DatabaseSync as Ws}from"node:sqlite";var Kd,Gd,Bo,Y,Hs=l(()=>{"use strict";kr();qs();Ms();Kd=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Gd=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},Y=Bo=class{logger=new Qd(Bo.name);sqlite;db;constructor(){let t=process.env.KNO_SQLITE_PATH??bs();t===":memory:"?this.sqlite=new Ws(":memory:"):(Xd(Yd(t),{recursive:!0}),this.sqlite=new Ws(t)),this.db=$s(this.sqlite),qo(this.sqlite,this.db,{log:n=>this.logger.log(n)})}async onModuleInit(){qo(this.sqlite,this.db,{log:e=>this.logger.log(e)})}getDb(){return this.db}getSqlite(){return this.sqlite}};Y=Bo=Kd([zd(),Gd("design:paramtypes",[])],Y)});import{Injectable as tp}from"@nestjs/common";import{eq as Vs}from"drizzle-orm";var Zd,ep,O,mt=l(()=>{"use strict";jo();Zd=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},ep=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},O=class{db;sqlite;constructor(e,t){this.db=e,this.sqlite=t}async create(e){let t=new Date().toISOString();return await this.db.insert(Ge).values({id:e.id,name:e.name,description:e.description??null,appliesTo:e.appliesTo,subjectHandling:e.subjectHandling,inputSchema:e.inputSchema,steps:e.steps,notificationPolicy:e.notificationPolicy,createdAt:t,updatedAt:t}),await this.get(e.id)}async get(e){let t=await this.db.query.workflowDefinitions.findFirst({where:{id:e}});return t?this.toDomain(t):null}async update(e,t){let n=await this.get(e);return n?(await this.db.update(Ge).set({name:t.name??n.name,description:t.description!==void 0?t.description??null:n.description??null,appliesTo:t.appliesTo??n.appliesTo,subjectHandling:t.subjectHandling??n.subjectHandling,inputSchema:t.inputSchema??n.inputSchema,steps:t.steps??n.steps,notificationPolicy:t.notificationPolicy??n.notificationPolicy,updatedAt:new Date().toISOString()}).where(Vs(Ge.id,e)),this.get(e)):null}async list(e={}){return(e.subjectHandling?await this.db.query.workflowDefinitions.findMany({where:{subjectHandling:e.subjectHandling}}):await this.db.query.workflowDefinitions.findMany()).map(n=>this.toDomain(n))}async delete(e){if(!await this.get(e))return!1;try{this.sqlite?.exec("PRAGMA foreign_keys = OFF"),await this.db.delete(Ge).where(Vs(Ge.id,e))}finally{this.sqlite?.exec("PRAGMA foreign_keys = ON")}return!0}toDomain(e){return{id:e.id,name:e.name,...e.description!=null?{description:e.description}:{},appliesTo:e.appliesTo,subjectHandling:e.subjectHandling,inputSchema:e.inputSchema,steps:e.steps,notificationPolicy:e.notificationPolicy}}};O=Zd([tp(),ep("design:paramtypes",[Object,Function])],O)});import{Injectable as op}from"@nestjs/common";import{eq as Do}from"drizzle-orm";var rp,np,Ks,ie,qr=l(()=>{"use strict";_o();rp=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},np=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},Ks=["ticket","pull_request","documentation"],ie=class{db;constructor(e){this.db=e}async create(e){let t=await this.nextOrder(e.subjectType);return await this.db.insert(Ie).values({id:e.id,name:e.name,subjectType:e.subjectType,workflowId:e.workflowId,query:e.query,description:e.description??null,queryTemplate:e.queryTemplate??null,providerInstanceId:e.providerInstanceId,order:t}),await this.get(e.id)}async get(e){let t=await this.db.query.subjectViews.findFirst({where:{id:e}});return t?this.toDomain(t):null}async update(e,t){let n=await this.get(e);if(!n)return null;let o=t.queryTemplate!==void 0?t.queryTemplate:t.query!==void 0?void 0:n.queryTemplate;return await this.db.update(Ie).set({name:t.name??n.name,subjectType:t.subjectType??n.subjectType,workflowId:t.workflowId??n.workflowId,query:t.query??n.query,description:t.description!==void 0?t.description??null:n.description??null,queryTemplate:o??null,providerInstanceId:t.providerInstanceId??n.providerInstanceId}).where(Do(Ie.id,e)),this.get(e)}async list(e={}){let t=e.subjectType?await this.db.query.subjectViews.findMany({where:{subjectType:e.subjectType}}):await this.db.query.subjectViews.findMany();return this.sortViews(t.map(n=>this.toDomain(n)))}async reorder(e){let t=[];for(let o of e){let i=await this.get(o);if(!i)return[];t.push(i)}let n=t[0].subjectType;if(!t.every(o=>o.subjectType===n))return[];for(let o=0;o<e.length;o+=1)await this.db.update(Ie).set({order:o}).where(Do(Ie.id,e[o]));return this.list({subjectType:n})}async delete(e){return await this.get(e)?(await this.db.delete(Ie).where(Do(Ie.id,e)),!0):!1}async nextOrder(e){let t=await this.db.query.subjectViews.findMany({where:{subjectType:e}});return t.length===0?0:Math.max(...t.map(n=>n.order))+1}sortViews(e){return[...e].sort((t,n)=>{let o=Ks.indexOf(t.subjectType)-Ks.indexOf(n.subjectType);return o!==0?o:t.order-n.order})}toDomain(e){return{id:e.id,name:e.name,subjectType:e.subjectType,workflowId:e.workflowId,providerInstanceId:e.providerInstanceId,query:e.query,order:e.order,...e.description!=null?{description:e.description}:{},...e.queryTemplate!=null?{queryTemplate:e.queryTemplate}:{}}}};ie=rp([op(),np("design:paramtypes",[Object])],ie)});import{Injectable as ap}from"@nestjs/common";import{and as cp,desc as up,eq as dr,inArray as lp}from"drizzle-orm";import{randomUUID as dp}from"node:crypto";function pp(r){return r?r.mode==="single"?[r.subject]:r.subjects:[]}function fp(r){if(r.length!==0)return r.length===1?{mode:"single",subject:r[0]}:{mode:"collection",subjects:r}}function zs(r,e,t=null,n=null){let o=[];for(let i of e)if(o.push({id:i.id,jobId:r,stepDefinitionId:i.stepDefinitionId,type:i.type,status:i.status,startedAt:i.startedAt??null,completedAt:i.completedAt??null,output:i.output??null,error:i.error??null,childJobIds:i.childJobIds??null,parentStepExecutionId:t,iterationIndex:n}),i.iterations)for(let s of i.iterations)o.push(...zs(r,s.stepExecutions,i.id,s.index));return o}function mp(r){let e=new Map;for(let o of r){let i=o.parentStepExecutionId,s=e.get(i)??[];s.push(o),e.set(i,s)}let t=o=>{let i=e.get(o)??[];if(i.length===0)return;let s=new Map;for(let a of i){if(a.iterationIndex==null)continue;let u=s.get(a.iterationIndex)??[];u.push(a),s.set(a.iterationIndex,u)}if(s.size!==0)return[...s.entries()].sort(([a],[u])=>a-u).map(([a,u])=>{let c=u.map(p=>Gs(p,t(p.id)));return{index:a,stepExecutions:c,startedAt:hp(c),...gp(c)?{completedAt:yp(c)}:{}}})};return(e.get(null)??[]).filter(o=>o.iterationIndex==null).map(o=>Gs(o,t(o.id)))}function Gs(r,e){return{id:r.id,stepDefinitionId:r.stepDefinitionId,type:r.type,status:r.status,...r.startedAt!=null?{startedAt:r.startedAt}:{},...r.completedAt!=null?{completedAt:r.completedAt}:{},...r.output!==null&&r.output!==void 0?{output:r.output}:{},...r.error!=null?{error:r.error}:{},...r.childJobIds!=null?{childJobIds:r.childJobIds}:{},...e&&e.length>0?{iterations:e}:{}}}function hp(r){let e=r.map(t=>t.startedAt).filter(t=>t!=null);return e.length===0?"":e.reduce((t,n)=>t<n?t:n)}function yp(r){return r.map(t=>t.completedAt).filter(t=>t!=null).reduce((t,n)=>t>n?t:n)}function gp(r){return r.length>0&&r.every(e=>e.completedAt!=null)}function wp(r){return r==="completed"||r==="failed"||r==="cancelled"}var ip,sp,z,pr=l(()=>{"use strict";nr();Eo();Po();ip=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},sp=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},z=class{db;sqlite;constructor(e,t){this.db=e,this.sqlite=t}async create(e){return await this.withoutForeignKeys(async()=>{await this.db.insert(L).values(this.jobToRow(e)),await this.replaceSubjects(e.id,e.subjectContext),await this.replaceStepExecutions(e.id,e.stepHistory)}),await this.get(e.id)}async get(e){let t=await this.db.query.jobs.findFirst({where:{id:e},with:{subjects:!0,stepExecutions:!0}});return t?this.toDomain(t,t.subjects,t.stepExecutions):null}async update(e,t){let n=await this.get(e);if(!n)return null;let o={...n,...t,id:e,context:t.context??n.context,stepHistory:t.stepHistory??n.stepHistory,updatedAt:t.updatedAt??new Date().toISOString()};return await this.withoutForeignKeys(async()=>{await this.db.update(L).set({workflowId:o.workflowId,status:o.status,selection:o.selection??null,batchId:o.batchId??null,parentJobId:o.parentJobId??null,parentStepExecutionId:o.parentStepExecutionId??null,fanOutIndex:o.fanOutIndex??null,retryOf:o.retryOf??null,workflowSnapshot:o.workflowSnapshot??null,context:o.context,worktreePath:o.worktreePath??null,branch:o.branch??null,worktreeDeletedAt:o.worktreeDeletedAt??null,currentStepId:o.currentStepId??null,currentStepExecutionId:o.currentStepExecutionId??null,createdAt:o.createdAt,updatedAt:o.updatedAt,completedAt:o.completedAt??null}).where(dr(L.id,e)),t.subjectContext!==void 0&&await this.replaceSubjects(e,t.subjectContext),t.stepHistory!==void 0&&await this.replaceStepExecutions(e,t.stepHistory)}),this.get(e)}async list(e={}){let t={};e.workflowId!==void 0&&(t.workflowId=e.workflowId),e.status!==void 0&&(t.status=e.status),e.batchId!==void 0&&(t.batchId=e.batchId),e.parentJobId!==void 0&&(t.parentJobId=e.parentJobId),e.parentStepExecutionId!==void 0&&(t.parentStepExecutionId=e.parentStepExecutionId);let o=(Object.keys(t).length>0?await this.db.query.jobs.findMany({where:t,with:{subjects:!0,stepExecutions:!0}}):await this.db.query.jobs.findMany({with:{subjects:!0,stepExecutions:!0}})).map(s=>this.toDomain(s,s.subjects,s.stepExecutions)),i=e.topLevelOnly?o.filter(s=>s.batchId==null&&s.parentJobId==null):o;return e.liveWorktree&&(i=i.filter(s=>s.worktreePath!=null&&s.worktreeDeletedAt==null)),e.terminal===void 0?i:i.filter(s=>wp(s.status)===e.terminal)}async latestBySubject(e,t){let n={};for(let c of t)n[c]=null;if(t.length===0)return n;let o=await this.db.select({subjectId:_e.subjectId,jobId:L.id,createdAt:L.createdAt}).from(_e).innerJoin(L,dr(_e.jobId,L.id)).where(cp(dr(L.workflowId,e),lp(_e.subjectId,t))).orderBy(up(L.createdAt)),i=new Map;for(let c of o)i.has(c.subjectId)||i.set(c.subjectId,c.jobId);let s=[...new Set(i.values())],a=await Promise.all(s.map(c=>this.get(c))),u=new Map(a.filter(c=>c!=null).map(c=>[c.id,c]));for(let[c,p]of i)n[c]=u.get(p)??null;return n}async withoutForeignKeys(e){if(!this.sqlite){await e();return}try{this.sqlite.exec("PRAGMA foreign_keys = OFF"),await e()}finally{this.sqlite.exec("PRAGMA foreign_keys = ON")}}jobToRow(e){return{id:e.id,workflowId:e.workflowId,status:e.status,selection:e.selection??null,batchId:e.batchId??null,parentJobId:e.parentJobId??null,parentStepExecutionId:e.parentStepExecutionId??null,fanOutIndex:e.fanOutIndex??null,retryOf:e.retryOf??null,workflowSnapshot:e.workflowSnapshot??null,context:e.context,worktreePath:e.worktreePath??null,branch:e.branch??null,worktreeDeletedAt:e.worktreeDeletedAt??null,currentStepId:e.currentStepId??null,currentStepExecutionId:e.currentStepExecutionId??null,createdAt:e.createdAt,updatedAt:e.updatedAt,completedAt:e.completedAt??null}}async replaceSubjects(e,t){await this.db.delete(_e).where(dr(_e.jobId,e));let n=pp(t);n.length!==0&&await this.db.insert(_e).values(n.map(o=>({id:dp(),jobId:e,subjectType:o.subjectType,subjectId:o.id,snapshot:o})))}async replaceStepExecutions(e,t){await this.db.delete(pt).where(dr(pt.jobId,e));let n=zs(e,t);n.length!==0&&await this.db.insert(pt).values(n)}toDomain(e,t,n){let o=fp(t.map(s=>s.snapshot)),i=mp(n);return{id:e.id,workflowId:e.workflowId,status:e.status,...o?{subjectContext:o}:{},...e.selection!=null?{selection:e.selection}:{},...e.batchId!=null?{batchId:e.batchId}:{},...e.parentJobId!=null?{parentJobId:e.parentJobId}:{},...e.parentStepExecutionId!=null?{parentStepExecutionId:e.parentStepExecutionId}:{},...e.fanOutIndex!=null?{fanOutIndex:e.fanOutIndex}:{},...e.retryOf!=null?{retryOf:e.retryOf}:{},...e.workflowSnapshot!=null?{workflowSnapshot:e.workflowSnapshot}:{},context:e.context,...e.worktreePath!=null?{worktreePath:e.worktreePath}:{},...e.branch!=null?{branch:e.branch}:{},...e.worktreeDeletedAt!=null?{worktreeDeletedAt:e.worktreeDeletedAt}:{},...e.currentStepId!=null?{currentStepId:e.currentStepId}:{},...e.currentStepExecutionId!=null?{currentStepExecutionId:e.currentStepExecutionId}:{},stepHistory:i,createdAt:e.createdAt,updatedAt:e.updatedAt,...e.completedAt!=null?{completedAt:e.completedAt}:{}}}};z=ip([ap(),sp("design:paramtypes",[Object,Function])],z)});import{Injectable as xp}from"@nestjs/common";import{eq as vp}from"drizzle-orm";var bp,Sp,se,Br=l(()=>{"use strict";Cr();bp=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Sp=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},se=class{db;constructor(e){this.db=e}async create(e){return await this.db.insert(Qe).values({id:e.id,workflowId:e.workflowId,selection:e.selection,resolvedSubjects:e.resolvedSubjects,status:e.status,triggeredBy:e.triggeredBy,scheduleId:e.scheduleId??null,notificationOverride:e.notificationOverride??null,notificationSent:e.notificationSent,createdAt:e.createdAt,completedAt:e.completedAt??null}),await this.get(e.id)}async get(e){let t=await this.db.query.jobBatches.findFirst({where:{id:e},with:{jobs:!0}});return t?this.toDomain(t,t.jobs.map(n=>n.id)):null}async update(e,t){let n=await this.get(e);return n?(await this.db.update(Qe).set({workflowId:t.workflowId??n.workflowId,selection:t.selection??n.selection,resolvedSubjects:t.resolvedSubjects??n.resolvedSubjects,status:t.status??n.status,triggeredBy:t.triggeredBy??n.triggeredBy,scheduleId:t.scheduleId!==void 0?t.scheduleId??null:n.scheduleId??null,notificationOverride:t.notificationOverride!==void 0?t.notificationOverride??null:n.notificationOverride??null,notificationSent:t.notificationSent??n.notificationSent,createdAt:t.createdAt??n.createdAt,completedAt:t.completedAt!==void 0?t.completedAt??null:n.completedAt??null}).where(vp(Qe.id,e)),this.get(e)):null}async list(e={}){return(e.workflowId?await this.db.query.jobBatches.findMany({where:{workflowId:e.workflowId},with:{jobs:!0}}):await this.db.query.jobBatches.findMany({with:{jobs:!0}})).map(n=>this.toDomain(n,n.jobs.map(o=>o.id)))}toDomain(e,t){return{id:e.id,workflowId:e.workflowId,selection:e.selection,resolvedSubjects:e.resolvedSubjects,jobIds:t,status:e.status,triggeredBy:e.triggeredBy,...e.scheduleId!=null?{scheduleId:e.scheduleId}:{},...e.notificationOverride!=null?{notificationOverride:e.notificationOverride}:{},notificationSent:e.notificationSent,createdAt:e.createdAt,...e.completedAt!=null?{completedAt:e.completedAt}:{}}}};se=bp([xp(),Sp("design:paramtypes",[Object])],se)});import{Injectable as _p}from"@nestjs/common";import{eq as Qs}from"drizzle-orm";var Ip,jp,$e,Fo=l(()=>{"use strict";Ro();Ip=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},jp=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},$e=class{db;constructor(e){this.db=e}async create(e){return await this.db.insert(Ye).values({id:e.id,viewId:e.viewId,triggerType:e.trigger.type,cadence:e.trigger.cadence,notificationOverride:e.notificationOverride??null,missedFirePolicy:e.missedFirePolicy,enabled:e.enabled,lastFiredAt:e.lastFiredAt??null,createdAt:e.createdAt}),await this.get(e.id)}async get(e){let t=await this.db.query.schedules.findFirst({where:{id:e}});return t?this.toDomain(t):null}async update(e,t){let n=await this.get(e);if(!n)return null;let o=t.trigger??n.trigger;return await this.db.update(Ye).set({viewId:t.viewId??n.viewId,triggerType:o.type,cadence:o.cadence,notificationOverride:t.notificationOverride!==void 0?t.notificationOverride??null:n.notificationOverride??null,missedFirePolicy:t.missedFirePolicy??n.missedFirePolicy,enabled:t.enabled??n.enabled,lastFiredAt:t.lastFiredAt!==void 0?t.lastFiredAt??null:n.lastFiredAt??null,createdAt:t.createdAt??n.createdAt}).where(Qs(Ye.id,e)),this.get(e)}async list(e={}){return(e.enabled!==void 0?await this.db.query.schedules.findMany({where:{enabled:e.enabled}}):await this.db.query.schedules.findMany()).map(n=>this.toDomain(n))}async delete(e){return await this.get(e)?(await this.db.delete(Ye).where(Qs(Ye.id,e)),!0):!1}async findDue(e){return(await this.list({enabled:!0})).filter(n=>n.lastFiredAt==null||n.lastFiredAt<e)}toDomain(e){return{id:e.id,viewId:e.viewId,trigger:{type:"cron",cadence:e.cadence},...e.notificationOverride!=null?{notificationOverride:e.notificationOverride}:{},missedFirePolicy:e.missedFirePolicy,enabled:e.enabled,...e.lastFiredAt!=null?{lastFiredAt:e.lastFiredAt}:{},createdAt:e.createdAt}}};$e=Ip([_p(),jp("design:paramtypes",[Object])],$e)});import{Injectable as Rp}from"@nestjs/common";import{eq as No}from"drizzle-orm";var Ep,Pp,qe,Jo=l(()=>{"use strict";ko();Ep=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Pp=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},qe=class{db;constructor(e){this.db=e}async create(e){let t=await this.nextOrder();return await this.db.insert(Ee).values({id:e.id,name:e.name,workflowId:e.workflowId,inputValues:e.inputValues,lastJobId:e.lastJobId??null,order:t}),await this.get(e.id)}async get(e){let t=await this.db.query.workflowShortcuts.findFirst({where:{id:e}});return t?this.toDomain(t):null}async update(e,t){let n=await this.get(e);return n?(await this.db.update(Ee).set({name:t.name??n.name,workflowId:t.workflowId??n.workflowId,inputValues:t.inputValues??n.inputValues,lastJobId:t.lastJobId!==void 0?t.lastJobId??null:n.lastJobId??null}).where(No(Ee.id,e)),this.get(e)):null}async list(){return(await this.db.query.workflowShortcuts.findMany()).map(t=>this.toDomain(t)).sort((t,n)=>t.order-n.order)}async reorder(e){let t=[];for(let n of e){let o=await this.get(n);if(!o)return[];t.push(o)}for(let n=0;n<e.length;n+=1)await this.db.update(Ee).set({order:n}).where(No(Ee.id,e[n]));return this.list()}async delete(e){return await this.get(e)?(await this.db.delete(Ee).where(No(Ee.id,e)),!0):!1}async nextOrder(){let e=await this.db.query.workflowShortcuts.findMany();return e.length===0?0:Math.max(...e.map(t=>t.order))+1}toDomain(e){return{id:e.id,name:e.name,workflowId:e.workflowId,inputValues:e.inputValues,order:e.order,...e.lastJobId!=null?{lastJobId:e.lastJobId}:{}}}};qe=Ep([Rp(),Pp("design:paramtypes",[Object])],qe)});import{Injectable as Cp}from"@nestjs/common";import{eq as Xs}from"drizzle-orm";var kp,Ap,ae,Dr=l(()=>{"use strict";Ao();kp=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Ap=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},ae=class{db;constructor(e){this.db=e}async create(e){return await this.db.insert(Ze).values({id:e.id,name:e.name,description:e.description??null,tier:e.tier,path:e.path}),await this.get(e.id)}async get(e){let t=await this.db.query.contextFiles.findFirst({where:{id:e}});return t?this.toDomain(t):null}async update(e,t){let n=await this.get(e);return n?(await this.db.update(Ze).set({name:t.name??n.name,description:t.description!==void 0?t.description??null:n.description??null,tier:t.tier??n.tier,path:t.path??n.path}).where(Xs(Ze.id,e)),this.get(e)):null}async list(){return(await this.db.query.contextFiles.findMany()).map(t=>this.toDomain(t)).sort((t,n)=>t.name.localeCompare(n.name))}async delete(e){return await this.get(e)?(await this.db.delete(Ze).where(Xs(Ze.id,e)),!0):!1}toDomain(e){return{id:e.id,name:e.name,tier:e.tier,path:e.path,...e.description!=null&&e.description!==""?{description:e.description}:{}}}};ae=kp([Cp(),Ap("design:paramtypes",[Object])],ae)});import{Injectable as $p}from"@nestjs/common";import{eq as Ys}from"drizzle-orm";var Tp,Op,ce,Fr=l(()=>{"use strict";Co();Tp=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Op=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},ce=class{db;constructor(e){this.db=e}async create(e){return await this.db.insert(et).values({id:e.id,name:e.name,localPath:e.localPath,worktreeBasePath:e.worktreeBasePath??null}),await this.get(e.id)}async get(e){let t=await this.db.query.localRepositories.findFirst({where:{id:e}});return t?this.toDomain(t):null}async findByLocalPath(e){let n=(await this.db.query.localRepositories.findMany()).find(o=>o.localPath===e);return n?this.toDomain(n):null}async update(e,t){let n=await this.get(e);return n?(await this.db.update(et).set({name:t.name??n.name,localPath:t.localPath??n.localPath,worktreeBasePath:t.worktreeBasePath!==void 0?t.worktreeBasePath??null:n.worktreeBasePath??null}).where(Ys(et.id,e)),this.get(e)):null}async list(){return(await this.db.query.localRepositories.findMany()).map(t=>this.toDomain(t)).sort((t,n)=>t.name.localeCompare(n.name))}async delete(e){return await this.get(e)?(await this.db.delete(et).where(Ys(et.id,e)),!0):!1}toDomain(e){return{id:e.id,name:e.name,localPath:e.localPath,...e.worktreeBasePath!=null&&e.worktreeBasePath!==""?{worktreeBasePath:e.worktreeBasePath}:{}}}};ce=Tp([$p(),Op("design:paramtypes",[Object])],ce)});import{z as E}from"zod";var Zs,ea,ta,Lo,Nr,ra,Uo=l(()=>{"use strict";Zs=E.object({name:E.string().min(1),label:E.string().min(1),type:E.enum(["string","select"]),options:E.array(E.string()).optional(),required:E.boolean()}),ea=E.object({id:E.string().min(1),label:E.string().min(1),params:E.array(Zs)}),ta=E.object({actionId:E.string().min(1),label:E.string().min(1),params:E.array(Zs)}),Lo=E.object({templateId:E.string().min(1),params:E.record(E.string(),E.unknown())}),Nr=E.object({params:E.record(E.string(),E.unknown())}),ra=E.object({query:E.record(E.string(),E.unknown())})});import{z as Z}from"zod";var re,Jr,Lr,Ur,Mr,Wr=l(()=>{"use strict";Uo();re=Z.enum(["ticket","pull_request","documentation"]),Jr=Z.object({id:Z.string().min(1),name:Z.string().min(1),subjectType:re,workflowId:Z.string().min(1),providerInstanceId:Z.string().min(1),query:Z.record(Z.string(),Z.unknown()),description:Z.string().optional(),queryTemplate:Lo.optional(),order:Z.number().int().nonnegative()}),Lr=Jr.omit({order:!0}),Ur=Jr.partial().omit({id:!0,order:!0}).extend({queryTemplate:Lo.nullable().optional()}),Mr=Z.object({viewIds:Z.array(Z.string().min(1)).min(1)})});var na=l(()=>{"use strict";Wr()});var oa=l(()=>{"use strict";Uo()});function qp(r){let e=r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"");return e.length>0?e:"step"}function ia(r,e){let t=e instanceof Set?e:new Set(e),n=qp(r);if(!t.has(n))return n;let o=2;for(;t.has(`${n}-${o}`);)o+=1;return`${n}-${o}`}function sa(r,e){for(let t of r)t.id&&e.push(t.id),t.type==="loop"&&Array.isArray(t.steps)&&sa(t.steps,e)}function aa(r){let e=[];sa(r,e);let t=new Map;for(let n of e)t.set(n,(t.get(n)??0)+1);return[...t.entries()].filter(([,n])=>n>1).map(([n])=>n)}function ca(r){let e=new Set,t=n=>{for(let o of n)o.id&&e.add(o.id),o.type==="loop"&&Array.isArray(o.steps)&&t(o.steps)};return t(r),e}var Mo=l(()=>{"use strict"});import{z as f}from"zod";function Jp(r){return!!(r.path?.trim()||r.pattern?.trim())}function Sa(r){let e=[];for(let t of r)e.push(t),t.type==="loop"&&e.push(...Sa(t.steps));return e}var Bp,fr,Dp,Be,ua,la,da,pa,fa,ma,ha,ya,Fp,Np,ga,wa,ba,ht,Lp,Up,Mp,Wp,Hp,Vp,Kp,Gp,xa,tt,va=l(()=>{"use strict";Wr();Mo();Bp=f.enum(["on_fail","on_complete","on_needs_input"]),fr=f.object({triggers:f.array(Bp),messageTemplate:f.string().optional()}),Dp=f.object({name:f.string().min(1),label:f.string().min(1),type:f.enum(["string","number","boolean","select","localRepository"]),options:f.array(f.string()).optional(),required:f.boolean(),defaultValue:f.unknown().optional()}),Be=f.string().min(1),ua=f.object({type:f.literal("agent"),id:f.string().min(1),name:Be,objective:f.string().min(1),contextFileIds:f.array(f.string().min(1)).optional(),outputFormat:f.enum(["questionnaire","confirmation","comment_suggestions","free_text"]),agentInstanceId:f.string().min(1).optional()}),la=f.object({type:f.literal("interaction"),id:f.string().min(1),name:Be,interaction:f.union([f.literal("questionnaire"),f.literal("confirmation"),f.literal("conversation")]),notify:f.boolean().optional()}),da=f.object({type:f.literal("shell"),id:f.string().min(1),name:Be,command:f.string().min(1)}),pa=f.object({type:f.literal("git"),id:f.string().min(1),name:Be,operation:f.enum(["create_worktree","checkout","create_branch","commit","push"]),params:f.record(f.string(),f.unknown())}),fa=f.object({type:f.literal("provider_action"),id:f.string().min(1),name:Be,action:f.enum(["get_subject","get_comments","post_comment","update_status","get_content"]),params:f.record(f.string(),f.unknown()).optional(),extendedAction:f.object({providerId:f.string().min(1),actionId:f.string().min(1),params:f.record(f.string(),f.unknown()).optional()}).optional(),target:f.object({subjectType:re,source:f.string().min(1),subjectId:f.string().min(1)}).optional()}),ma=f.object({type:f.literal("sub_workflow"),id:f.string().min(1),name:Be,workflowId:f.string().min(1),forEach:f.literal("selection")}),ha=f.discriminatedUnion("type",[f.object({type:f.literal("field_empty"),stepId:f.string().min(1),field:f.string().min(1)}),f.object({type:f.literal("field_equals"),stepId:f.string().min(1),field:f.string().min(1),value:f.unknown()})]),ya=f.discriminatedUnion("action",[f.object({action:f.literal("fail")}),f.object({action:f.literal("continue")}),f.object({action:f.literal("ask_human")})]),Fp=f.object({type:f.literal("loop"),id:f.string().min(1),name:Be,steps:f.array(f.lazy(()=>wa)),until:ha,maxIterations:f.number().int().nonnegative(),onMaxIterations:ya}),Np=f.enum(["fail","empty","ask_human"]),ga=f.object({type:f.literal("extract"),id:f.string().min(1),name:Be,source:f.string(),path:f.string().optional(),pattern:f.string().optional(),onNoMatch:Np}),wa=f.lazy(()=>f.discriminatedUnion("type",[pa,fa,da,ua,la,ma,Fp,ga])),ba=f.object({id:f.string().min(1),name:f.string().min(1),description:f.string().optional(),appliesTo:f.union([re,f.array(re),f.literal("none")]),subjectHandling:f.enum(["per-subject","collection"]),inputSchema:f.array(Dp),steps:f.array(wa),notificationPolicy:fr}),ht=ba.superRefine((r,e)=>{let t=aa(r.steps);t.length>0&&e.addIssue({code:"custom",path:["steps"],message:`Duplicate step id(s): ${t.join(", ")}`});for(let n of Sa(r.steps))n.type==="extract"&&(Jp(n)||e.addIssue({code:"custom",path:["steps"],message:`Extract step '${n.id}' must set at least one of path or pattern`}))});Lp=ua.extend({id:f.string().min(1).optional()}),Up=la.extend({id:f.string().min(1).optional()}),Mp=da.extend({id:f.string().min(1).optional()}),Wp=pa.extend({id:f.string().min(1).optional()}),Hp=fa.extend({id:f.string().min(1).optional()}),Vp=ma.extend({id:f.string().min(1).optional()}),Kp=f.object({type:f.literal("loop"),id:f.string().min(1).optional(),name:Be,steps:f.array(f.lazy(()=>xa)),until:ha,maxIterations:f.number().int().nonnegative(),onMaxIterations:ya}),Gp=ga.extend({id:f.string().min(1).optional()}),xa=f.lazy(()=>f.discriminatedUnion("type",[Wp,Hp,Mp,Lp,Up,Vp,Kp,Gp])),tt=ba.omit({id:!0,steps:!0}).extend({id:f.string().min(1).optional(),steps:f.array(xa)})});function Ia(r){return r==="none"?[]:Array.isArray(r)?r:[r]}function ja(r,e){return Ia(r).includes(e)}var Wo=l(()=>{"use strict"});var _a=l(()=>{"use strict"});var Ea=l(()=>{"use strict";Wo()});var Pa=l(()=>{"use strict";va();Mo();Wo();_a();Ea()});import{z as yt}from"zod";var zp,Hr,Vr,Kr,Ra=l(()=>{"use strict";zp=yt.enum(["user","organization","project"]),Hr=yt.object({id:yt.string().min(1),name:yt.string().min(1),description:yt.string().optional(),tier:zp,path:yt.string().min(1)}),Vr=Hr.omit({id:!0}).extend({id:yt.string().min(1).optional()}),Kr=Hr.partial().omit({id:!0})});var ka=l(()=>{"use strict";Ra()});import{z as Tt}from"zod";var Gr,zr,Qr,Aa=l(()=>{"use strict";Gr=Tt.object({id:Tt.string().min(1),name:Tt.string().min(1),localPath:Tt.string().min(1),worktreeBasePath:Tt.string().min(1).optional()}),zr=Gr.omit({id:!0}).extend({id:Tt.string().min(1).optional()}),Qr=Gr.partial().omit({id:!0})});var Ca=l(()=>{"use strict";Aa()});var Ta=l(()=>{"use strict"});var Oa=l(()=>{"use strict";Ta()});var $a=l(()=>{"use strict"});var qa=l(()=>{"use strict";$a()});import{z as ee}from"zod";var Ot,Ba=l(()=>{"use strict";Ot=ee.object({id:ee.string().min(1),viewId:ee.string().min(1),trigger:ee.object({type:ee.literal("cron"),cadence:ee.string().min(1)}),notificationOverride:ee.object({triggers:ee.array(ee.enum(["on_fail","on_complete","on_needs_input"])),messageTemplate:ee.string().optional()}).optional(),missedFirePolicy:ee.enum(["skip","catch_up"]),enabled:ee.boolean(),lastFiredAt:ee.string().optional(),createdAt:ee.string()})});var Da=l(()=>{"use strict";Ba()});import{z as ue}from"zod";var Xr,Yr,Zr,en,Fa=l(()=>{"use strict";Xr=ue.object({id:ue.string().min(1),name:ue.string().min(1),workflowId:ue.string().min(1),inputValues:ue.record(ue.string(),ue.unknown()),lastJobId:ue.string().min(1).optional(),order:ue.number().int().nonnegative()}),Yr=Xr.omit({order:!0}),Zr=Xr.partial().omit({id:!0,order:!0}),en=ue.object({shortcutIds:ue.array(ue.string().min(1)).min(1)})});var Na=l(()=>{"use strict";Fa()});import{z as x}from"zod";function gt(r){return r.kind==="subject"}function $t(r){return r.kind==="agent"}var Qp,Ja,La,Ua,Ma,tn,rn,nn,on,sn,an,Wa,Ha,Va=l(()=>{"use strict";Wr();Qp=x.enum(["jira","bitbucket","github","confluence","manual"]),Ja=x.enum(["claude","cursor"]),La={id:x.string().min(1),displayName:x.string().min(1),config:x.record(x.string(),x.unknown()),secretKey:x.string().min(1),expiresOn:x.string().min(1).optional()},Ua=x.object({...La,kind:x.literal("subject"),type:Qp,subjectType:re}),Ma=x.object({...La,kind:x.literal("agent"),type:Ja}),tn=x.discriminatedUnion("kind",[Ua,Ma]),rn=x.object({providerInstances:x.array(tn).default([]),defaultAgentInstanceId:x.string().min(1).optional()}),nn=x.object({providerInstances:x.array(tn).optional(),defaultAgentInstanceId:x.string().min(1).nullable().optional()}),on=x.discriminatedUnion("kind",[Ua.extend({defaultAgent:x.boolean().optional()}),Ma.extend({defaultAgent:x.boolean().optional()})]),sn=x.object({displayName:x.string().min(1).optional(),config:x.record(x.string(),x.unknown()).optional(),secretKey:x.string().min(1).optional(),expiresOn:x.union([x.string().min(1),x.null()]).optional(),defaultAgent:x.boolean().optional()}),an=x.object({type:Ja,apiKey:x.string().min(1).optional(),instanceId:x.string().min(1).optional()}),Wa=x.object({id:x.string().min(1),displayName:x.string().min(1)}),Ha={providerInstances:[]}});var Ka=l(()=>{"use strict";Va()});var Ga=l(()=>{"use strict"});var za=l(()=>{"use strict";Ga()});var C=l(()=>{"use strict";na();oa();Pa();ka();Ca();Oa();qa();Da();Na();Ka();za()});import{Injectable as Zp}from"@nestjs/common";import{eq as ef}from"drizzle-orm";function tf(r,e){let t=e.providerInstances!==void 0?e.providerInstances:r.providerInstances,n=e.defaultAgentInstanceId===null?void 0:e.defaultAgentInstanceId!==void 0?e.defaultAgentInstanceId:r.defaultAgentInstanceId;return Ho({providerInstances:t,...n?{defaultAgentInstanceId:n}:{}})}function Ho(r){return{providerInstances:r.providerInstances??Ha.providerInstances,...r.defaultAgentInstanceId?{defaultAgentInstanceId:r.defaultAgentInstanceId}:{}}}function Qa(r){return r.providerInstances!==void 0}var Xp,Yp,P,Pe=l(()=>{"use strict";C();To();Xp=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Yp=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},P=class{db;constructor(e){this.db=e}async get(){let e=await this.db.query.settings.findFirst({where:{id:ar}});return Ho(e?e.data:{})}async update(e){let t=tf(await this.get(),e);return await this.db.query.settings.findFirst({where:{id:ar}})?await this.db.update(Ct).set({data:t}).where(ef(Ct.id,ar)):await this.db.insert(Ct).values({id:ar,data:t}),t}async replaceProviderInstances(e){return this.update({providerInstances:e})}};P=Xp([Zp(),Yp("design:paramtypes",[Object])],P)});import{Module as nf}from"@nestjs/common";var rf,of,Re,mr=l(()=>{"use strict";Hs();mt();qr();pr();Br();Fo();Jo();Dr();Fr();Pe();rf=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},of=[O,ie,z,se,$e,qe,ae,ce,P],Re=class{};Re=rf([nf({providers:[Y,{provide:O,useFactory:r=>new O(r.getDb(),r.getSqlite()),inject:[Y]},{provide:ie,useFactory:r=>new ie(r.getDb()),inject:[Y]},{provide:z,useFactory:r=>new z(r.getDb(),r.getSqlite()),inject:[Y]},{provide:se,useFactory:r=>new se(r.getDb()),inject:[Y]},{provide:$e,useFactory:r=>new $e(r.getDb()),inject:[Y]},{provide:qe,useFactory:r=>new qe(r.getDb()),inject:[Y]},{provide:ae,useFactory:r=>new ae(r.getDb()),inject:[Y]},{provide:ce,useFactory:r=>new ce(r.getDb()),inject:[Y]},{provide:P,useFactory:r=>new P(r.getDb()),inject:[Y]}],exports:[Y,...of]})],Re)});import{Injectable as cf,Logger as uf,Inject as Ya}from"@nestjs/common";async function Za(r,e){let t=[];for(let n of e){let o=await r.get(n.secretKey);t.push({providerId:n.id,secretKey:n.secretKey,configured:typeof o=="string"&&o.length>0})}return t}async function lf(r,e,t){let n=await Za(r,e);for(let o of n)o.configured||t(`Provider instance '${o.providerId}' API key not configured (looked up as '${o.secretKey}'). GET /api/providers/status lists what's missing; store a key with: POST /api/secrets/${o.secretKey} or npm --workspace apps/engine run set-secret -- ${o.secretKey} <value>`)}var sf,af,Xa,Vo,rt,Ko=l(()=>{"use strict";Pe();Oe();sf=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},af=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},Xa=function(r,e){return function(t,n){e(t,n,r)}};rt=Vo=class{secrets;settings;logger=new uf(Vo.name);constructor(e,t){this.secrets=e,this.settings=t}async onModuleInit(){let e=await this.settings.get();await lf(this.secrets,e.providerInstances??[],t=>this.logger.warn(t))}async list(){let e=await this.settings.get();return Za(this.secrets,e.providerInstances??[])}};rt=Vo=sf([cf(),Xa(0,Ya(fe)),Xa(1,Ya(P)),af("design:paramtypes",[Function,P])],rt)});function cn(r,e=kt(r)){let t=mf[r]??r;return new Error(`${t} API key not configured \u2014 set '${e}' via the setup script`)}function ec(r){let e=new Map;for(let n of r){let o=n.content.trim();if(!o)continue;let i=e.get(n.tier)??[];i.push(o),e.set(n.tier,i)}let t=[];for(let n of pf){let o=e.get(n);o?.length&&t.push(`## ${df[n]}
|
|
12
12
|
${o.join(`
|
|
13
13
|
|
|
14
14
|
`)}`)}return t.join(`
|
|
15
15
|
|
|
16
|
-
`)}function
|
|
16
|
+
`)}function hr(r){let e=[],t=ec(r.knowledge);return t&&e.push(t),e.push(`# Objective
|
|
17
17
|
${r.objective}`),e.push(`# Output format
|
|
18
|
-
${
|
|
18
|
+
${ff[r.outputFormat]}`),e.join(`
|
|
19
19
|
|
|
20
|
-
`)}function
|
|
21
|
-
`).map(t=>({type:"paragraph",content:t.length===0?[]:[{type:"text",text:t}]}))}}function
|
|
22
|
-
`;let t=(e.content??[]).map(
|
|
23
|
-
`:t}var Ko=l(()=>{"use strict"});function cf(r,e){return e.startsWith("http://")||e.startsWith("https://")?e:`${r.replace(/\/$/,"")}${e.startsWith("/")?e:`/${e}`}`}function Za(r){return{representation:"atlas_doc_format",value:JSON.stringify(mn(r))}}function tc(r){return hr(uf(r))}function uf(r){if(r==null||typeof r!="object")return r;let e=r.atlas_doc_format;if(e!=null){if(typeof e=="object"&&e!==null&&"value"in e){let t=e.value;if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t}return e}}function ec(r,e,t){return{id:String(r.id??""),source:t,title:String(r.title??""),url:lf(e,r),raw:r}}function lf(r,e){let t=r.replace(/\/$/,""),n=e._links?.webui?.trim();if(n)return n.startsWith("http://")||n.startsWith("https://")?n:n.startsWith("/wiki")?`${t}${n}`:`${t}/wiki${n.startsWith("/")?n:`/${n}`}`;let o=e.id!=null?String(e.id):"";return o?`${t}/wiki/pages/${encodeURIComponent(o)}`:t}function pf(r,e){return{id:String(r.id??""),subjectId:e,body:tc(r.body),createdAt:r.version?.createdAt??r.createdAt??"",raw:r}}var of,sf,af,Ya,hn,yn,Go=l(()=>{"use strict";fn();Ko();of="kno.confluence.apiToken",sf=50,af=10,Ya=500,hn=[{actionId:"create_page",label:"Create Confluence page",params:[{name:"spaceKey",label:"Space key",type:"string",required:!0},{name:"title",label:"Title",type:"string",required:!0},{name:"content",label:"Content",type:"string",required:!0}]}],yn=class{secrets;fetchFn;instanceId;baseUrl;email;secretKey;constructor(e,t,n=fetch){this.secrets=e,this.fetchFn=n,this.instanceId=t.instanceId,this.baseUrl=t.baseUrl?.trim()||void 0,this.email=t.email?.trim()||void 0,this.secretKey=t.secretKey?.trim()||of}async get(e){let{baseUrl:t}=await this.requireConfig(),n=await this.request("GET",`/wiki/api/v2/pages/${encodeURIComponent(e)}`);return ec(n,t,this.instanceId)}async getContent(e){await this.requireConfig();let t=await this.request("GET",`/wiki/api/v2/pages/${encodeURIComponent(e)}?body-format=atlas_doc_format`);return tc(t.body)}async query(e){let t=e.pageIds;if(!Array.isArray(t))throw new Error("Documentation query requires { pageIds: string[] }");let n=[];for(let o of t)n.push(await this.get(String(o)));return n}async getComments(e){await this.requireConfig();let t=[],n=`/wiki/api/v2/pages/${encodeURIComponent(e)}/footer-comments?body-format=atlas_doc_format&limit=${sf}`,o=new Set;for(let i=0;i<af&&t.length<Ya&&!(!n||o.has(n));i++){o.add(n);let s=await this.request("GET",n),a=Array.isArray(s.results)?s.results:[];for(let c of a){if(t.length>=Ya)break;t.push(pf(c,e))}let u=typeof s._links?.next=="string"?s._links.next:void 0;if(!u||a.length===0)break;n=u}return t}async postComment(e,t){await this.requireConfig(),await this.request("POST","/wiki/api/v2/footer-comments",{body:{pageId:e,body:Za(t)}})}listExtendedActions(){return hn}async executeExtendedAction(e,t){if(e==="create_page")return this.createPage(t);throw new Error(`Provider 'confluence' has no extended action '${e}'. Available: ${Ot(this.listExtendedActions())}`)}async createPage(e){let t=hn[0];dn(t,e);let n=String(e.spaceKey).trim(),o=String(e.title).trim(),i=String(e.content),{baseUrl:s}=await this.requireConfig(),a=await this.resolveSpaceId(n),u=await this.request("POST","/wiki/api/v2/pages",{body:{spaceId:a,status:"current",title:o,body:Za(i)}});return ec(u,s,this.instanceId)}async resolveSpaceId(e){let t=await this.request("GET",`/wiki/api/v2/spaces?keys=${encodeURIComponent(e)}`),n=Array.isArray(t.results)?t.results:[],o=n.find(s=>(s.key??"").toLowerCase()===e.toLowerCase())??n[0],i=o?.id!=null?String(o.id):"";if(!i)throw new Error(`Confluence space '${e}' was not found`);return i}async requireConfig(){let e=this.baseUrl,t=this.email,n=await this.secrets.get(this.secretKey);if(!e||!t||!n){let o=[];throw e||o.push("config.baseUrl"),t||o.push("config.email"),n||o.push(`SecretStore '${this.secretKey}'`),new Error(`Confluence instance '${this.instanceId}' is not configured \u2014 missing ${o.join(", ")}. Set baseUrl and email on the provider instance, and store the API token with: POST /api/secrets/${this.secretKey} or npm --workspace apps/engine run set-secret -- ${this.secretKey} <value>`)}return{baseUrl:e,email:t,token:n}}async request(e,t,n={}){let{baseUrl:o,email:i,token:s}=await this.requireConfig(),a=cf(o,t),u={Authorization:`Basic ${Buffer.from(`${i}:${s}`).toString("base64")}`,Accept:"application/json"};n.body!==void 0&&(u["Content-Type"]="application/json");let c=await this.fetchFn(a,{method:e,headers:u,...n.body!==void 0?{body:JSON.stringify(n.body)}:{}});if(!c.ok){let m=await c.text().catch(()=>"");throw new Error(`Confluence ${e} ${t} failed (${c.status}): ${m||c.statusText}`)}if(c.status===204)return;let d=await c.text();if(d)return JSON.parse(d)}}});import{randomUUID as df}from"node:crypto";var ff,wn,rc=l(()=>{"use strict";ff=new Set(["github_wiki","gitlab_wiki","azure_wiki","web"]),wn=class{pages;contentById;comments;instanceId;type;constructor(e=[],t){this.pages=new Map,this.contentById=new Map,this.comments=new Map,this.instanceId=t?.instanceId,this.type=t?.type;for(let n of e){let{content:o,...i}=n;this.pages.set(i.id,structuredClone(i)),o!==void 0&&this.contentById.set(i.id,o)}}async get(e){let t=this.pages.get(e);if(!t)throw new Error(`Documentation page not found: ${e}`);return this.withSource(structuredClone(t))}async getContent(e){await this.get(e);let t=this.contentById.get(e);if(t===void 0)throw new Error(`Documentation content not found: ${e}`);return t}async query(e){let t=e.pageIds;if(!Array.isArray(t))throw new Error("Documentation query requires { pageIds: string[] }");let n=[];for(let o of t)n.push(await this.get(String(o)));return n}async getComments(e){let t=await this.get(e);return this.assertCommentsSupported(t),structuredClone(this.comments.get(e)??[])}async postComment(e,t){let n=await this.get(e);this.assertCommentsSupported(n);let o=this.comments.get(e)??[];o.push({id:df(),subjectId:e,body:t,createdAt:new Date().toISOString()}),this.comments.set(e,o)}assertCommentsSupported(e){let t=this.type??e.source;if(ff.has(t))throw new Error(`Comments are not supported for documentation source '${t}'`)}withSource(e){return this.instanceId?{...e,source:this.instanceId}:e}}});function zo(){return hf.replace(/\/$/,"")}function yr(r){let e=r.trim(),t=e.lastIndexOf("#");if(t<=0||t===e.length-1)throw new Error(`Bitbucket pull request id must be '{repoSlug}#{prNumber}' (e.g. 'kno-engine#42'), got '${r}'`);let n=e.slice(0,t),o=e.slice(t+1);if(!/^\d+$/.test(o))throw new Error(`Bitbucket pull request id must be '{repoSlug}#{prNumber}' with a numeric PR number, got '${r}'`);return{repoSlug:n,prNumber:o}}function yf(r,e){return`${r}#${e}`}function wf(r){let e=r.repoSlug;if(typeof e!="string"||e.trim().length===0)throw new Error("Bitbucket query requires filter.repoSlug or filter.role \u2014 repo-scoped listing needs repoSlug; workspace-wide listing needs role (author|reviewer)");return e.trim()}function gf(r){if(typeof r.repoSlug=="string"&&r.repoSlug.trim().length>0||!ic(r.role))return;let e=String(r.role).trim().toLowerCase();if(e!=="author"&&e!=="reviewer")throw new Error(`Bitbucket query filter.role must be 'author' or 'reviewer', got '${String(r.role)}'`);return e}function oc(r){if(!ic(r))return;let e=String(r).trim().toUpperCase();if(e!=="OPEN"&&e!=="MERGED"&&e!=="DECLINED")throw new Error(`Bitbucket query filter.state must be OPEN, MERGED, or DECLINED, got '${String(r)}'`);return e}function bf(r){if(typeof r.q=="string"&&r.q.trim().length>0)return r.q;let e=oc(r.state);if(e)return`state="${e}"`}function Sf(r){let e=r.destination?.repository?.name;if(typeof e=="string"&&e.trim().length>0)return e.trim();let t=r.destination?.repository?.full_name;if(typeof t=="string"&&t.includes("/"))return t.slice(t.lastIndexOf("/")+1);throw new Error("Bitbucket workspace pull request is missing destination.repository slug")}function xf(r){let e=r.trim().toLowerCase();if(e==="approved")return"approve";if(e==="declined"||e==="rejected")return"decline";if(e==="merged")return"merge";throw new Error(`No Bitbucket action for status '${r}'. Accepted: approved, declined/rejected, merged`)}function ic(r){return r!=null&&r!==""}function Yo(...r){for(let e of r)if(typeof e=="string"&&e.trim().length>0)return e.trim()}function gn(r,e,t){let n=String(r.id??""),o=typeof r.description=="string"?r.description:"";return{id:yf(e,n),source:t,title:String(r.title??""),...o?{description:o}:{},sourceBranch:String(r.source?.branch?.name??""),targetBranch:String(r.destination?.branch?.name??""),...r.author?.display_name?{author:r.author.display_name}:{},...r.links?.html?.href?{url:r.links.html.href}:{},raw:r}}function vf(r,e){let t=r.user?.display_name??r.author?.display_name;return{id:String(r.id??""),subjectId:e,body:r.content?.raw??"",...t?{author:t}:{},createdAt:r.created_on??"",raw:r}}var mf,hf,Qo,nc,Xo,Zo,bn,ei=l(()=>{"use strict";fn();mf="kno.bitbucket.apiToken",hf="https://api.bitbucket.org/2.0";Qo=50,nc=10,Xo=500,Zo=[{actionId:"add_reviewer",label:"Add reviewer",params:[{name:"username",label:"Reviewer username",type:"string",required:!0}]}],bn=class{secrets;fetchFn;instanceId;email;workspace;secretKey;constructor(e,t,n=fetch){this.secrets=e,this.fetchFn=n,this.instanceId=t.instanceId,this.email=t.email?.trim()||void 0,this.workspace=t.workspace?.trim()||void 0,this.secretKey=t.secretKey?.trim()||mf}async get(e){let{repoSlug:t,prNumber:n}=yr(e),{workspace:o}=await this.requireConfig(),i=await this.request("GET",this.prPath(o,t,n));return gn(i,t,this.instanceId)}async query(e){let t=gf(e);if(t)return this.queryWorkspacePullRequests(t,e);let n=wf(e),{workspace:o}=await this.requireConfig(),i=bf(e),s=new URLSearchParams({pagelen:String(Qo)});i&&s.set("q",i);let a=`${zo()}/repositories/${encodeURIComponent(o)}/${encodeURIComponent(n)}/pullrequests?${s.toString()}`;return this.collectPullRequests(a,n)}async queryWorkspacePullRequests(e,t){let{workspace:n}=await this.requireConfig(),o=await this.selectedUser(),i=new URLSearchParams({pagelen:String(Qo)}),s=oc(t.state);s&&i.set("state",s),e==="reviewer"&&i.set("role","REVIEWER");let a=`${zo()}/workspaces/${encodeURIComponent(n)}/pullrequests/${encodeURIComponent(o)}?${i.toString()}`;return this.collectPullRequests(a)}selectedUserCache;async selectedUser(){let{email:e}=await this.requireConfig();if(this.selectedUserCache?.email===e)return this.selectedUserCache.id;let t=await this.request("GET","/user"),n=Yo(t.uuid,t.account_id,t.username);if(!n)throw new Error("Bitbucket GET /user did not return uuid, account_id, or username \u2014 cannot list workspace pull requests");return this.selectedUserCache={email:e,id:n},n}async collectPullRequests(e,t){let n=[],o=new Set,i=e;for(let s=0;s<nc&&n.length<Xo&&!(!i||o.has(i));s++){o.add(i);let a=await this.request("GET",i),u=Array.isArray(a.values)?a.values:[];for(let d of u){if(n.length>=Xo)break;n.push(gn(d,t??Sf(d),this.instanceId))}let c=typeof a.next=="string"&&a.next.length>0?a.next:void 0;if(!c||u.length===0)break;i=c}return n}async getComments(e){let{repoSlug:t,prNumber:n}=yr(e),{workspace:o}=await this.requireConfig(),i=[],s=new Set,a=`${this.prPath(o,t,n)}/comments?pagelen=${Qo}`;for(let u=0;u<nc&&i.length<Xo&&!(!a||s.has(a));u++){s.add(a);let c=await this.request("GET",a),d=Array.isArray(c.values)?c.values:[];for(let b of d)i.push(vf(b,e));let m=typeof c.next=="string"&&c.next.length>0?c.next:void 0;if(!m||d.length===0)break;a=m}return i}async postComment(e,t){let{repoSlug:n,prNumber:o}=yr(e),{workspace:i}=await this.requireConfig();await this.request("POST",`${this.prPath(i,n,o)}/comments`,{body:{content:{raw:t}}})}async updateStatus(e,t){let{repoSlug:n,prNumber:o}=yr(e),{workspace:i}=await this.requireConfig(),s=xf(t);await this.request("POST",`${this.prPath(i,n,o)}/${s}`)}listExtendedActions(){return Zo}async executeExtendedAction(e,t){if(e==="add_reviewer")return this.addReviewer(t);throw new Error(`Provider 'bitbucket' has no extended action '${e}'. Available: ${Ot(this.listExtendedActions())}`)}async addReviewer(e){let t=typeof e.subjectId=="string"?e.subjectId.trim():"";if(!t)throw new Error("Bitbucket action 'add_reviewer' requires params.subjectId");let n=typeof e.username=="string"?e.username.trim():"";if(!n)throw new Error("Bitbucket action 'add_reviewer' requires params.username");let{repoSlug:o,prNumber:i}=yr(t),{workspace:s}=await this.requireConfig(),a=await this.request("GET",this.prPath(s,o,i)),u=await this.request("GET",`/users/${encodeURIComponent(n)}`),c=Yo(u.uuid),d=Yo(u.account_id);if(!c&&!d)throw new Error(`Bitbucket user '${n}' has no uuid or account_id`);let m=Array.isArray(a.reviewers)?a.reviewers:[];if(m.some(N=>c!=null&&N.uuid===c||d!=null&&N.account_id===d))return gn(a,o,this.instanceId);let S=[...m.map(N=>N.uuid?{uuid:N.uuid}:{account_id:N.account_id}),c?{uuid:c}:{account_id:d}],I=await this.request("PUT",this.prPath(s,o,i),{body:{title:a.title??"",reviewers:S}});return gn(I,o,this.instanceId)}prPath(e,t,n){return`/repositories/${encodeURIComponent(e)}/${encodeURIComponent(t)}/pullrequests/${encodeURIComponent(n)}`}async requireConfig(){let e=this.email,t=this.workspace,n=await this.secrets.get(this.secretKey);if(!e||!t||!n){let o=[];throw e||o.push("config.email"),t||o.push("config.workspace"),n||o.push(`SecretStore '${this.secretKey}'`),new Error(`Bitbucket instance '${this.instanceId}' is not configured \u2014 missing ${o.join(", ")}. Set email and workspace on the provider instance, and store the API token with: POST /api/secrets/${this.secretKey} or npm --workspace apps/engine run set-secret -- ${this.secretKey} <value>`)}return{email:e,workspace:t,token:n}}async request(e,t,n={}){let{email:o,token:i}=await this.requireConfig(),s=t.startsWith("http://")||t.startsWith("https://")?t:`${zo()}${t.startsWith("/")?t:`/${t}`}`,a={Authorization:`Basic ${Buffer.from(`${o}:${i}`).toString("base64")}`,Accept:"application/json"};n.body!==void 0&&(a["Content-Type"]="application/json");let u=await this.fetchFn(s,{method:e,headers:a,...n.body!==void 0?{body:JSON.stringify(n.body)}:{}});if(!u.ok){let d=await u.text().catch(()=>"");throw new Error(`Bitbucket ${e} ${t} failed (${u.status}): ${d||u.statusText}`)}if(u.status===204)return;let c=await u.text();if(c)return JSON.parse(c)}}});import{randomUUID as jf}from"node:crypto";function If(r,e){return Object.entries(e).every(([t,n])=>t==="status"?r.raw?.status===n:r[t]===n)}var Sn,sc=l(()=>{"use strict";Sn=class{pullRequests;comments;instanceId;constructor(e=[],t){this.pullRequests=new Map(e.map(n=>[n.id,structuredClone(n)])),this.comments=new Map,this.instanceId=t}async get(e){let t=this.pullRequests.get(e);if(!t)throw new Error(`Pull request not found: ${e}`);return this.withSource(structuredClone(t))}async query(e){return[...this.pullRequests.values()].filter(t=>If(t,e)).map(t=>this.withSource(structuredClone(t)))}async getComments(e){return await this.get(e),structuredClone(this.comments.get(e)??[])}async postComment(e,t){await this.get(e);let n=this.comments.get(e)??[];n.push({id:jf(),subjectId:e,body:t,createdAt:new Date().toISOString()}),this.comments.set(e,n)}async updateStatus(e,t){let n=this.pullRequests.get(e);if(!n)throw new Error(`Pull request not found: ${e}`);n.raw={...n.raw??{},status:t}}withSource(e){return this.instanceId?{...e,source:this.instanceId}:e}}});function ti(r){return r.pull_request!=null}function xn(r){let e=r.trim(),t=e.lastIndexOf("#");if(t<=0||t===e.length-1)throw new Error(`GitHub issue id must be '{owner}/{repo}#{issueNumber}' (e.g. 'acme/kno#42'), got '${r}'`);let n=e.slice(0,t),o=e.slice(t+1),{owner:i,name:s}=ac(n);if(!/^\d+$/.test(o))throw new Error(`GitHub issue id must be '{owner}/{repo}#{issueNumber}' (e.g. 'acme/kno#42'), got '${r}'`);return{owner:i,repo:s,issueNumber:o}}function kf(r,e,t){return`${r}/${e}#${t}`}function ac(r){let e=r.trim(),t=e.indexOf("/");if(t<=0||t===e.length-1||e.indexOf("/",t+1)!==-1)throw new Error(`GitHub repo must be '{owner}/{name}', got '${r}'`);return{owner:e.slice(0,t),name:e.slice(t+1)}}function Af(r){let e=r.role;if(e==="assignee"||e==="creator")return e}function Cf(r,e){return r==="creator"?`author:${e}`:`assignee:${e}`}function Tf(r){let e=r.trim().toLowerCase();if(e==="open")return{state:"open"};if(e==="closed"||e==="done"||e==="completed")return{state:"closed",state_reason:"completed"};if(e==="not_planned"||e==="wontfix")return{state:"closed",state_reason:"not_planned"};throw new Error(`No GitHub Issues mapping for status '${r}'. Accepted: ${Ef.join(", ")}`)}function Of(r){let e=r.repository?.full_name;if(typeof e=="string"&&e.includes("/"))return e;let t=r.repository_url;if(typeof t=="string"){let n="/repos/",o=t.lastIndexOf(n);if(o>=0){let i=t.slice(o+n.length);if(i.includes("/"))return i}}throw new Error("GitHub search result is missing repository full_name")}function ri(r,e,t){let n=String(r.number??""),[o,i]=t.split("/"),s=typeof r.body=="string"?r.body:"";return{id:kf(o??"",i??"",n),source:e,title:String(r.title??""),...s?{description:s}:{},status:String(r.state??""),...r.assignee?.login?{assignee:r.assignee.login}:{},...r.html_url?{url:r.html_url}:{},raw:r}}function $f(r,e){return{id:String(r.id??""),subjectId:e,body:r.body??"",...r.user?.login?{author:r.user.login}:{},createdAt:r.created_at??""}}function vn(r){return r!=null&&r!==""}var _f,Pf,Rf,Ef,jn,cc=l(()=>{"use strict";_f="2026-03-10",Pf="https://api.github.com",Rf="kno.github.apiToken",Ef=["open","closed/done/completed","not_planned/wontfix"],jn=class{secrets;fetchFn;instanceId;username;secretKey;constructor(e,t,n=fetch){this.secrets=e,this.fetchFn=n,this.instanceId=t.instanceId,this.username=t.username?.trim()||void 0,this.secretKey=t.secretKey?.trim()||Rf}async get(e){let{owner:t,repo:n,issueNumber:o}=xn(e),i=await this.request("GET",`/repos/${encodeURIComponent(t)}/${encodeURIComponent(n)}/issues/${encodeURIComponent(o)}`);if(ti(i))throw new Error(`Ticket not found: ${e}`);return ri(i,this.instanceId,`${t}/${n}`)}async query(e){let t=typeof e.repo=="string"?e.repo.trim():"";if(t)return this.queryRepoIssues(t,e);let n=Af(e);if(n)return this.querySearch(n,e);throw new Error("GitHub Issues query requires filter.repo ('owner/name') or filter.role ('assignee' | 'creator')")}async getComments(e){let{owner:t,repo:n,issueNumber:o}=xn(e),i=await this.request("GET",`/repos/${encodeURIComponent(t)}/${encodeURIComponent(n)}/issues/${encodeURIComponent(o)}/comments`);return(Array.isArray(i)?i:[]).map(a=>$f(a,e))}async postComment(e,t){let{owner:n,repo:o,issueNumber:i}=xn(e);await this.request("POST",`/repos/${encodeURIComponent(n)}/${encodeURIComponent(o)}/issues/${encodeURIComponent(i)}/comments`,{body:{body:t}})}async updateStatus(e,t){let{owner:n,repo:o,issueNumber:i}=xn(e);await this.request("PATCH",`/repos/${encodeURIComponent(n)}/${encodeURIComponent(o)}/issues/${encodeURIComponent(i)}`,{body:Tf(t)})}async queryRepoIssues(e,t){let{owner:n,name:o}=ac(e),i=[],s=new URLSearchParams;s.set("per_page",String(100)),vn(t.state)&&s.set("state",String(t.state)),vn(t.labels)&&s.set("labels",String(t.labels)),vn(t.assignee)&&s.set("assignee",String(t.assignee));for(let a=1;a<=10&&i.length<500;a++){s.set("page",String(a));let u=await this.request("GET",`/repos/${encodeURIComponent(n)}/${encodeURIComponent(o)}/issues?${s.toString()}`),c=Array.isArray(u)?u:[];if(c.length===0)break;for(let d of c)if(!ti(d)){if(i.length>=500)break;i.push(ri(d,this.instanceId,`${n}/${o}`))}if(c.length<100)break}return i}async querySearch(e,t){let n=this.requireUsername(),o=[Cf(e,n),"is:issue"];vn(t.state)&&o.push(`is:${String(t.state).trim().toLowerCase()}`);let i=o.join(" "),s=[];for(let a=1;a<=10&&s.length<500;a++){let u=new URLSearchParams({q:i,per_page:String(100),page:String(a)}),c=await this.request("GET",`/search/issues?${u.toString()}`),d=Array.isArray(c.items)?c.items:[];if(d.length===0)break;for(let m of d)if(!ti(m)){if(s.length>=500)break;s.push(ri(m,this.instanceId,Of(m)))}if(d.length<100)break}return s}requireUsername(){if(!this.username)throw new Error(`GitHub Issues instance '${this.instanceId}' is not configured \u2014 missing config.username`);return this.username}async requireToken(){let e=await this.secrets.get(this.secretKey);if(!e)throw new Error(`GitHub Issues instance '${this.instanceId}' is not configured \u2014 missing SecretStore '${this.secretKey}'. Store the token with: POST /api/secrets/${this.secretKey} or npm --workspace apps/engine run set-secret -- ${this.secretKey} <value>`);return e}async request(e,t,n={}){let o=await this.requireToken(),i=`${Pf}${t}`,s={Authorization:`Bearer ${o}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":_f};n.body!==void 0&&(s["Content-Type"]="application/json");let a=await this.fetchFn(i,{method:e,headers:s,...n.body!==void 0?{body:JSON.stringify(n.body)}:{}});if(!a.ok){let c=await a.text().catch(()=>"");throw new Error(`GitHub ${e} ${t} failed (${a.status}): ${c||a.statusText}`)}if(a.status===204)return;let u=await a.text();if(u)return JSON.parse(u)}}});var wt,y,h,J,E=l(()=>{"use strict";wt=class extends Error{constructor(e){super(e),this.name=this.constructor.name}},y=class extends wt{httpStatus=404},h=class extends wt{httpStatus=400},J=class extends wt{httpStatus=409}});function Ff(r){if(typeof r.jql=="string"&&r.jql.trim().length>0)return r.jql;let e=[];if(_n(r.project)&&e.push(`project = ${Pn(r.project)}`),_n(r.status)&&e.push(`status = ${Pn(r.status)}`),_n(r.assignee)&&e.push(`assignee = ${Pn(r.assignee)}`),_n(r.sprintId)){let t=r.sprintId;e.push(typeof t=="number"||/^\d+$/.test(String(t))?`sprint = ${Number(t)}`:`sprint = ${Pn(t)}`)}if(e.length===0)throw new h("Jira query requires jql or at least one of project, status, assignee, sprintId");return e.join(" AND ")}function _n(r){return r!=null&&r!==""}function Pn(r){return`"${String(r).replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function uc(r,e,t){let n=String(r.key??r.id??""),o=r.fields??{},i=hr(o.description);return{id:n,source:t,title:String(o.summary??""),...i?{description:i}:{},status:String(o.status?.name??""),...o.assignee?.displayName?{assignee:String(o.assignee.displayName)}:{},url:`${e.replace(/\/$/,"")}/browse/${n}`,raw:r}}var qf,Bf,Df,In,Rn,lc=l(()=>{"use strict";E();Ko();qf="kno.jira.apiToken",Bf=50,Df=10,In=500,Rn=class{secrets;fetchFn;instanceId;baseUrl;email;secretKey;constructor(e,t,n=fetch){this.secrets=e,this.fetchFn=n,this.instanceId=t.instanceId,this.baseUrl=t.baseUrl?.trim()||void 0,this.email=t.email?.trim()||void 0,this.secretKey=t.secretKey?.trim()||qf}async get(e){let{baseUrl:t}=await this.requireConfig(),n=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}`);return uc(n,t,this.instanceId)}async query(e){let{baseUrl:t}=await this.requireConfig(),n=Ff(e),o=[],i,s=new Set;for(let a=0;a<Df&&o.length<In;a++){let u={jql:n,maxResults:Math.min(Bf,In-o.length),fields:["summary","description","status","assignee"]};i&&(u.nextPageToken=i);let c=await this.request("POST","/rest/api/3/search/jql",{body:u}),d=Array.isArray(c.issues)?c.issues:[];for(let b of d){if(o.length>=In)break;o.push(uc(b,t,this.instanceId))}let m=typeof c.nextPageToken=="string"?c.nextPageToken:void 0;if(c.isLast===!0||!m||d.length===0||m===i||s.has(m))break;s.add(m),i=m}return o}async getComments(e){let t=[],n=0,o=100,i=In;for(;t.length<i;){let s=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}/comment?startAt=${n}&maxResults=${o}`),a=Array.isArray(s.comments)?s.comments:[];for(let u of a)t.push({id:String(u.id??""),subjectId:e,body:hr(u.body),...u.author?.displayName?{author:u.author.displayName}:{},createdAt:u.created??"",raw:u});if(n+=a.length,a.length===0||typeof s.total=="number"&&n>=s.total||a.length<o)break}return t}async postComment(e,t){await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(e)}/comment`,{body:{body:mn(t)}})}async updateStatus(e,t){let n=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}/transitions`),o=Array.isArray(n.transitions)?n.transitions:[],i=t.trim().toLowerCase(),s=o.find(a=>(a.to?.name??"").trim().toLowerCase()===i);if(!s?.id){let a=o.map(c=>c.to?.name).filter(c=>typeof c=="string"&&c.length>0),u=a.length>0?a.join(", "):"(none)";throw new Error(`No Jira transition to status '${t}' from the current state. Available: ${u}`)}await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(e)}/transitions`,{body:{transition:{id:s.id}}})}async requireConfig(){let e=this.baseUrl,t=this.email,n=await this.secrets.get(this.secretKey);if(!e||!t||!n){let o=[];throw e||o.push("config.baseUrl"),t||o.push("config.email"),n||o.push(`SecretStore '${this.secretKey}'`),new Error(`Jira instance '${this.instanceId}' is not configured \u2014 missing ${o.join(", ")}. Set baseUrl and email on the provider instance, and store the API token with: POST /api/secrets/${this.secretKey} or npm --workspace apps/engine run set-secret -- ${this.secretKey} <value>`)}return{baseUrl:e,email:t,token:n}}async request(e,t,n={}){let{baseUrl:o,email:i,token:s}=await this.requireConfig(),a=`${o.replace(/\/$/,"")}${t}`,u={Authorization:`Basic ${Buffer.from(`${i}:${s}`).toString("base64")}`,Accept:"application/json"};n.body!==void 0&&(u["Content-Type"]="application/json");let c=await this.fetchFn(a,{method:e,headers:u,...n.body!==void 0?{body:JSON.stringify(n.body)}:{}});if(!c.ok){let m=await c.text().catch(()=>"");throw new Error(`Jira ${e} ${t} failed (${c.status}): ${m||c.statusText}`)}if(c.status===204)return;let d=await c.text();if(d)return JSON.parse(d)}}});import{randomUUID as Nf}from"node:crypto";function Jf(r,e){return Object.entries(e).every(([t,n])=>r[t]===n)}var En,pc=l(()=>{"use strict";En=class{tickets;comments;instanceId;constructor(e=[],t){this.tickets=new Map(e.map(n=>[n.id,structuredClone(n)])),this.comments=new Map,this.instanceId=t}async get(e){let t=this.tickets.get(e);if(!t)throw new Error(`Ticket not found: ${e}`);return this.withSource(structuredClone(t))}async query(e){return[...this.tickets.values()].filter(t=>Jf(t,e)).map(t=>this.withSource(structuredClone(t)))}async getComments(e){return await this.get(e),structuredClone(this.comments.get(e)??[])}async postComment(e,t){await this.get(e);let n=this.comments.get(e)??[];n.push({id:Nf(),subjectId:e,body:t,createdAt:new Date().toISOString()}),this.comments.set(e,n)}async updateStatus(e,t){let n=this.tickets.get(e);if(!n)throw new Error(`Ticket not found: ${e}`);n.status=t}withSource(e){return this.instanceId?{...e,source:this.instanceId}:e}}});function qe(r,e){let t=r[e];return typeof t=="string"&&t.trim().length>0?t.trim():void 0}function kn(r){return new Error(`This workflow requires provider instance '${r}', which isn't configured`)}function Lf(r){return r==="jira"||r==="github"?"ticket":r==="bitbucket"?"pull_request":r==="confluence"?"documentation":"any"}var lv,F,$t=l(()=>{"use strict";C();Ga();za();Go();rc();ei();sc();cc();lc();pc();lv=Symbol("PROVIDER_REGISTRY");F=class r{tickets=new Map;repos=new Map;documentation=new Map;agents=new Map;instances=[];constructor(){}static fromSettings(e,t){let n=new r;return n.load(e,t),n}static fromMaps(e){let t=new r;for(let[n,o]of Object.entries(e.tickets??{}))t.tickets.set(n,o);for(let[n,o]of Object.entries(e.repos??{}))t.repos.set(n,o);for(let[n,o]of Object.entries(e.documentation??{}))t.documentation.set(n,o);for(let[n,o]of Object.entries(e.agents??{}))t.agents.set(n,o);return t.instances.push(...e.instances??[]),t}load(e,t){let n=new Set;for(let o of e){if(n.has(o.id))throw new Error(`Duplicate provider instance id '${o.id}'`);n.add(o.id),this.instances.push(o),this.instantiate(o,t)}}instantiate(e,t){if(Tt(e)){let o=qe(e.config,"model");if(e.type==="claude"){this.agents.set(e.id,new ln(t,{secretKey:e.secretKey,model:o}));return}this.agents.set(e.id,new pn(t,{secretKey:e.secretKey,model:o}));return}if(!yt(e))throw new Error(`Unknown provider instance kind on '${e.id}'`);let n=Lf(e.type);if(n!=="any"&&e.subjectType!==n)throw new Error(`Provider instance '${e.id}' type '${e.type}' cannot serve subjectType '${e.subjectType}'`);if(e.type==="jira"){this.tickets.set(e.id,new Rn(t,{instanceId:e.id,baseUrl:qe(e.config,"baseUrl"),email:qe(e.config,"email"),secretKey:e.secretKey}));return}if(e.type==="github"){this.tickets.set(e.id,new jn(t,{instanceId:e.id,username:qe(e.config,"username"),secretKey:e.secretKey}));return}if(e.type==="bitbucket"){this.repos.set(e.id,new bn(t,{instanceId:e.id,email:qe(e.config,"email"),workspace:qe(e.config,"workspace"),secretKey:e.secretKey}));return}if(e.type==="confluence"){this.documentation.set(e.id,new yn(t,{instanceId:e.id,baseUrl:qe(e.config,"baseUrl"),email:qe(e.config,"email"),secretKey:e.secretKey}));return}if(e.subjectType==="ticket"){this.tickets.set(e.id,new En([],e.id));return}if(e.subjectType==="pull_request"){this.repos.set(e.id,new Sn([],e.id));return}this.documentation.set(e.id,new wn([],{instanceId:e.id,type:qe(e.config,"type")}))}getTicketProvider(e){let t=this.tickets.get(e);if(!t)throw kn(e);return t}getRepoProvider(e){let t=this.repos.get(e);if(!t)throw kn(e);return t}getDocumentationProvider(e){let t=this.documentation.get(e);if(!t)throw kn(e);return t}getAgentProvider(e){let t=this.agents.get(e);if(!t)throw kn(e);return t}getInstance(e){return this.instances.find(t=>t.id===e)}listInstances(e){return e==null?[...this.instances]:this.instances.filter(t=>yt(t)&&t.subjectType===e)}ticketInstanceIds(){return[...this.tickets.keys()]}repoInstanceIds(){return[...this.repos.keys()]}documentationInstanceIds(){return[...this.documentation.keys()]}}});function fc(r,e){switch(r){case"my-open-prs":return{role:"author",state:"OPEN"};case"reviewing":return{role:"reviewer",state:"OPEN"};case"repo-open-prs":{let t=typeof e.repoSlug=="string"?e.repoSlug.trim():"";if(!t)throw new h("Bitbucket template 'repo-open-prs' requires params.repoSlug");return{repoSlug:t,state:"OPEN"}}default:throw new y(`Unknown Bitbucket query template: ${r}`)}}var dc,mc=l(()=>{"use strict";E();dc=[{id:"my-open-prs",label:"My open pull requests",params:[]},{id:"reviewing",label:"Pull requests I'm reviewing",params:[]},{id:"repo-open-prs",label:"Open pull requests in a repository",params:[{name:"repoSlug",label:"Repository",type:"string",required:!0}]}]});function yc(r,e){switch(r){case"my-open-issues":return{role:"assignee",state:"open"};case"created-by-me":return{role:"creator",state:"open"};case"repo-open-issues":{let t=typeof e.repo=="string"?e.repo.trim():"";if(!t)throw new h("GitHub template 'repo-open-issues' requires params.repo");return{repo:t,state:"open"}}default:throw new y(`Unknown GitHub query template: ${r}`)}}var hc,wc=l(()=>{"use strict";E();hc=[{id:"my-open-issues",label:"My open issues",params:[]},{id:"created-by-me",label:"Issues I created",params:[]},{id:"repo-open-issues",label:"Open issues in a repository",params:[{name:"repo",label:"Repository (owner/name)",type:"string",required:!0}]}]});function vc(r,e){switch(r){case"my-open-tickets":return{jql:"assignee = currentUser() AND statusCategory != Done"};case"created-by-me":return{jql:"reporter = currentUser() AND statusCategory != Done"};case"project-open-tickets":return{jql:`project = ${Sc(bc(r,e))} AND statusCategory != Done`};case"current-sprint-tickets":return{jql:`project = ${Sc(bc(r,e))} AND sprint in openSprints() AND statusCategory != Done`};default:throw new y(`Unknown Jira query template: ${r}`)}}function bc(r,e){let t=typeof e.project=="string"?e.project.trim():"";if(!t)throw new h(`Jira template '${r}' requires params.project`);return t}function Sc(r){return`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}var gc,xc,jc=l(()=>{"use strict";E();gc={name:"project",label:"Project key",type:"string",required:!0},xc=[{id:"my-open-tickets",label:"My open tickets",params:[]},{id:"created-by-me",label:"Tickets I created",params:[]},{id:"project-open-tickets",label:"Open tickets in a project",params:[gc]},{id:"current-sprint-tickets",label:"Tickets in the current sprint",params:[gc]}]});import{Inject as _c,Injectable as Wf}from"@nestjs/common";var Uf,Mf,Ic,Pc,rt,ni=l(()=>{"use strict";C();E();Pe();$t();mc();wc();jc();Uf=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Mf=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},Ic=function(r,e){return function(t,n){e(t,n,r)}},Pc={bitbucket:{list:()=>dc,resolve:fc},github:{list:()=>hc,resolve:yc},jira:{list:()=>xc,resolve:vc}},rt=class{settings;registry;constructor(e,t){this.settings=e,this.registry=t}async list(e){let t=await this.providerType(e);return t?Pc[t]?.list()??[]:[]}async resolve(e,t,n){let o=await this.providerType(e),i=o?Pc[o]:void 0;if(!i)throw new y(`No query templates for provider instance '${e}'`);let s=i.list().find(a=>a.id===t);if(!s)throw new y(`Unknown query template '${t}' for provider instance '${e}'`);for(let a of s.params){if(!a.required)continue;let u=n[a.name];if(u==null||typeof u=="string"&&u.trim()==="")throw new h(`Template '${t}' requires params.${a.name}`)}return i.resolve(t,n)}async providerType(e){let n=(await this.settings.get()).providerInstances?.find(o=>o.id===e)??this.registry.getInstance(e);if(!(!n||!yt(n)))return n.type}};rt=Uf([Wf(),Ic(0,_c(R)),Ic(1,_c(F)),Mf("design:paramtypes",[R,F])],rt)});import{Inject as Ec,Injectable as Kf}from"@nestjs/common";var Hf,Vf,Rc,Gf,nt,oi=l(()=>{"use strict";C();Pe();Go();ei();$t();Hf=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Vf=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},Rc=function(r,e){return function(t,n){e(t,n,r)}},Gf={bitbucket:()=>Zo,confluence:()=>hn},nt=class{settings;registry;constructor(e,t){this.settings=e,this.registry=t}async list(e){let n=(await this.settings.get()).providerInstances?.find(o=>o.id===e)??this.registry.getInstance(e);return!n||!yt(n)?[]:Gf[n.type]?.()??[]}};nt=Hf([Kf(),Rc(0,Ec(R)),Rc(1,Ec(F)),Vf("design:paramtypes",[R,F])],nt)});async function kc(r){let e=r.fetchFn??fetch;return r.type==="claude"?Yf(r.apiKey,e):Zf(r.apiKey,e)}async function Yf(r,e){let t=await e(zf,{method:"GET",headers:{"x-api-key":r,"anthropic-version":Xf}});if(!t.ok)throw Ac("Claude",t.status);let n=await t.json();return(Array.isArray(n.data)?n.data:[]).flatMap(i=>{if(!i||typeof i!="object")return[];let s=i,a=typeof s.id=="string"?s.id:"";if(!a)return[];let u=typeof s.display_name=="string"&&s.display_name.trim()?s.display_name:a;return[{id:a,displayName:u}]})}async function Zf(r,e){let t=await e(Qf,{method:"GET",headers:{Authorization:`Basic ${Buffer.from(`${r}:`).toString("base64")}`}});if(!t.ok)throw Ac("Cursor",t.status);let n=await t.json();return(Array.isArray(n.items)?n.items:[]).flatMap(i=>{if(!i||typeof i!="object")return[];let s=i,a=typeof s.id=="string"?s.id:"";if(!a)return[];let u=typeof s.displayName=="string"&&s.displayName.trim()?s.displayName:a;return[{id:a,displayName:u}]})}function Ac(r,e){let t=new Error(`${r} rejected the API key (HTTP ${e}). Check the key and try again.`);return t.name="PreviewModelsAuthError",t}var zf,Qf,Xf,Cc=l(()=>{"use strict";zf="https://api.anthropic.com/v1/models",Qf="https://api.cursor.com/v1/models",Xf="2023-06-01"});import{Inject as si,Injectable as rm}from"@nestjs/common";var em,tm,ii,An,ot,ai=l(()=>{"use strict";C();Pe();Te();E();Cc();em=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},tm=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},ii=function(r,e){return function(t,n){e(t,n,r)}},An="PREVIEW_MODELS_FETCH",ot=class{settings;secrets;fetchFn;constructor(e,t,n){this.settings=e,this.secrets=t,this.fetchFn=n}async preview(e){let t=e.apiKey?.trim();if(t)return this.lookup(e.type,t);let n=e.instanceId?.trim();if(!n)throw new h("Provide apiKey or instanceId to preview models");let o=(await this.settings.get()).providerInstances?.find(s=>s.id===n);if(!o)throw new y(`Provider instance not found: ${n}`);if(!Tt(o)||o.type!==e.type)throw new h(`Provider instance '${n}' is not a ${e.type} agent`);let i=await this.secrets.get(o.secretKey);if(!i)throw new h(`No API key stored for instance '${n}'. Enter a key to fetch models.`);return this.lookup(e.type,i)}async lookup(e,t){try{return await kc({type:e,apiKey:t,fetchFn:this.fetchFn})}catch(n){throw n instanceof Error&&n.name==="PreviewModelsAuthError"?new h(n.message):new h(n instanceof Error?n.message:"Failed to fetch available models")}}};ot=em([rm(),ii(0,si(R)),ii(1,si(fe)),ii(2,si(An)),tm("design:paramtypes",[R,Function,Function])],ot)});import{Module as om}from"@nestjs/common";var nm,it,Cn=l(()=>{"use strict";go();ds();jo();Te();dr();Pe();Vo();$t();ni();oi();ai();nm=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},it=class{};it=nm([om({imports:[Et,Re],providers:[{provide:F,useFactory:async(r,e)=>{let t=await r.get();return F.fromSettings(t.providerInstances??[],e)},inject:[R,fe]},{provide:Yt,useClass:Er},tt,rt,nt,{provide:An,useValue:(r,e)=>fetch(r,e)},ot],exports:[F,Yt,tt,rt,nt,ot,An]})],it)});import{Injectable as sm}from"@nestjs/common";var im,ye,Tn=l(()=>{"use strict";im=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},ye=class{listeners=new Set;emit(e){for(let t of this.listeners)t(e)}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}};ye=im([sm()],ye)});import{Global as cm,Module as um}from"@nestjs/common";var am,st,On=l(()=>{"use strict";Tn();am=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},st=class{};st=am([cm(),um({providers:[ye],exports:[ye]})],st)});import{Injectable as dm}from"@nestjs/common";import{execFile as fm}from"node:child_process";import{mkdirSync as ci,rmSync as mm}from"node:fs";import{dirname as hm,join as $n,resolve as Tc}from"node:path";import{promisify as ym}from"node:util";function Oc(r){return r==null?"":typeof r=="string"?r:r.toString("utf8")}function $c(r){return $n(r,"worktrees")}function gm(r){let e=[],t;for(let n of r.split(/\r?\n/)){let o=n.trimEnd();if(o===""){t&&e.push(t),t=void 0;continue}if(o.startsWith("worktree ")){t&&e.push(t),t={path:o.slice(9)};continue}if(t&&o.startsWith("branch ")){let i=o.slice(7);t.branch=i.startsWith("refs/heads/")?i.slice(11):i}}return t&&e.push(t),e}var lm,pm,wm,Be,ui=l(()=>{"use strict";lm=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},pm=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},wm=ym(fm),Be=class{worktreesRoot;constructor(e){this.worktreesRoot=e,ci(this.worktreesRoot,{recursive:!0})}async createWorktree(e,t){let n=t.worktreePath??$n(this.worktreesRoot,e);return ci($n(n,".."),{recursive:!0}),await this.git(t.repoPath,["worktree","add","-b",t.branchName,n,t.baseBranch]),{worktreePath:n,branch:t.branchName}}async addWorktreeForExistingBranch(e){ci($n(e.worktreePath,".."),{recursive:!0});try{await this.git(e.repoPath,["fetch","origin",e.branch])}catch{}let t=await this.existingBranchStartPoint(e.repoPath,e.branch);return t.kind==="local"?await this.git(e.repoPath,["worktree","add",e.worktreePath,e.branch]):await this.git(e.repoPath,["worktree","add","--track","-b",e.branch,e.worktreePath,t.ref]),{worktreePath:e.worktreePath,branch:e.branch}}async listWorktrees(e){let{stdout:t}=await this.git(e,["worktree","list","--porcelain"]);return gm(t)}async resetWorktreeToRemote(e,t){try{await this.git(e,["fetch","origin",t])}catch{}let n=`origin/${t}`;try{await this.git(e,["rev-parse","--verify",n]),await this.git(e,["reset","--hard",n])}catch{await this.git(e,["reset","--hard",t])}await this.git(e,["clean","-fd"])}async removeWorktree(e){let t=Tc(e);try{let{stdout:n}=await this.git(t,["rev-parse","--git-common-dir"]),o=Tc(t,n.trim()),i=o.endsWith(".git")?hm(o):o;await this.git(i,["worktree","remove","--force",t])}catch{mm(t,{recursive:!0,force:!0})}}async existingBranchStartPoint(e,t){try{return await this.git(e,["rev-parse","--verify",`refs/heads/${t}`]),{kind:"local"}}catch{let n=`origin/${t}`;return await this.git(e,["rev-parse","--verify",n]),{kind:"remote",ref:n}}}async checkout(e,t){await this.git(e,["checkout",t.branch])}async createBranch(e,t){t.baseBranch?await this.git(e,["checkout","-b",t.branchName,t.baseBranch]):await this.git(e,["checkout","-b",t.branchName])}async commit(e,t){return t.addAll!==!1&&await this.git(e,["add","-A"]),await this.git(e,["commit","-m",t.message]),{sha:(await this.git(e,["rev-parse","HEAD"])).stdout.trim()}}async push(e,t={}){let n=t.remote??"origin";t.branch?await this.git(e,["push",n,t.branch]):await this.git(e,["push",n,"HEAD"])}async git(e,t){try{let n=await wm("git",t,{cwd:e,encoding:"utf8",windowsHide:!0});return{stdout:n.stdout??"",stderr:n.stderr??""}}catch(n){let o=n,i=Oc(o.stderr),s=Oc(o.stdout),a=i||s||o.message||"unknown git error";throw new Error(`git ${t.join(" ")} failed (cwd=${e}, code=${String(o.code??"?")}): ${a}`)}}};Be=lm([dm(),pm("design:paramtypes",[String])],Be)});import{Module as Sm}from"@nestjs/common";import{mkdirSync as xm}from"node:fs";var bm,qc,qn,Bc=l(()=>{"use strict";kr();ui();bm=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},qc=er();xm(qc,{recursive:!0});qn=class{};qn=bm([Sm({providers:[{provide:Be,useFactory:()=>new Be($c(qc))}],exports:[Be]})],qn)});function wr(r,e){return r.replace(/\{\{\s*([^}]+?)\s*\}\}/g,(t,n)=>{let o=vm(e,n.trim());return o==null?"":typeof o=="string"?o:JSON.stringify(o)})}function vm(r,e){let t=e.split(".").filter(Boolean),n=r;for(let o of t){if(n==null||typeof n!="object")return;n=n[o]}return n}function qt(r,e){return typeof r=="string"?wr(r,e):Array.isArray(r)?r.map(t=>qt(t,e)):r&&typeof r=="object"?Object.fromEntries(Object.entries(r).map(([t,n])=>[t,qt(n,e)])):r}var Dc=l(()=>{"use strict"});function Fc(r,e){switch(r){case"questionnaire":return li(e);case"confirmation":return jm(e);case"conversation":return Im(e);default:return r}}function li(r){if(typeof r=="string"&&r.trim())return[r.trim()];if(!r||typeof r!="object")return[];let e=r.questions;return Array.isArray(e)?e.map(t=>typeof t=="string"?t.trim():t&&typeof t=="object"&&"prompt"in t?String(t.prompt).trim():"").filter(Boolean):[]}function jm(r){if(typeof r=="string"&&r.trim())return[r.trim()];if(!r||typeof r!="object")return[];let e=r;for(let t of["prompt","message","summary","question"]){let n=e[t];if(typeof n=="string"&&n.trim())return[n.trim()]}return"approved"in e&&!("questions"in e)?[]:li(r)}function Im(r){if(typeof r=="string"&&r.trim())return[r.trim()];if(!r||typeof r!="object")return[];let e=r;for(let t of["prompt","message","text"]){let n=e[t];if(typeof n=="string"&&n.trim())return[n.trim()]}return"suggestions"in e?[]:"questions"in e?li(r):[]}var Nc=l(()=>{"use strict"});function at(r,e){for(let t of r){if(t.id===e)return t;if(t.iterations)for(let n of t.iterations){let o=at(n.stepExecutions,e);if(o)return o}}}function Bt(r,e,t,n){for(let o=0;o<r.length;o++){let i=r[o];if(i.id===e)return{execution:i,siblings:r,index:o,parentLoopExecutionId:t,iterationIndex:n};if(i.iterations)for(let s of i.iterations){let a=Bt(s.stepExecutions,e,i.id,s.index);if(a)return a}}}function ee(r,e,t){return r.map(n=>n.id===e?t(n):n.iterations?{...n,iterations:n.iterations.map(o=>({...o,stepExecutions:ee(o.stepExecutions,e,t)}))}:n)}function pi(r,e,t,n){return t==null?[...r,e]:r.map(o=>{if(o.id===t){let i=[...o.iterations??[]],s=i.find(a=>a.index===n);if(s){let a={...s,stepExecutions:[...s.stepExecutions,e]},u=i.findIndex(c=>c.index===n);i[u]=a}else{let a={index:n,stepExecutions:[e],startedAt:e.startedAt??new Date().toISOString()};i.push(a),i.sort((u,c)=>u.index-c.index)}return{...o,iterations:i}}return o.iterations?{...o,iterations:o.iterations.map(i=>({...i,stepExecutions:pi(i.stepExecutions,e,t,n)}))}:o})}function gr(r,e){for(let t of r){if(t.id===e)return t;if(t.type==="loop"){let n=gr(t.steps,e);if(n)return n}}}function Jc(r,e,t){return ee(r,e,n=>{let o=(n.iterations??[]).map(i=>{if(i.index!==t)return i;let s=i.stepExecutions.every(a=>a.completedAt)?i.stepExecutions.map(a=>a.completedAt).reduce((a,u)=>a>u?a:u):void 0;return{...i,...s?{completedAt:s}:{}}});return{...n,iterations:o}})}function di(r){let e=[];for(let t of r){t.childJobIds&&e.push(...t.childJobIds);for(let n of t.iterations??[])e.push(...di(n.stepExecutions))}return e}var Lc=l(()=>{"use strict"});import{z as le}from"zod";function Uc(r,e){let t=km[r].safeParse(e);if(!t.success){let n=t.error.issues.map(o=>`${o.path.length?o.path.join("."):"(root)"}: ${o.message}`).join("; ");throw new Error(`Agent output failed validation for format '${r}': ${n}`)}return t.data}var _m,Pm,Rm,Em,km,Mc=l(()=>{"use strict";_m=le.object({questions:le.array(le.object({id:le.string(),prompt:le.string()}))}),Pm=le.object({approved:le.boolean()}),Rm=le.object({suggestions:le.array(le.object({body:le.string()}))}),Em=le.string(),km={questionnaire:_m,confirmation:Pm,comment_suggestions:Rm,free_text:Em}});function we(r){return r==="completed"||r==="failed"||r==="cancelled"}function fi(r,e){let t=new Map;for(let o of r){let i=e(o);if(i==null)continue;let s=t.get(i)??[];s.push(o),t.set(i,s)}if(t.size===0)return null;let n=[];for(let o of t.values()){let i=new Set(o.map(a=>a.retryOf).filter(a=>a!=null)),s=o.find(a=>!i.has(a.id));if(!s)return null;n.push(s)}return{activeJobs:n,allTerminal:n.every(o=>we(o.status)),groupCount:t.size}}function Wc(r){let e=r.every(n=>n.status==="completed"),t=r.every(n=>n.status==="failed"||n.status==="cancelled");return e?"completed":t?"failed":"completed_with_issues"}var mi=l(()=>{"use strict"});async function Bn(r,e,t){let n=await e.get(r);if(!n)throw new y(`SubjectView not found: ${r}`);if(!n.providerInstanceId)throw new h(`SubjectView '${r}' has no providerInstanceId \u2014 reconfigure the View to pick a provider instance`);if(n.subjectType==="ticket")return(await t.getTicketProvider(n.providerInstanceId).query(n.query)).map(i=>({subjectType:"ticket",...i}));if(n.subjectType==="pull_request")return(await t.getRepoProvider(n.providerInstanceId).query(n.query)).map(i=>({subjectType:"pull_request",...i}));if(n.subjectType==="documentation")return(await t.getDocumentationProvider(n.providerInstanceId).query(n.query)).map(i=>({subjectType:"documentation",...i}));throw new h(`Unsupported subjectType on view: ${n.subjectType}`)}var hi=l(()=>{"use strict";E()});import{Injectable as Cm}from"@nestjs/common";var Am,gt,yi=l(()=>{"use strict";Am=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},gt=class{requested=new Set;requestCancellation(e){this.requested.add(e)}isCancellationRequested(e){return this.requested.has(e)}clear(e){this.requested.delete(e)}};gt=Am([Cm()],gt)});import{Logger as Tm}from"@nestjs/common";import{readFile as Om}from"node:fs/promises";async function Hc(r,e,t=new Tm("resolveContextFiles"),n=o=>Om(o,"utf8")){let o=[];for(let i of r){let s=await e.get(i);if(!s){t.warn(`Context file '${i}' is no longer in the catalog; skipping`);continue}try{let a=await n(s.path);o.push({tier:s.tier,content:a,sourceRef:s.path})}catch(a){let u=a instanceof Error?a.message:String(a);throw new Error(`Cannot read context file '${s.name}' at ${s.path}: ${u}`)}}return o}var Vc=l(()=>{"use strict"});import{basename as $m,dirname as qm,join as Bm,resolve as br,sep as Kc}from"node:path";function Dm(r){return r.replace(/-/g,"").slice(0,4)}function Gc(r,e){return`${r}-${Dm(e)}`}function wi(r){return r.replace(/[\\/:*?"<>|]/g,"-")}function Dn(r){let e=br(r);return Bm(qm(e),`${$m(e)}-worktrees`)}function Fn(r,e){let t=br(r),n=br(e);if(ct(t,n))return!0;let o=t.endsWith(Kc)?t:t+Kc,i=process.platform==="win32"?n.toLowerCase():n,s=process.platform==="win32"?o.toLowerCase():o;return i.startsWith(s)}function ct(r,e){let t=br(r),n=br(e);return process.platform==="win32"?t.toLowerCase()===n.toLowerCase():t===n}var gi=l(()=>{"use strict"});import{join as zc}from"node:path";async function Qc(r,e,t){let n={...e},o=await t.list();for(let i of r){if(i.type!=="localRepository")continue;let s=n[i.name];if(s==null||s==="")continue;let a=String(s),u=o.find(m=>m.id===a),c=o.find(m=>ct(m.localPath,a)),d=u??c;if(!d)throw new h(`Unknown local repository: ${a}`);n[i.name]=d.localPath}return n}async function Xc(r){let{job:e,params:t,git:n,jobs:o,localRepositories:i}=r,s=Nn(t,"repoPath"),a=t.mode==="existing-branch"?"existing-branch":"new-branch",u=(await i.list()).find(S=>ct(S.localPath,s)),c=u?.worktreeBasePath?.trim()?u.worktreeBasePath.trim():Dn(s);if(Fn(s,c)&&!ct(s,c))throw new Error(`Worktree base '${c}' must not be inside the repository at '${s}'`);if(a==="existing-branch")return Fm({job:e,repoPath:s,branch:Nn(t,"branch"),worktreeBase:c,explicitPath:typeof t.worktreePath=="string"?t.worktreePath:void 0,git:n,jobs:o});let d=Nn(t,"branchName"),m=Gc(d,e.id),b=typeof t.worktreePath=="string"&&t.worktreePath.trim()!==""?t.worktreePath:zc(c,wi(m));return n.createWorktree(e.id,{repoPath:s,baseBranch:Nn(t,"baseBranch"),branchName:m,worktreePath:b})}async function Fm(r){let{job:e,repoPath:t,branch:n,worktreeBase:o,git:i,jobs:s}=r,a=await i.listWorktrees(t),u=a.filter(b=>b.branch===n&&!ct(b.path,t)),c=a.find(b=>b.branch===n&&ct(b.path,t));if(u.length===0){if(c)throw new Error(`branch ${n} is checked out in the repository working copy; refusing to reuse the main clone`);let b=r.explicitPath&&r.explicitPath.trim()!==""?r.explicitPath:zc(o,wi(n));return i.addWorktreeForExistingBranch({repoPath:t,branch:n,worktreePath:b})}let d=u[0].path,m=await Nm(s,d);if(m&&!we(m.status))throw new Error(`branch ${n} already has an active worktree in use by Job ${m.id}`);return m&&m.id!==e.id&&await s.update(m.id,{worktreeDeletedAt:new Date().toISOString()}),await i.resetWorktreeToRemote(d,n),{worktreePath:d,branch:n}}async function Nm(r,e){let n=(await r.list({liveWorktree:!0})).filter(o=>o.worktreePath!=null&&ct(o.worktreePath,e));return n.find(o=>!we(o.status))??n.sort((o,i)=>i.updatedAt.localeCompare(o.updatedAt))[0]}function Nn(r,e){let t=r[e];if(typeof t!="string"||t.trim()==="")throw new Error(`git step missing required param '${e}'`);return t}var Yc=l(()=>{"use strict";E();gi();mi()});import{Inject as de,Injectable as Um,Logger as Mm}from"@nestjs/common";import{randomUUID as bi}from"node:crypto";import{exec as Wm}from"node:child_process";import{promisify as Hm}from"node:util";async function Si(r,e,t){if(r.length===0)throw new Error(t);let n;for(let o of r)try{return await e(o)}catch(i){n=i}throw n instanceof Error?n:new Error(t)}function Zc(r,e){let t=e[r.stepId];if(t==null||typeof t!="object")return r.type==="field_empty";let n=t[r.field];return r.type==="field_empty"?n==null?!0:typeof n=="string"||Array.isArray(n)?n.length===0:!1:n===r.value}function Gm(r,e){let t=o=>{let i=[];for(let s of o)i.push(s),s.type==="loop"&&i.push(...t(s.steps));return i},n=o=>{let i=o.findIndex(s=>s.id===e);if(i>=0){for(let s=i-1;s>=0;s--)if(o[s].type==="agent")return o[s].id;return}for(let s of o)if(s.type==="loop"){let a=n(s.steps);if(a!==void 0||s.steps.some(u=>u.id===e))return a}};return n(r.steps)}function Dt(r){let e={...r.context};return r.subjectContext?.mode==="single"&&(e.subject=r.subjectContext.subject),r.worktreePath&&(e.worktreePath=r.worktreePath),r.branch&&(e.branch=r.branch),e}function Jn(r){if(!r.worktreePath)throw new Error(`Job ${r.id} has no worktreePath; run create_worktree first`);return r.worktreePath}function bt(r,e){let t=r[e];if(typeof t!="string"||t.length===0)throw new Error(`Missing required string param '${e}'`);return t}function zm(r){if(r==="none")throw new Error("normalizeAppliesTo called with none");if(Array.isArray(r)){if(r.length!==1)throw new Error(`Workflow Runner requires appliesTo to be a single SubjectType (got ${JSON.stringify(r)})`);return r[0]}return r}function eu(r,e){for(let t of r)if(t.required&&(e[t.name]===void 0||e[t.name]===null))throw new h(`Missing required input: ${t.name}`)}var Jm,Lm,pe,xi,Vm,Km,ge,Ln=l(()=>{"use strict";ft();lr();Br();qr();Tn();ui();Pe();Dr();Fr();$t();go();fn();E();Dc();Nc();Lc();Mc();mi();hi();yi();Vc();Yc();Jm=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Lm=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},pe=function(r,e){return function(t,n){e(t,n,r)}},Vm=Hm(Wm),Km=new Set(["agent","shell","git","provider_action"]),ge=xi=class{workflows;jobs;batches;views;events;providers;notifications;contextFiles;localRepositories;git;settings;cancellation;logger=new Mm(xi.name);childTerminalLocks=new Set;batchTerminalLocks=new Set;constructor(e,t,n,o,i,s,a,u,c,d,m,b){this.workflows=e,this.jobs=t,this.batches=n,this.views=o,this.events=i,this.providers=s,this.notifications=a,this.contextFiles=u,this.localRepositories=c,this.git=d,this.settings=m,this.cancellation=b,this.events.subscribe(S=>{let I=S;(I.type==="job_completed"||I.type==="job_failed"||I.type==="job_cancelled")&&this.onChildTerminal(I.jobId)})}async start(e){let t=await this.createJob(e);return this.emit({type:"job_started",jobId:t.id,timestamp:new Date().toISOString()}),this.runJob(t.id)}async launch(e){let t=await this.requireWorkflow(e.workflowId);if(t.subjectHandling!=="per-subject"&&t.subjectHandling!=="collection")throw new h(`Unsupported subjectHandling: ${String(t.subjectHandling)}`);eu(t.inputSchema,e.inputValues);let n=await this.resolveSelection(e.selection);if(t.subjectHandling==="collection"){let a=await this.createJob({workflowId:t.id,subjectContext:{mode:"collection",subjects:n},selection:e.selection,inputValues:e.inputValues});return this.emit({type:"job_started",jobId:a.id,timestamp:new Date().toISOString()}),this.runJob(a.id)}let o=new Date().toISOString(),i=await this.batches.create({id:bi(),workflowId:t.id,selection:e.selection,resolvedSubjects:n,status:"running",triggeredBy:e.triggeredBy,...e.notificationOverride?{notificationOverride:e.notificationOverride}:{},notificationSent:!1,createdAt:o}),s=[];for(let a=0;a<n.length;a++){let u=n[a],c=await this.createJob({workflowId:t.id,subjectContext:{mode:"single",subject:u},selection:e.selection,batchId:i.id,fanOutIndex:a,inputValues:e.inputValues});s.push(c)}for(let a of s)this.emit({type:"job_started",jobId:a.id,timestamp:new Date().toISOString()}),await this.runJob(a.id);return await this.batches.get(i.id)}async createJob(e){let t=e.workflowSnapshot?structuredClone(e.workflowSnapshot):await this.workflows.get(e.workflowId);if(!t)throw new y(`Workflow not found: ${e.workflowId}`);if(!e.subjectContext&&t.subjectHandling!=="per-subject")throw new h(`Workflow Runner only supports subjectHandling 'per-subject' at start() without an explicit subjectContext (got '${t.subjectHandling}')`);let n=await Qc(t.inputSchema,e.inputValues,this.localRepositories);eu(t.inputSchema,n);let o=e.subjectContext??await this.resolveSubjectContext(t,e.subjectId),i=new Date().toISOString();return this.jobs.create({id:bi(),workflowId:t.id,status:"pending",...o?{subjectContext:o}:{},...e.selection?{selection:e.selection}:{},...e.batchId?{batchId:e.batchId}:{},...e.parentJobId?{parentJobId:e.parentJobId}:{},...e.parentStepExecutionId?{parentStepExecutionId:e.parentStepExecutionId}:{},...e.fanOutIndex!=null?{fanOutIndex:e.fanOutIndex}:{},...e.retryOf?{retryOf:e.retryOf}:{},workflowSnapshot:structuredClone(t),context:{...n},stepHistory:[],createdAt:i,updatedAt:i})}async deleteWorktrees(e){if(e.length===0)throw new h("jobIds is required");let t=[];for(let s of e){let a=await this.jobs.get(s);if(!a)throw new y(`Job not found: ${s}`);t.push(a)}let n=t.find(s=>!we(s.status));if(n)throw new J(`Cannot delete worktree for active Job ${n.id}`);let o=new Date().toISOString(),i=[];for(let s of t){s.worktreePath&&!s.worktreeDeletedAt&&await this.git.removeWorktree(s.worktreePath);let a=await this.jobs.update(s.id,{worktreeDeletedAt:o,updatedAt:o});i.push(a)}return i}async runJob(e){let t=await this.jobs.get(e);if(!t)throw new y(`Job not found: ${e}`);if(we(t.status))return t;let n=await this.workflowForJob(t);if(t.status==="pending"&&(t=await this.persistJob({...t,status:"planning",updatedAt:new Date().toISOString()}),t.status==="cancelled"))return t;let o=await this.executeStepSequence(t,n,n.steps,void 0,void 0,0);return o.outcome!=="completed"?o.job:this.completeJob(o.job,n)}async resume(e,t){let n=await this.jobs.get(e);if(!n)throw new y(`Job not found: ${e}`);if(n.status!=="waiting_for_human")throw new J(`Job ${e} is not waiting for human input (status: ${n.status})`);let o=await this.workflowForJob(n),i=n.currentStepExecutionId;if(!i)throw new Error(`Job ${e} is waiting_for_human but has no currentStepExecutionId`);let s=at(n.stepHistory,i);if(!s)throw new Error(`Paused execution ${i} not found on job ${e}`);if(s.type==="loop")return this.resumeAskHuman(n,o,s,t);if(s.type!=="interaction")throw new Error(`Paused execution ${i} has type '${s.type}'; expected interaction or loop`);let a=new Date().toISOString(),u=ee(n.stepHistory,i,I=>({...I,status:"completed",completedAt:a,output:t})),c=t!==null&&typeof t=="object"&&!Array.isArray(t)?t:{response:t};n=await this.persistJob({...n,status:"planning",context:{...n.context,[s.stepDefinitionId]:t},stepHistory:u,currentStepId:void 0,currentStepExecutionId:void 0,updatedAt:a}),this.emit({type:"human_answered",jobId:n.id,answers:c,timestamp:a});let d=Bt(n.stepHistory,i);if(!d)throw new Error(`Could not locate frame for execution ${i}`);let m=this.sequenceForFrameOnJob(n,o,d),b=d.index+1,S=await this.executeStepSequence(n,o,m,d.parentLoopExecutionId,d.iterationIndex,b);return S.outcome!=="completed"?S.job:d.parentLoopExecutionId!=null&&d.iterationIndex!=null?this.continueLoopAfterBody(S.job,o,d.parentLoopExecutionId,d.iterationIndex):this.completeJob(S.job,o)}async retryFailedJob(e){let t=await this.jobs.get(e);if(!t)throw new y(`Job not found: ${e}`);if(t.status!=="failed")throw new J(`Job ${e} is not failed (status: ${t.status})`);let n=t.parentJobId!=null&&t.parentStepExecutionId!=null&&t.fanOutIndex!=null,o=t.batchId!=null&&t.fanOutIndex!=null;if(n){let a=await this.jobs.get(t.parentJobId);if(!a)throw new y(`Parent job not found: ${t.parentJobId}`);let u=await this.createJob({workflowId:t.workflowId,subjectContext:t.subjectContext,inputValues:{},parentJobId:t.parentJobId,parentStepExecutionId:t.parentStepExecutionId,fanOutIndex:t.fanOutIndex,retryOf:t.id,workflowSnapshot:t.workflowSnapshot}),c=ee(a.stepHistory,t.parentStepExecutionId,d=>({...d,status:"waiting_for_children",error:void 0,completedAt:void 0,childJobIds:[...d.childJobIds??[],u.id]}));return a=await this.persistJob({...a,status:"waiting_for_children",stepHistory:c,completedAt:void 0,updatedAt:new Date().toISOString()}),this.emitRetryLaunch(u.id,t.id),this.runJob(u.id),u}if(o){let a=await this.batches.get(t.batchId);if(!a)throw new y(`JobBatch not found: ${t.batchId}`);a.status!=="running"&&await this.batches.update(a.id,{status:"running",completedAt:null,notificationSent:!1});let u=await this.createJob({workflowId:t.workflowId,subjectContext:t.subjectContext,selection:t.selection,batchId:t.batchId,fanOutIndex:t.fanOutIndex,inputValues:{},retryOf:t.id,workflowSnapshot:t.workflowSnapshot});return this.emitRetryLaunch(u.id,t.id),this.runJob(u.id),u}let i=await this.workflowForJob(t),s=await this.createJob({workflowId:t.workflowId,subjectContext:t.subjectContext,selection:t.selection,inputValues:this.inputValuesFromContext(t.context,i),retryOf:t.id,workflowSnapshot:t.workflowSnapshot});return this.emitRetryLaunch(s.id,t.id),this.runJob(s.id),s}async retryFailedStep(e){let t=await this.jobs.get(e);if(!t)throw new y(`Job not found: ${e}`);if(t.status!=="failed")throw new J(`Job ${e} is not failed (status: ${t.status})`);let n=t.currentStepExecutionId;if(!n)throw new J(`Job ${e} has no currentStepExecutionId; cannot retry the failed step`);let o=at(t.stepHistory,n);if(!o)throw new J(`Job ${e} currentStepExecutionId ${n} was not found in stepHistory`);if(o.type==="sub_workflow")throw new J("Step-level retry is not available for sub_workflow steps. Retry the specific failed child job instead.");if(!Km.has(o.type))throw new J(`Step-level retry is not available for '${o.type}' steps`);let i=await this.workflowForJob(t),s=Bt(t.stepHistory,n);if(!s)throw new J(`Could not locate execution frame for ${n} on job ${e}`);let a=this.sequenceForFrameOnJob(t,i,s),u=a[s.index];if(!u||u.id!==o.stepDefinitionId)throw new J(`Failed step '${o.stepDefinitionId}' does not match sequence position ${s.index}`);let c=new Date().toISOString(),d={...t.context};delete d[o.stepDefinitionId];let m=await this.persistJob({...t,status:"planning",context:d,completedAt:void 0,currentStepId:o.stepDefinitionId,currentStepExecutionId:o.id,stepHistory:ee(t.stepHistory,o.id,S=>({...S,status:"running",error:void 0,completedAt:void 0,output:void 0,startedAt:c})),updatedAt:c}),b=await this.executeStepSequence(m,i,a,s.parentLoopExecutionId,s.iterationIndex,s.index,o.id);return b.outcome!=="completed"?b.job:s.parentLoopExecutionId!=null&&s.iterationIndex!=null?this.continueLoopAfterBody(b.job,i,s.parentLoopExecutionId,s.iterationIndex):this.completeJob(b.job,i)}async cancelJob(e){let t=await this.jobs.get(e);if(!t)throw new y(`Job not found: ${e}`);if(we(t.status))throw new J(`Job ${e} is already terminal (status: ${t.status})`);for(let i of di(t.stepHistory)){let s=await this.jobs.get(i);s&&!we(s.status)&&await this.cancelJob(i)}let n=await this.jobs.get(e);if(we(n.status))return n;this.cancellation.requestCancellation(e);let o=await this.persistCancelled(n);return(n.status==="waiting_for_human"||n.status==="waiting_for_children")&&this.cancellation.clear(e),await this.onBatchMemberTerminal(o.id),o}async cancelBatch(e){let t=await this.batches.get(e);if(!t)throw new y(`JobBatch not found: ${e}`);if(t.status!=="running")throw new J(`JobBatch ${e} is already terminal (status: ${t.status})`);let n=await this.jobs.list({batchId:e});for(let s of n)we(s.status)||await this.cancelJob(s.id);let o=new Date().toISOString(),i=await this.batches.update(e,{status:"cancelled",completedAt:o});if(!i)throw new Error(`Failed to persist cancelled batch ${e}`);return this.emit({type:"batch_cancelled",batchId:i.id,timestamp:o}),i}async executeStepSequence(e,t,n,o,i,s,a){let u=e;for(let c=s;c<n.length;c++){let d=await this.stopIfCancelled(u);if(d)return{outcome:"cancelled",job:d};let m=n[c],b=new Date().toISOString(),S=c===s?a:void 0,I,N=u.stepHistory;if(S){let A=at(u.stepHistory,S);if(!A)throw new Error(`Reuse execution ${S} not found on job ${u.id}`);I=A}else I={id:bi(),stepDefinitionId:m.id,type:m.type,status:"running",startedAt:b},N=pi(u.stepHistory,I,o,i);if(u=await this.persistJob({...u,status:u.status==="pending"?"planning":u.status,currentStepId:m.id,currentStepExecutionId:I.id,stepHistory:N,updatedAt:b}),u.status==="cancelled")return{outcome:"cancelled",job:u};this.emit({type:"step_started",jobId:u.id,stepDefinitionId:m.id,timestamp:b});try{let A=await this.dispatchStep(u,t,m,I.id,o,i);u=A.job;let He=await this.stopIfCancelled(u);if(He)return{outcome:"cancelled",job:He};if(A.outcome!=="completed")return A}catch(A){let He=await this.failJob(u,t,I.id,m.id,A);return He.status==="cancelled"?{outcome:"cancelled",job:He}:{outcome:"failed",job:He}}}return o!=null&&i!=null&&(u=await this.persistJob({...u,stepHistory:Jc(u.stepHistory,o,i),updatedAt:new Date().toISOString()})),{outcome:"completed",job:u}}async dispatchStep(e,t,n,o,i,s){switch(n.type){case"agent":return{outcome:"completed",job:await this.executeAgentStep(e,n,o)};case"interaction":return{outcome:"paused",job:await this.pauseForInteraction(e,t,n,o)};case"git":return{outcome:"completed",job:await this.executeGitStep(e,n,o)};case"provider_action":return{outcome:"completed",job:await this.executeProviderActionStep(e,n,o)};case"shell":return{outcome:"completed",job:await this.executeShellStep(e,n,o)};case"loop":return this.runLoopStep(e,t,n,o,i,s);case"sub_workflow":return this.runSubWorkflowStep(e,n,o);default:{let a=n;throw new h(`Step type '${a.type}' not yet supported by the Workflow Runner`)}}}async runLoopStep(e,t,n,o,i,s,a=0,u=n.maxIterations){let c=e,d=a;for(;;){if(d>=u)switch(n.onMaxIterations.action){case"fail":return c=await this.failExecution(c,t,o,n.id,`Loop '${n.id}' exceeded maxIterations (${u})`),{outcome:"failed",job:c};case"continue":return c=await this.finishExecution(c,o,n.id,{iterations:d,exitedOnMaxIterations:!0}),{outcome:"completed",job:c};case"ask_human":{let b={maxIterationsCheckpoint:!0,nextIteration:d,effectiveMaxIterations:u},S=new Date().toISOString(),I=ee(c.stepHistory,o,N=>({...N,status:"pending",output:b}));return c=await this.persistJob({...c,status:"waiting_for_human",currentStepId:n.id,currentStepExecutionId:o,stepHistory:I,updatedAt:S}),this.emit({type:"waiting_for_human",jobId:c.id,stepDefinitionId:n.id,interaction:"confirmation",data:b,questions:[`Loop '${n.id}' reached maxIterations (${u}). Extend, continue, or cancel?`],timestamp:S}),t.notificationPolicy.triggers.includes("on_needs_input")&&await this.notifications.send({title:`Input needed: ${t.name}`,body:`Job ${c.id} hit max iterations on loop '${n.id}'`,jobId:c.id}),{outcome:"paused",job:c}}default:{let b=n.onMaxIterations;throw new Error(`Unknown onMaxIterations action: ${JSON.stringify(b)}`)}}let m=await this.executeStepSequence(c,t,n.steps,o,d,0);if(c=m.job,m.outcome!=="completed")return m;if(Zc(n.until,c.context))return c=await this.finishExecution(c,o,n.id,{iterations:d+1}),{outcome:"completed",job:c};d+=1}}async resumeAskHuman(e,t,n,o){let i=o,s=n.output;if(!s?.maxIterationsCheckpoint)throw new Error(`Loop execution ${n.id} is not at an ask_human checkpoint`);let a=gr(t.steps,n.stepDefinitionId);if(!a||a.type!=="loop")throw new Error(`Loop step definition '${n.stepDefinitionId}' not found`);let u=Bt(e.stepHistory,n.id),c=new Date().toISOString();if(i.action==="cancel")return await this.failExecution({...e,status:"planning",currentStepId:void 0,currentStepExecutionId:void 0,updatedAt:c},t,n.id,a.id,"Loop cancelled by human at maxIterations checkpoint");if(i.action==="continue"){let I=await this.persistJob({...e,status:"planning",currentStepId:void 0,currentStepExecutionId:void 0,stepHistory:ee(e.stepHistory,n.id,N=>({...N,status:"completed",completedAt:c,output:{iterations:s.nextIteration,exitedOnMaxIterations:!0,humanAction:"continue"}})),updatedAt:c});return this.emit({type:"human_answered",jobId:I.id,answers:i,timestamp:c}),this.emit({type:"step_completed",jobId:I.id,stepDefinitionId:a.id,timestamp:c}),u?.parentLoopExecutionId!=null&&u.iterationIndex!=null?this.continueLoopAfterBody(I,t,u.parentLoopExecutionId,u.iterationIndex):this.continueTopLevelAfter(I,t,a.id)}let d=typeof i.additionalIterations=="number"?i.additionalIterations:0,m=s.effectiveMaxIterations+d,b=await this.persistJob({...e,status:"planning",currentStepId:void 0,currentStepExecutionId:void 0,stepHistory:ee(e.stepHistory,n.id,I=>({...I,status:"running",output:void 0})),updatedAt:c});this.emit({type:"human_answered",jobId:b.id,answers:i,timestamp:c});let S=await this.runLoopStep(b,t,a,n.id,u?.parentLoopExecutionId,u?.iterationIndex,s.nextIteration,m);return S.outcome!=="completed"?S.job:u?.parentLoopExecutionId!=null&&u.iterationIndex!=null?this.continueLoopAfterBody(S.job,t,u.parentLoopExecutionId,u.iterationIndex):this.continueTopLevelAfter(S.job,t,a.id)}async continueLoopAfterBody(e,t,n,o){let i=at(e.stepHistory,n);if(!i)throw new Error(`Loop execution ${n} not found`);let s=gr(t.steps,i.stepDefinitionId);if(!s||s.type!=="loop")throw new Error(`Loop step '${i.stepDefinitionId}' not found`);let a=Bt(e.stepHistory,n),u=i.output?.effectiveMaxIterations??s.maxIterations,c=e;if(Zc(s.until,c.context))c=await this.finishExecution(c,n,s.id,{iterations:o+1});else{let d=o+1,m=await this.runLoopStep(c,t,s,n,a?.parentLoopExecutionId,a?.iterationIndex,d,u);if(m.outcome!=="completed")return m.job;c=m.job}return a?.parentLoopExecutionId!=null&&a.iterationIndex!=null?this.continueLoopAfterBody(c,t,a.parentLoopExecutionId,a.iterationIndex):this.continueTopLevelAfter(c,t,s.id)}async continueTopLevelAfter(e,t,n){let o=t.steps.findIndex(s=>s.id===n),i=await this.executeStepSequence(e,t,t.steps,void 0,void 0,o+1);return i.outcome!=="completed"?i.job:this.completeJob(i.job,t)}sequenceForFrameOnJob(e,t,n){if(n.parentLoopExecutionId==null)return t.steps;let o=at(e.stepHistory,n.parentLoopExecutionId);if(!o)throw new Error(`Parent loop execution ${n.parentLoopExecutionId} not found`);let i=gr(t.steps,o.stepDefinitionId);if(!i||i.type!=="loop")throw new Error(`Parent loop step '${o.stepDefinitionId}' not found`);return i.steps}async runSubWorkflowStep(e,t,n){if(!e.subjectContext||e.subjectContext.mode!=="collection")throw new h(`sub_workflow steps require subjectContext.mode === 'collection' (job ${e.id})`);let o=e.subjectContext.subjects,i=[];for(let d=0;d<o.length;d++){let m=o[d],b=await this.createJob({workflowId:t.workflowId,subjectContext:{mode:"single",subject:m},inputValues:{},parentJobId:e.id,parentStepExecutionId:n,fanOutIndex:d});i.push(b)}let s=i.map(d=>d.id),a=new Date().toISOString(),u=ee(e.stepHistory,n,d=>({...d,status:"waiting_for_children",childJobIds:s})),c=await this.persistJob({...e,status:"waiting_for_children",currentStepId:t.id,currentStepExecutionId:n,stepHistory:u,updatedAt:a});for(let d of i)this.emit({type:"job_started",jobId:d.id,timestamp:a}),this.runJob(d.id);return{outcome:"paused",job:c}}async onChildTerminal(e){let t=await this.jobs.get(e);if(!t?.parentJobId||!t.parentStepExecutionId)return;let n=`${t.parentJobId}:${t.parentStepExecutionId}`;if(!this.childTerminalLocks.has(n)){this.childTerminalLocks.add(n);try{let o=(await this.jobs.list({parentJobId:t.parentJobId,parentStepExecutionId:t.parentStepExecutionId})).filter(A=>A.parentStepExecutionId===t.parentStepExecutionId),i=fi(o,A=>A.fanOutIndex);if(!i?.allTerminal)return;let{activeJobs:s}=i,a=await this.jobs.get(t.parentJobId);if(!a||a.status==="cancelled"||a.status!=="waiting_for_children"&&a.status!=="failed")return;let u=await this.workflowForJob(a),c=t.parentStepExecutionId,d=at(a.stepHistory,c);if(!d||d.type!=="sub_workflow")return;let m=s.some(A=>A.status==="failed");if(s.some(A=>A.status==="cancelled"))return;if(m){await this.failExecution(a,u,c,d.stepDefinitionId,"One or more child jobs failed");return}let S=s.slice().sort((A,He)=>(A.fanOutIndex??0)-(He.fanOutIndex??0)).map(A=>({fanOutIndex:A.fanOutIndex,jobId:A.id,output:A.context})),I=new Date().toISOString();a=await this.persistJob({...a,status:"planning",context:{...a.context,[d.stepDefinitionId]:S},currentStepId:void 0,currentStepExecutionId:void 0,stepHistory:ee(a.stepHistory,c,A=>({...A,status:"completed",completedAt:I,output:S})),completedAt:void 0,updatedAt:I}),this.emit({type:"step_completed",jobId:a.id,stepDefinitionId:d.stepDefinitionId,timestamp:I});let N=await this.continueTopLevelAfter(a,u,d.stepDefinitionId)}finally{this.childTerminalLocks.delete(n)}}}async onBatchMemberTerminal(e){let t=await this.jobs.get(e);if(!t?.batchId)return;let n=t.batchId;if(!this.batchTerminalLocks.has(n)){this.batchTerminalLocks.add(n);try{let o=await this.batches.get(t.batchId);if(!o||o.status!=="running")return;let i=await this.jobs.list({batchId:o.id}),s=fi(i,m=>m.fanOutIndex);if(!s||s.groupCount!==o.resolvedSubjects.length||!s.allTerminal)return;let{activeJobs:a}=s,u=Wc(a),c=new Date().toISOString(),d=await this.batches.update(o.id,{status:u,completedAt:c});if(!d)return;if(this.emit({type:"batch_completed",batchId:d.id,summary:a.map(m=>({jobId:m.id,status:m.status})),timestamp:c}),!d.notificationSent){let m=await this.workflowForJob(t),b=d.notificationOverride??m.notificationPolicy,S=u==="completed"?"on_complete":"on_fail";b.triggers.includes(S)&&await this.notifications.send({title:`Batch ${u}: ${m.name}`,body:`JobBatch ${d.id} finished with status '${u}' (${a.length} members)`,batchId:d.id}),await this.batches.update(d.id,{notificationSent:!0})}}finally{this.batchTerminalLocks.delete(n)}}}async resolveSelection(e){if(e.mode==="view")return Bn(e.viewId,this.views,this.providers);let t=[];for(let n of e.subjectIds)if(e.subjectType==="ticket"){let o=await this.getTicketById(n);t.push({subjectType:"ticket",...o})}else if(e.subjectType==="pull_request"){let o=await this.getPullRequestById(n);t.push({subjectType:"pull_request",...o})}else if(e.subjectType==="documentation"){let o=await this.getDocumentationById(n);t.push({subjectType:"documentation",...o})}else throw new h(`Unsupported subjectType: ${e.subjectType}`);return t}async executeAgentStep(e,t,n){let o=await Hc(t.contextFileIds??[],this.contextFiles,this.logger),i=Dt(e),s=wr(t.objective,i),a=t.agentInstanceId??(await this.settings.get()).defaultAgentInstanceId;if(!a)throw new Error("No default agent instance configured (set EngineSettings.defaultAgentInstanceId)");let u=await this.providers.getAgentProvider(a).run({objective:s,outputFormat:t.outputFormat,knowledge:o,context:{...i,stepId:t.id},...e.worktreePath?{cwd:e.worktreePath}:{}}),c=Uc(t.outputFormat,u.parsed);return this.finishExecution(e,n,t.id,c)}async executeGitStep(e,t,n){let o=qt(t.params,Dt(e));switch(t.operation){case"create_worktree":{let i=await Xc({job:e,params:o,git:this.git,jobs:this.jobs,localRepositories:this.localRepositories});return this.finishExecution(e,n,t.id,i,{worktreePath:i.worktreePath,branch:i.branch})}case"create_branch":{let i=Jn(e),s=bt(o,"branchName");return await this.git.createBranch(i,{branchName:s,...typeof o.baseBranch=="string"?{baseBranch:o.baseBranch}:{}}),this.finishExecution(e,n,t.id,{branch:s},{branch:s})}case"checkout":{let i=Jn(e),s=bt(o,"branch");return await this.git.checkout(i,{branch:s}),this.finishExecution(e,n,t.id,{branch:s},{branch:s})}case"commit":{let i=Jn(e),s=await this.git.commit(i,{message:bt(o,"message"),addAll:o.addAll!==!1});return this.finishExecution(e,n,t.id,s)}case"push":{let i=Jn(e);return await this.git.push(i,{...typeof o.remote=="string"?{remote:o.remote}:{},...typeof o.branch=="string"?{branch:o.branch}:{}}),this.finishExecution(e,n,t.id,{remote:typeof o.remote=="string"?o.remote:"origin",branch:typeof o.branch=="string"?o.branch:e.branch})}default:{let i=t.operation;throw new Error(`Unknown git operation: ${i}`)}}}async executeProviderActionStep(e,t,n){if(!e.subjectContext||e.subjectContext.mode!=="single")throw new h(`provider_action steps require subjectContext.mode === 'single' (job ${e.id})`);let o=this.resolveProviderActionSubject(e,t);if(t.extendedAction)return this.executeExtendedProviderAction(e,t,n,o);let i=qt(t.params??{},Dt(e))??{},s=await this.dispatchPortableProviderAction(o,t.action,i);return this.finishExecution(e,n,t.id,s)}resolveProviderActionSubject(e,t){if(!t.target){let o=e.subjectContext;if(!o||o.mode!=="single")throw new h(`provider_action steps require subjectContext.mode === 'single' (job ${e.id})`);let i=o.subject;return{subjectType:i.subjectType,source:i.source,subjectId:i.id}}let n=wr(t.target.subjectId,Dt(e)).trim();if(!n)throw new Error(`provider_action '${t.id}' target.subjectId interpolated to an empty id`);return{subjectType:t.target.subjectType,source:t.target.source,subjectId:n}}async dispatchPortableProviderAction(e,t,n){let{subjectType:o,source:i,subjectId:s}=e;if(o==="documentation"){let u=this.providers.getDocumentationProvider(i);switch(t){case"get_subject":return u.get(s);case"get_content":return u.getContent(s);case"get_comments":return u.getComments(s);case"post_comment":return await u.postComment(s,bt(n,"body")),{posted:!0};case"update_status":throw new Error(`Provider action '${t}' is not valid for subject type 'documentation'`);default:{let c=t;throw new Error(`Unknown provider action: ${c}`)}}}let a=o==="ticket"?this.providers.getTicketProvider(i):o==="pull_request"?this.providers.getRepoProvider(i):null;if(!a)throw new Error(`Unsupported subjectType for provider_action: ${o}`);switch(t){case"get_subject":return a.get(s);case"get_comments":return a.getComments(s);case"post_comment":return await a.postComment(s,bt(n,"body")),{posted:!0};case"update_status":return await a.updateStatus(s,bt(n,"status")),{status:bt(n,"status")};case"get_content":throw new Error(`Provider action 'get_content' is not valid for subject type '${o}'`);default:{let u=t;throw new Error(`Unknown provider action: ${u}`)}}}async executeExtendedProviderAction(e,t,n,o){let i=t.extendedAction,s=o.subjectType==="documentation"?this.providers.getDocumentationProvider(i.providerId):o.subjectType==="ticket"?this.providers.getTicketProvider(i.providerId):o.subjectType==="pull_request"?this.providers.getRepoProvider(i.providerId):null;if(!s)throw new Error(`Unsupported subjectType for provider_action: ${o.subjectType}`);if(!Qa(s))throw new Error(`Provider instance '${i.providerId}' does not support extended actions. Available: none`);let a=await s.listExtendedActions(),u=a.find(m=>m.actionId===i.actionId);if(!u)throw new Error(`Provider '${i.providerId}' has no extended action '${i.actionId}'. Available: ${Ot(a)}`);let c=qt(i.params??{},Dt(e))??{};dn(u,c);let d=await s.executeExtendedAction(i.actionId,{...c,subjectId:o.subjectId});return this.finishExecution(e,n,t.id,d)}async executeShellStep(e,t,n){let o=wr(t.command,Dt(e)),i=e.worktreePath??process.cwd();try{let s=await Vm(o,{cwd:i,windowsHide:!0});return this.finishExecution(e,n,t.id,{exitCode:0,stdout:String(s.stdout??""),stderr:String(s.stderr??"")})}catch(s){let a=s,u=a.stderr??"",c=a.stdout??"",d=typeof a.code=="number"?a.code:Number.parseInt(String(a.code??"1"),10)||1;throw new Error(`shell command failed (exit ${d}, cwd=${i}): ${u||c||a.message||o}`)}}async pauseForInteraction(e,t,n,o){let i=new Date().toISOString(),s=Gm(t,n.id),a=s!=null?e.context[s]:void 0,u=ee(e.stepHistory,o,b=>({...b,status:"pending"})),c=await this.persistJob({...e,status:"waiting_for_human",currentStepId:n.id,currentStepExecutionId:o,stepHistory:u,updatedAt:i}),d=Fc(n.interaction,a);return this.emit({type:"waiting_for_human",jobId:c.id,stepDefinitionId:n.id,interaction:n.interaction,data:a,questions:d,timestamp:i}),t.notificationPolicy.triggers.includes("on_needs_input")&&n.notify!==!1&&await this.notifications.send({title:`Input needed: ${t.name}`,body:`Job ${c.id} is waiting for human input on step '${n.id}'`,jobId:c.id}),c}async finishExecution(e,t,n,o,i={}){let s=new Date().toISOString(),a=ee(e.stepHistory,t,c=>({...c,status:"completed",completedAt:s,output:o})),u=await this.persistJob({...e,...i,context:{...e.context,[n]:o},stepHistory:a,updatedAt:s});return this.emit({type:"step_completed",jobId:u.id,stepDefinitionId:n,timestamp:s}),u}async failExecution(e,t,n,o,i){return this.failJob(e,t,n,o,new Error(i))}async completeJob(e,t){let n=new Date().toISOString(),o=await this.persistJob({...e,status:"completed",currentStepId:void 0,currentStepExecutionId:void 0,completedAt:n,updatedAt:n});return o.status==="cancelled"||(this.emit({type:"job_completed",jobId:o.id,timestamp:n}),await this.onBatchMemberTerminal(o.id),!o.batchId&&t.notificationPolicy.triggers.includes("on_complete")&&await this.notifications.send({title:`Job completed: ${t.name}`,body:`Job ${o.id} completed successfully`,jobId:o.id})),o}async failJob(e,t,n,o,i){let s=i instanceof Error?i.message:String(i),a=new Date().toISOString(),u=ee(e.stepHistory,n,d=>({...d,status:"failed",completedAt:a,error:s})),c=await this.persistJob({...e,status:"failed",currentStepId:o,currentStepExecutionId:n,stepHistory:u,completedAt:a,updatedAt:a});return this.emit({type:"step_failed",jobId:c.id,stepDefinitionId:o,error:s,timestamp:a}),c.status==="cancelled"?(await this.onBatchMemberTerminal(c.id),c):(this.emit({type:"job_failed",jobId:c.id,error:s,timestamp:a}),await this.onBatchMemberTerminal(c.id),!c.batchId&&t.notificationPolicy.triggers.includes("on_fail")&&await this.notifications.send({title:`Job failed: ${t.name}`,body:`Job ${c.id} failed on step '${o}': ${s}`,jobId:c.id}),c)}async resolveSubjectContext(e,t){if(e.appliesTo==="none")return;let n=zm(e.appliesTo);if(!t)throw new Error(`Workflow '${e.id}' applies to '${n}' but no subjectId was provided`);if(n==="ticket")return{mode:"single",subject:{subjectType:"ticket",...await this.getTicketById(t)}};if(n==="pull_request")return{mode:"single",subject:{subjectType:"pull_request",...await this.getPullRequestById(t)}};if(n==="documentation")return{mode:"single",subject:{subjectType:"documentation",...await this.getDocumentationById(t)}};throw new Error(`Unsupported subjectType for workflow subject resolution: ${n}`)}async workflowForJob(e){return e.workflowSnapshot?e.workflowSnapshot:(this.logger.warn(`Job ${e.id} has no workflowSnapshot; falling back to live WorkflowDefinition ${e.workflowId}`),this.requireWorkflow(e.workflowId))}async requireWorkflow(e){let t=await this.workflows.get(e);if(!t)throw new y(`Workflow not found: ${e}`);return t}emitRetryLaunch(e,t){let n=new Date().toISOString();this.emit({type:"job_started",jobId:e,timestamp:n}),this.emit({type:"job_retried",jobId:e,retryOf:t,timestamp:n})}inputValuesFromContext(e,t){let n={};for(let o of t.inputSchema)Object.prototype.hasOwnProperty.call(e,o.name)&&(n[o.name]=e[o.name]);return n}async persistCancelled(e){let t=new Date().toISOString();return this.persistJob({...e,status:"cancelled",completedAt:e.completedAt??t,updatedAt:t})}async stopIfCancelled(e){return!this.cancellation.isCancellationRequested(e.id)&&e.status!=="cancelled"&&(await this.jobs.get(e.id))?.status!=="cancelled"?null:(this.cancellation.clear(e.id),e.status==="cancelled"?e:this.persistCancelled(e))}async persistJob(e){let t=await this.jobs.get(e.id),n=this.cancellation.isCancellationRequested(e.id)||t?.status==="cancelled"||e.status==="cancelled",o=n?"cancelled":e.status,i=n?t?.completedAt??e.completedAt??e.updatedAt:e.completedAt,s=await this.jobs.update(e.id,{status:o,context:e.context,currentStepId:e.currentStepId,currentStepExecutionId:e.currentStepExecutionId,stepHistory:e.stepHistory,worktreePath:e.worktreePath,branch:e.branch,updatedAt:e.updatedAt,completedAt:i});if(!s)throw new Error(`Failed to persist job ${e.id}`);return t?.status!=="cancelled"&&s.status==="cancelled"&&this.emit({type:"job_cancelled",jobId:s.id,timestamp:s.updatedAt}),s}emit(e){this.events.emit(e)}async getTicketById(e){return Si(this.providers.ticketInstanceIds(),t=>this.providers.getTicketProvider(t).get(e),`Ticket not found: ${e}`)}async getPullRequestById(e){return Si(this.providers.repoInstanceIds(),t=>this.providers.getRepoProvider(t).get(e),`Pull request not found: ${e}`)}async getDocumentationById(e){return Si(this.providers.documentationInstanceIds(),t=>this.providers.getDocumentationProvider(t).get(e),`Documentation page not found: ${e}`)}};ge=xi=Jm([Um(),pe(0,de(O)),pe(1,de(z)),pe(2,de(se)),pe(3,de(ie)),pe(4,de(ye)),pe(5,de(F)),pe(6,de(Yt)),pe(7,de(ae)),pe(8,de(ce)),pe(9,de(Be)),pe(10,de(R)),pe(11,de(gt)),Lm("design:paramtypes",[O,z,se,ie,ye,F,Object,ae,ce,Be,Object,gt])],ge)});import{Module as Xm}from"@nestjs/common";var Qm,Ft,vi=l(()=>{"use strict";dr();Cn();On();Bc();Ln();yi();Qm=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Ft=class{};Ft=Qm([Xm({imports:[Re,it,st,qn],providers:[gt,ge],exports:[ge]})],Ft)});import{Catch as Zm}from"@nestjs/common";var Ym,Un,tu=l(()=>{"use strict";E();Ym=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Un=class{catch(e,t){t.switchToHttp().getResponse().status(e.httpStatus).json({error:e.message})}};Un=Ym([Zm(wt)],Un)});var v,ne=l(()=>{"use strict";E();v=class{schema;constructor(e){this.schema=e}transform(e){let t=this.schema.safeParse(e);if(!t.success){let n=t.error.issues.map(o=>`${o.path.join(".")||"(root)"}: ${o.message}`).join("; ");throw new h(`Validation failed: ${n}`)}return t.data}}});import{randomUUID as eh}from"node:crypto";function th(){return eh()}function Mn(r){let e=r.id??th(),t=na(r.steps),n=ru(r.steps,t);return{...r,id:e,steps:n}}function ru(r,e){return r.map(t=>{let n=t.id;return n||(n=ea(t.name,e),e.add(n)),t.type==="loop"?{...t,id:n,steps:ru(t.steps,e)}:{...t,id:n}})}var ji=l(()=>{"use strict";C()});function nu(r,e,t){if(!r)throw new y(`Workflow not found: ${e}`);if(r.appliesTo==="none")throw new h(`Cannot bind a View to workflow '${e}' because appliesTo is 'none'`);if(!ya(r.appliesTo,t))throw new h(`subjectType '${t}' is not included in workflow '${e}' appliesTo`);return r}function ou(r,e){if(!r)throw new y(`Workflow not found: ${e}`);if(r.appliesTo!=="none")throw new h(`WorkflowShortcut requires appliesTo 'none', got '${String(r.appliesTo)}'`);if(r.subjectHandling!=="per-subject")throw new h(`WorkflowShortcut requires subjectHandling 'per-subject', got '${r.subjectHandling}'`);return r}function Wn(r){if(r.appliesTo==="none"&&r.subjectHandling==="collection")throw new h("Workflows with appliesTo 'none' must use subjectHandling 'per-subject'")}var Sr=l(()=>{"use strict";C();E()});function iu(r){return r.issues.map(e=>`${e.path.join(".")||"(root)"}: ${e.message}`).join("; ")}async function Hn(r,e){let t=et.safeParse(e);if(!t.success)throw new h(`Validation failed: ${iu(t.error)}`);let n=Mn(t.data),o=mt.safeParse(n);if(!o.success)throw new h(`Validation failed: ${iu(o.error)}`);return Wn(o.data),r.create(o.data)}var Ii=l(()=>{"use strict";C();E();Sr();ji()});import{Body as su,Controller as rh,Delete as nh,Get as au,HttpCode as oh,Inject as ih,Param as _i,Patch as sh,Post as ah,Query as ch}from"@nestjs/common";var Nt,U,St,De,cu=l(()=>{"use strict";C();ft();E();ne();ji();Ii();Sr();Nt=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},U=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},St=function(r,e){return function(t,n){e(t,n,r)}},De=class{workflows;constructor(e){this.workflows=e}async list(e){if(e!=null&&e!==""&&e!=="per-subject"&&e!=="collection")throw new h(`Invalid subjectHandling filter: ${e}`);return this.workflows.list(e?{subjectHandling:e}:{})}async get(e){let t=await this.workflows.get(e);if(!t)throw new y(`Workflow not found: ${e}`);return t}async create(e){return Hn(this.workflows,e)}async update(e,t){let n=Mn({...t,id:e}),o=mt.safeParse(n);if(!o.success){let u=o.error.issues.map(c=>`${c.path.join(".")||"(root)"}: ${c.message}`).join("; ");throw new h(`Validation failed: ${u}`)}Wn(o.data);let{id:i,...s}=o.data,a=await this.workflows.update(e,s);if(!a)throw new y(`Workflow not found: ${e}`);return a}async remove(e){if(!await this.workflows.get(e))throw new y(`Workflow not found: ${e}`);if(!await this.workflows.delete(e))throw new y(`Workflow not found: ${e}`)}};Nt([au(),St(0,ch("subjectHandling")),U("design:type",Function),U("design:paramtypes",[String]),U("design:returntype",Promise)],De.prototype,"list",null);Nt([au(":id"),St(0,_i("id")),U("design:type",Function),U("design:paramtypes",[String]),U("design:returntype",Promise)],De.prototype,"get",null);Nt([ah(),St(0,su()),U("design:type",Function),U("design:paramtypes",[Object]),U("design:returntype",Promise)],De.prototype,"create",null);Nt([sh(":id"),St(0,_i("id")),St(1,su(new v(et))),U("design:type",Function),U("design:paramtypes",[String,Object]),U("design:returntype",Promise)],De.prototype,"update",null);Nt([nh(":id"),oh(204),St(0,_i("id")),U("design:type",Function),U("design:paramtypes",[String]),U("design:returntype",Promise)],De.prototype,"remove",null);De=Nt([rh("workflows"),St(0,ih(O)),U("design:paramtypes",[O])],De)});function uh(r){return lu(r.workflowDefinition.steps,"steps")}function uu(r){let e=uh(r);if(e.length>0)throw new Error(`Workflow library entry '${r.id}' is not portable: ${e.join(", ")}`)}function lu(r,e){let t=[];return r.forEach((n,o)=>{let i=`${e}[${o}]`;n.type==="provider_action"&&(n.target&&t.push(`${i}.target`),n.extendedAction&&t.push(`${i}.extendedAction`)),n.type==="loop"&&t.push(...lu(n.steps,`${i}.steps`))}),t}var pu=l(()=>{"use strict"});function du(){return structuredClone(Pi)}function fu(r){let e=Pi.find(t=>t.id===r);return e?structuredClone(e):void 0}var lh,ph,Pi,mu=l(()=>{"use strict";pu();lh={id:"clarify-then-summarize",source:"example",name:"Clarify then summarize",description:"Asks clarifying questions in a loop until none remain, then summarizes the answers.",workflowDefinition:{name:"Clarify then summarize",description:"Asks clarifying questions in a loop until none remain, then summarizes the answers.",appliesTo:"none",subjectHandling:"per-subject",inputSchema:[{name:"topic",label:"Topic",type:"string",required:!0}],steps:[{type:"loop",name:"Clarify",steps:[{type:"agent",name:"Draft questions",objective:"Draft clarifying questions about {{topic}}. If you have no remaining questions, return an empty list.",outputFormat:"questionnaire"},{type:"interaction",name:"Collect answers",interaction:"questionnaire"}],until:{type:"field_empty",stepId:"draft-questions",field:"questions"},maxIterations:5,onMaxIterations:{action:"continue"}},{type:"agent",name:"Summarize",objective:"Produce a final summary for {{topic}} using these answers: {{collect-answers}}",outputFormat:"free_text"}],notificationPolicy:{triggers:["on_needs_input","on_complete","on_fail"]}}},ph={id:"pr-review",source:"example",name:"PR Review",description:"Reviews a pull request for acceptance criteria, code quality, and test coverage.",workflowDefinition:{name:"PR Review",description:"Reviews a pull request for acceptance criteria, code quality, and test coverage.",appliesTo:"pull_request",subjectHandling:"per-subject",inputSchema:[{name:"repoPath",label:"Repository path",type:"localRepository",required:!0},{name:"ticketDescription",label:"Related ticket description (optional)",type:"string",required:!1}],steps:[{type:"git",name:"Prepare review worktree",operation:"create_worktree",params:{repoPath:"{{repoPath}}",baseBranch:"{{subject.sourceBranch}}",branchName:"review/{{subject.id}}"}},{type:"agent",name:"Build requirements checklist",objective:`Ticket: {{ticketDescription}}
|
|
20
|
+
`)}function yr(r,e){return e==="free_text"?r:tc(r)}function tc(r){let e=[...r.matchAll(/```json\s*([\s\S]*?)```/gi)].map(o=>o[1].trim()),t=[...r.matchAll(/```\s*([\s\S]*?)```/g)].map(o=>o[1].trim()),n=[...e].reverse();n.length===0&&n.push(...[...t].reverse()),n.push(r.trim());for(let o of n)if(o)try{return JSON.parse(o)}catch{continue}throw new Error("No valid JSON block found in agent response")}var df,pf,ff,mf,un=l(()=>{"use strict";Oe();df={user:"User preferences",organization:"Organization guidelines",project:"Project context"},pf=["user","organization","project"],ff={questionnaire:'Respond with a single fenced JSON block matching this shape exactly: {"questions":[{"id":"<string>","prompt":"<string>"}]}. No other prose outside the fence.',confirmation:'Respond with a single fenced JSON block matching this shape exactly: {"approved":<boolean>}. No other prose outside the fence.',comment_suggestions:'Respond with a single fenced JSON block matching this shape exactly: {"suggestions":[{"body":"<string>"}]}. No other prose outside the fence.',free_text:"Respond in plain text. Do not wrap the answer in a JSON object."},mf={anthropic:"Anthropic",cursor:"Cursor"}});async function*yf(r){let{query:e}=await import("@anthropic-ai/claude-agent-sdk"),t=r.options;yield*e({prompt:r.prompt,options:{permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,...t?.cwd?{cwd:t.cwd}:{},...t?.resume?{resume:t.resume}:{},...t?.model?{model:t.model}:{},...t?.env?{env:t.env}:{}}})}var hf,ln,rc=l(()=>{"use strict";un();Oe();un();hf=kt("anthropic"),ln=class{secrets;options;constructor(e,t={}){this.secrets=e,this.options=t}async run(e){let t=await this.requireApiKey(),n=hr(e),o={permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,env:{...process.env,ANTHROPIC_API_KEY:t}};e.cwd&&(o.cwd=e.cwd),e.sessionId&&(o.resume=e.sessionId),this.options.model&&(o.model=this.options.model);let i=this.options.queryFn??yf,s,a,u;for await(let c of i({prompt:n,options:o}))c.session_id&&(s=c.session_id),c.type==="result"&&(c.subtype==="success"&&typeof c.result=="string"?a=c.result:u=c.errors?.join("; ")||c.subtype||"Claude agent returned an error result");if(u)throw new Error(`Claude agent failed: ${u}`);if(a==null)throw new Error("Claude agent returned no result text");if(!s)throw new Error("Claude agent returned no session id");return{raw:a,parsed:yr(a,e.outputFormat),sessionId:s}}async requireApiKey(){let e=this.options.secretKey?.trim()||hf,t=await this.secrets.get(e);if(!t)throw cn("anthropic",e);return t}}});function wf(r,e,t){return{apiKey:r,...t?{model:{id:t}}:{},local:{...e?{cwd:e}:{},settingSources:[]}}}async function bf(){let{Agent:r}=await import("@cursor/sdk");return{create:e=>r.create({apiKey:e.apiKey,...e.model?{model:e.model}:{},local:{...e.local?.cwd?{cwd:e.local.cwd}:{},settingSources:[]}}),resume:(e,t)=>r.resume(e,{apiKey:t.apiKey,...t.model?{model:t.model}:{},local:{...t.local?.cwd?{cwd:t.local.cwd}:{},settingSources:[]}})}}var gf,dn,nc=l(()=>{"use strict";un();Oe();gf=kt("cursor"),dn=class{secrets;options;constructor(e,t={}){this.secrets=e,this.options=t}async run(e){let t=await this.requireApiKey(),n=hr(e),o=this.options.sdk??await bf(),i=wf(t,e.cwd,this.options.model),s=e.sessionId?await o.resume(e.sessionId,i):await o.create(i);try{let u=await(await s.send(n)).wait();if(u.status!=="finished")throw new Error(u.error?.message||`Cursor agent ended with status '${u.status}'`);let c=u.result??"";return{raw:c,parsed:yr(c,e.outputFormat),sessionId:s.agentId}}finally{await s[Symbol.asyncDispose]?.()}}async requireApiKey(){let e=this.options.secretKey?.trim()||gf,t=await this.secrets.get(e);if(!t)throw cn("cursor",e);return t}}});function oc(r){return typeof r=="object"&&r!=null&&typeof r.listExtendedActions=="function"&&typeof r.executeExtendedAction=="function"}function pn(r,e){let t=r.params.filter(n=>n.required).filter(n=>{let o=e[n.name];return o==null||typeof o=="string"&&o.trim()===""}).map(n=>n.name);if(t.length>0)throw new Error(`Extended action '${r.actionId}' is missing required params: ${t.join(", ")}`)}function qt(r){return r.length===0?"none":r.map(e=>e.actionId).join(", ")}var fn=l(()=>{"use strict"});function gr(r){return r==null?"":typeof r=="string"?r:ic(r).replace(/\n+$/,"")}function mn(r){return{version:1,type:"doc",content:r.split(`
|
|
21
|
+
`).map(t=>({type:"paragraph",content:t.length===0?[]:[{type:"text",text:t}]}))}}function ic(r){if(r==null||typeof r!="object")return"";let e=r;if(e.type==="text")return e.text??"";if(e.type==="hardBreak")return`
|
|
22
|
+
`;let t=(e.content??[]).map(ic).join("");return e.type==="paragraph"||e.type==="heading"||e.type==="blockquote"||e.type==="listItem"?`${t}
|
|
23
|
+
`:t}var Go=l(()=>{"use strict"});function If(r,e){return e.startsWith("http://")||e.startsWith("https://")?e:`${r.replace(/\/$/,"")}${e.startsWith("/")?e:`/${e}`}`}function ac(r){return{representation:"atlas_doc_format",value:JSON.stringify(mn(r))}}function uc(r){return gr(jf(r))}function jf(r){if(r==null||typeof r!="object")return r;let e=r.atlas_doc_format;if(e!=null){if(typeof e=="object"&&e!==null&&"value"in e){let t=e.value;if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t}return e}}function cc(r,e,t){return{id:String(r.id??""),source:t,title:String(r.title??""),url:_f(e,r),raw:r}}function _f(r,e){let t=r.replace(/\/$/,""),n=e._links?.webui?.trim();if(n)return n.startsWith("http://")||n.startsWith("https://")?n:n.startsWith("/wiki")?`${t}${n}`:`${t}/wiki${n.startsWith("/")?n:`/${n}`}`;let o=e.id!=null?String(e.id):"";return o?`${t}/wiki/pages/${encodeURIComponent(o)}`:t}function Ef(r,e){return{id:String(r.id??""),subjectId:e,body:uc(r.body),createdAt:r.version?.createdAt??r.createdAt??"",raw:r}}var Sf,xf,vf,sc,hn,yn,zo=l(()=>{"use strict";fn();Go();Sf="kno.confluence.apiToken",xf=50,vf=10,sc=500,hn=[{actionId:"create_page",label:"Create Confluence page",params:[{name:"spaceKey",label:"Space key",type:"string",required:!0},{name:"title",label:"Title",type:"string",required:!0},{name:"content",label:"Content",type:"string",required:!0}]}],yn=class{secrets;fetchFn;instanceId;baseUrl;email;secretKey;constructor(e,t,n=fetch){this.secrets=e,this.fetchFn=n,this.instanceId=t.instanceId,this.baseUrl=t.baseUrl?.trim()||void 0,this.email=t.email?.trim()||void 0,this.secretKey=t.secretKey?.trim()||Sf}async get(e){let{baseUrl:t}=await this.requireConfig(),n=await this.request("GET",`/wiki/api/v2/pages/${encodeURIComponent(e)}`);return cc(n,t,this.instanceId)}async getContent(e){await this.requireConfig();let t=await this.request("GET",`/wiki/api/v2/pages/${encodeURIComponent(e)}?body-format=atlas_doc_format`);return uc(t.body)}async query(e){let t=e.pageIds;if(!Array.isArray(t))throw new Error("Documentation query requires { pageIds: string[] }");let n=[];for(let o of t)n.push(await this.get(String(o)));return n}async getComments(e){await this.requireConfig();let t=[],n=`/wiki/api/v2/pages/${encodeURIComponent(e)}/footer-comments?body-format=atlas_doc_format&limit=${xf}`,o=new Set;for(let i=0;i<vf&&t.length<sc&&!(!n||o.has(n));i++){o.add(n);let s=await this.request("GET",n),a=Array.isArray(s.results)?s.results:[];for(let c of a){if(t.length>=sc)break;t.push(Ef(c,e))}let u=typeof s._links?.next=="string"?s._links.next:void 0;if(!u||a.length===0)break;n=u}return t}async postComment(e,t){await this.requireConfig(),await this.request("POST","/wiki/api/v2/footer-comments",{body:{pageId:e,body:ac(t)}})}listExtendedActions(){return hn}async executeExtendedAction(e,t){if(e==="create_page")return this.createPage(t);throw new Error(`Provider 'confluence' has no extended action '${e}'. Available: ${qt(this.listExtendedActions())}`)}async createPage(e){let t=hn[0];pn(t,e);let n=String(e.spaceKey).trim(),o=String(e.title).trim(),i=String(e.content),{baseUrl:s}=await this.requireConfig(),a=await this.resolveSpaceId(n),u=await this.request("POST","/wiki/api/v2/pages",{body:{spaceId:a,status:"current",title:o,body:ac(i)}});return cc(u,s,this.instanceId)}async resolveSpaceId(e){let t=await this.request("GET",`/wiki/api/v2/spaces?keys=${encodeURIComponent(e)}`),n=Array.isArray(t.results)?t.results:[],o=n.find(s=>(s.key??"").toLowerCase()===e.toLowerCase())??n[0],i=o?.id!=null?String(o.id):"";if(!i)throw new Error(`Confluence space '${e}' was not found`);return i}async requireConfig(){let e=this.baseUrl,t=this.email,n=await this.secrets.get(this.secretKey);if(!e||!t||!n){let o=[];throw e||o.push("config.baseUrl"),t||o.push("config.email"),n||o.push(`SecretStore '${this.secretKey}'`),new Error(`Confluence instance '${this.instanceId}' is not configured \u2014 missing ${o.join(", ")}. Set baseUrl and email on the provider instance, and store the API token with: POST /api/secrets/${this.secretKey} or npm --workspace apps/engine run set-secret -- ${this.secretKey} <value>`)}return{baseUrl:e,email:t,token:n}}async request(e,t,n={}){let{baseUrl:o,email:i,token:s}=await this.requireConfig(),a=If(o,t),u={Authorization:`Basic ${Buffer.from(`${i}:${s}`).toString("base64")}`,Accept:"application/json"};n.body!==void 0&&(u["Content-Type"]="application/json");let c=await this.fetchFn(a,{method:e,headers:u,...n.body!==void 0?{body:JSON.stringify(n.body)}:{}});if(!c.ok){let m=await c.text().catch(()=>"");throw new Error(`Confluence ${e} ${t} failed (${c.status}): ${m||c.statusText}`)}if(c.status===204)return;let p=await c.text();if(p)return JSON.parse(p)}}});import{randomUUID as Pf}from"node:crypto";var Rf,gn,lc=l(()=>{"use strict";Rf=new Set(["github_wiki","gitlab_wiki","azure_wiki","web"]),gn=class{pages;contentById;comments;instanceId;type;constructor(e=[],t){this.pages=new Map,this.contentById=new Map,this.comments=new Map,this.instanceId=t?.instanceId,this.type=t?.type;for(let n of e){let{content:o,...i}=n;this.pages.set(i.id,structuredClone(i)),o!==void 0&&this.contentById.set(i.id,o)}}async get(e){let t=this.pages.get(e);if(!t)throw new Error(`Documentation page not found: ${e}`);return this.withSource(structuredClone(t))}async getContent(e){await this.get(e);let t=this.contentById.get(e);if(t===void 0)throw new Error(`Documentation content not found: ${e}`);return t}async query(e){let t=e.pageIds;if(!Array.isArray(t))throw new Error("Documentation query requires { pageIds: string[] }");let n=[];for(let o of t)n.push(await this.get(String(o)));return n}async getComments(e){let t=await this.get(e);return this.assertCommentsSupported(t),structuredClone(this.comments.get(e)??[])}async postComment(e,t){let n=await this.get(e);this.assertCommentsSupported(n);let o=this.comments.get(e)??[];o.push({id:Pf(),subjectId:e,body:t,createdAt:new Date().toISOString()}),this.comments.set(e,o)}assertCommentsSupported(e){let t=this.type??e.source;if(Rf.has(t))throw new Error(`Comments are not supported for documentation source '${t}'`)}withSource(e){return this.instanceId?{...e,source:this.instanceId}:e}}});function Qo(){return Af.replace(/\/$/,"")}function wr(r){let e=r.trim(),t=e.lastIndexOf("#");if(t<=0||t===e.length-1)throw new Error(`Bitbucket pull request id must be '{repoSlug}#{prNumber}' (e.g. 'kno-engine#42'), got '${r}'`);let n=e.slice(0,t),o=e.slice(t+1);if(!/^\d+$/.test(o))throw new Error(`Bitbucket pull request id must be '{repoSlug}#{prNumber}' with a numeric PR number, got '${r}'`);return{repoSlug:n,prNumber:o}}function Cf(r,e){return`${r}#${e}`}function Tf(r){let e=r.repoSlug;if(typeof e!="string"||e.trim().length===0)throw new Error("Bitbucket query requires filter.repoSlug or filter.role \u2014 repo-scoped listing needs repoSlug; workspace-wide listing needs role (author|reviewer)");return e.trim()}function Of(r){if(typeof r.repoSlug=="string"&&r.repoSlug.trim().length>0||!fc(r.role))return;let e=String(r.role).trim().toLowerCase();if(e!=="author"&&e!=="reviewer")throw new Error(`Bitbucket query filter.role must be 'author' or 'reviewer', got '${String(r.role)}'`);return e}function pc(r){if(!fc(r))return;let e=String(r).trim().toUpperCase();if(e!=="OPEN"&&e!=="MERGED"&&e!=="DECLINED")throw new Error(`Bitbucket query filter.state must be OPEN, MERGED, or DECLINED, got '${String(r)}'`);return e}function $f(r){if(typeof r.q=="string"&&r.q.trim().length>0)return r.q;let e=pc(r.state);if(e)return`state="${e}"`}function qf(r){let e=r.destination?.repository?.name;if(typeof e=="string"&&e.trim().length>0)return e.trim();let t=r.destination?.repository?.full_name;if(typeof t=="string"&&t.includes("/"))return t.slice(t.lastIndexOf("/")+1);throw new Error("Bitbucket workspace pull request is missing destination.repository slug")}function Bf(r){let e=r.trim().toLowerCase();if(e==="approved")return"approve";if(e==="declined"||e==="rejected")return"decline";if(e==="merged")return"merge";throw new Error(`No Bitbucket action for status '${r}'. Accepted: approved, declined/rejected, merged`)}function fc(r){return r!=null&&r!==""}function Zo(...r){for(let e of r)if(typeof e=="string"&&e.trim().length>0)return e.trim()}function wn(r,e,t){let n=String(r.id??""),o=typeof r.description=="string"?r.description:"";return{id:Cf(e,n),source:t,title:String(r.title??""),...o?{description:o}:{},sourceBranch:String(r.source?.branch?.name??""),targetBranch:String(r.destination?.branch?.name??""),...r.author?.display_name?{author:r.author.display_name}:{},...r.links?.html?.href?{url:r.links.html.href}:{},raw:r}}function Df(r,e){let t=r.user?.display_name??r.author?.display_name;return{id:String(r.id??""),subjectId:e,body:r.content?.raw??"",...t?{author:t}:{},createdAt:r.created_on??"",raw:r}}var kf,Af,Xo,dc,Yo,ei,bn,ti=l(()=>{"use strict";fn();kf="kno.bitbucket.apiToken",Af="https://api.bitbucket.org/2.0";Xo=50,dc=10,Yo=500,ei=[{actionId:"add_reviewer",label:"Add reviewer",params:[{name:"username",label:"Reviewer username",type:"string",required:!0}]}],bn=class{secrets;fetchFn;instanceId;email;workspace;secretKey;constructor(e,t,n=fetch){this.secrets=e,this.fetchFn=n,this.instanceId=t.instanceId,this.email=t.email?.trim()||void 0,this.workspace=t.workspace?.trim()||void 0,this.secretKey=t.secretKey?.trim()||kf}async get(e){let{repoSlug:t,prNumber:n}=wr(e),{workspace:o}=await this.requireConfig(),i=await this.request("GET",this.prPath(o,t,n));return wn(i,t,this.instanceId)}async query(e){let t=Of(e);if(t)return this.queryWorkspacePullRequests(t,e);let n=Tf(e),{workspace:o}=await this.requireConfig(),i=$f(e),s=new URLSearchParams({pagelen:String(Xo)});i&&s.set("q",i);let a=`${Qo()}/repositories/${encodeURIComponent(o)}/${encodeURIComponent(n)}/pullrequests?${s.toString()}`;return this.collectPullRequests(a,n)}async queryWorkspacePullRequests(e,t){let{workspace:n}=await this.requireConfig(),o=await this.selectedUser(),i=new URLSearchParams({pagelen:String(Xo)}),s=pc(t.state);s&&i.set("state",s),e==="reviewer"&&i.set("role","REVIEWER");let a=`${Qo()}/workspaces/${encodeURIComponent(n)}/pullrequests/${encodeURIComponent(o)}?${i.toString()}`;return this.collectPullRequests(a)}selectedUserCache;async selectedUser(){let{email:e}=await this.requireConfig();if(this.selectedUserCache?.email===e)return this.selectedUserCache.id;let t=await this.request("GET","/user"),n=Zo(t.uuid,t.account_id,t.username);if(!n)throw new Error("Bitbucket GET /user did not return uuid, account_id, or username \u2014 cannot list workspace pull requests");return this.selectedUserCache={email:e,id:n},n}async collectPullRequests(e,t){let n=[],o=new Set,i=e;for(let s=0;s<dc&&n.length<Yo&&!(!i||o.has(i));s++){o.add(i);let a=await this.request("GET",i),u=Array.isArray(a.values)?a.values:[];for(let p of u){if(n.length>=Yo)break;n.push(wn(p,t??qf(p),this.instanceId))}let c=typeof a.next=="string"&&a.next.length>0?a.next:void 0;if(!c||u.length===0)break;i=c}return n}async getComments(e){let{repoSlug:t,prNumber:n}=wr(e),{workspace:o}=await this.requireConfig(),i=[],s=new Set,a=`${this.prPath(o,t,n)}/comments?pagelen=${Xo}`;for(let u=0;u<dc&&i.length<Yo&&!(!a||s.has(a));u++){s.add(a);let c=await this.request("GET",a),p=Array.isArray(c.values)?c.values:[];for(let b of p)i.push(Df(b,e));let m=typeof c.next=="string"&&c.next.length>0?c.next:void 0;if(!m||p.length===0)break;a=m}return i}async postComment(e,t){let{repoSlug:n,prNumber:o}=wr(e),{workspace:i}=await this.requireConfig();await this.request("POST",`${this.prPath(i,n,o)}/comments`,{body:{content:{raw:t}}})}async updateStatus(e,t){let{repoSlug:n,prNumber:o}=wr(e),{workspace:i}=await this.requireConfig(),s=Bf(t);await this.request("POST",`${this.prPath(i,n,o)}/${s}`)}listExtendedActions(){return ei}async executeExtendedAction(e,t){if(e==="add_reviewer")return this.addReviewer(t);throw new Error(`Provider 'bitbucket' has no extended action '${e}'. Available: ${qt(this.listExtendedActions())}`)}async addReviewer(e){let t=typeof e.subjectId=="string"?e.subjectId.trim():"";if(!t)throw new Error("Bitbucket action 'add_reviewer' requires params.subjectId");let n=typeof e.username=="string"?e.username.trim():"";if(!n)throw new Error("Bitbucket action 'add_reviewer' requires params.username");let{repoSlug:o,prNumber:i}=wr(t),{workspace:s}=await this.requireConfig(),a=await this.request("GET",this.prPath(s,o,i)),u=await this.request("GET",`/users/${encodeURIComponent(n)}`),c=Zo(u.uuid),p=Zo(u.account_id);if(!c&&!p)throw new Error(`Bitbucket user '${n}' has no uuid or account_id`);let m=Array.isArray(a.reviewers)?a.reviewers:[];if(m.some(N=>c!=null&&N.uuid===c||p!=null&&N.account_id===p))return wn(a,o,this.instanceId);let S=[...m.map(N=>N.uuid?{uuid:N.uuid}:{account_id:N.account_id}),c?{uuid:c}:{account_id:p}],j=await this.request("PUT",this.prPath(s,o,i),{body:{title:a.title??"",reviewers:S}});return wn(j,o,this.instanceId)}prPath(e,t,n){return`/repositories/${encodeURIComponent(e)}/${encodeURIComponent(t)}/pullrequests/${encodeURIComponent(n)}`}async requireConfig(){let e=this.email,t=this.workspace,n=await this.secrets.get(this.secretKey);if(!e||!t||!n){let o=[];throw e||o.push("config.email"),t||o.push("config.workspace"),n||o.push(`SecretStore '${this.secretKey}'`),new Error(`Bitbucket instance '${this.instanceId}' is not configured \u2014 missing ${o.join(", ")}. Set email and workspace on the provider instance, and store the API token with: POST /api/secrets/${this.secretKey} or npm --workspace apps/engine run set-secret -- ${this.secretKey} <value>`)}return{email:e,workspace:t,token:n}}async request(e,t,n={}){let{email:o,token:i}=await this.requireConfig(),s=t.startsWith("http://")||t.startsWith("https://")?t:`${Qo()}${t.startsWith("/")?t:`/${t}`}`,a={Authorization:`Basic ${Buffer.from(`${o}:${i}`).toString("base64")}`,Accept:"application/json"};n.body!==void 0&&(a["Content-Type"]="application/json");let u=await this.fetchFn(s,{method:e,headers:a,...n.body!==void 0?{body:JSON.stringify(n.body)}:{}});if(!u.ok){let p=await u.text().catch(()=>"");throw new Error(`Bitbucket ${e} ${t} failed (${u.status}): ${p||u.statusText}`)}if(u.status===204)return;let c=await u.text();if(c)return JSON.parse(c)}}});import{randomUUID as Ff}from"node:crypto";function Nf(r,e){return Object.entries(e).every(([t,n])=>t==="status"?r.raw?.status===n:r[t]===n)}var Sn,mc=l(()=>{"use strict";Sn=class{pullRequests;comments;instanceId;constructor(e=[],t){this.pullRequests=new Map(e.map(n=>[n.id,structuredClone(n)])),this.comments=new Map,this.instanceId=t}async get(e){let t=this.pullRequests.get(e);if(!t)throw new Error(`Pull request not found: ${e}`);return this.withSource(structuredClone(t))}async query(e){return[...this.pullRequests.values()].filter(t=>Nf(t,e)).map(t=>this.withSource(structuredClone(t)))}async getComments(e){return await this.get(e),structuredClone(this.comments.get(e)??[])}async postComment(e,t){await this.get(e);let n=this.comments.get(e)??[];n.push({id:Ff(),subjectId:e,body:t,createdAt:new Date().toISOString()}),this.comments.set(e,n)}async updateStatus(e,t){let n=this.pullRequests.get(e);if(!n)throw new Error(`Pull request not found: ${e}`);n.raw={...n.raw??{},status:t}}withSource(e){return this.instanceId?{...e,source:this.instanceId}:e}}});function ri(r){return r.pull_request!=null}function xn(r){let e=r.trim(),t=e.lastIndexOf("#");if(t<=0||t===e.length-1)throw new Error(`GitHub issue id must be '{owner}/{repo}#{issueNumber}' (e.g. 'acme/kno#42'), got '${r}'`);let n=e.slice(0,t),o=e.slice(t+1),{owner:i,name:s}=hc(n);if(!/^\d+$/.test(o))throw new Error(`GitHub issue id must be '{owner}/{repo}#{issueNumber}' (e.g. 'acme/kno#42'), got '${r}'`);return{owner:i,repo:s,issueNumber:o}}function Wf(r,e,t){return`${r}/${e}#${t}`}function hc(r){let e=r.trim(),t=e.indexOf("/");if(t<=0||t===e.length-1||e.indexOf("/",t+1)!==-1)throw new Error(`GitHub repo must be '{owner}/{name}', got '${r}'`);return{owner:e.slice(0,t),name:e.slice(t+1)}}function Hf(r){let e=r.role;if(e==="assignee"||e==="creator")return e}function Vf(r,e){return r==="creator"?`author:${e}`:`assignee:${e}`}function Kf(r){let e=r.trim().toLowerCase();if(e==="open")return{state:"open"};if(e==="closed"||e==="done"||e==="completed")return{state:"closed",state_reason:"completed"};if(e==="not_planned"||e==="wontfix")return{state:"closed",state_reason:"not_planned"};throw new Error(`No GitHub Issues mapping for status '${r}'. Accepted: ${Mf.join(", ")}`)}function Gf(r){let e=r.repository?.full_name;if(typeof e=="string"&&e.includes("/"))return e;let t=r.repository_url;if(typeof t=="string"){let n="/repos/",o=t.lastIndexOf(n);if(o>=0){let i=t.slice(o+n.length);if(i.includes("/"))return i}}throw new Error("GitHub search result is missing repository full_name")}function ni(r,e,t){let n=String(r.number??""),[o,i]=t.split("/"),s=typeof r.body=="string"?r.body:"";return{id:Wf(o??"",i??"",n),source:e,title:String(r.title??""),...s?{description:s}:{},status:String(r.state??""),...r.assignee?.login?{assignee:r.assignee.login}:{},...r.html_url?{url:r.html_url}:{},raw:r}}function zf(r,e){return{id:String(r.id??""),subjectId:e,body:r.body??"",...r.user?.login?{author:r.user.login}:{},createdAt:r.created_at??""}}function vn(r){return r!=null&&r!==""}var Jf,Lf,Uf,Mf,In,yc=l(()=>{"use strict";Jf="2026-03-10",Lf="https://api.github.com",Uf="kno.github.apiToken",Mf=["open","closed/done/completed","not_planned/wontfix"],In=class{secrets;fetchFn;instanceId;username;secretKey;constructor(e,t,n=fetch){this.secrets=e,this.fetchFn=n,this.instanceId=t.instanceId,this.username=t.username?.trim()||void 0,this.secretKey=t.secretKey?.trim()||Uf}async get(e){let{owner:t,repo:n,issueNumber:o}=xn(e),i=await this.request("GET",`/repos/${encodeURIComponent(t)}/${encodeURIComponent(n)}/issues/${encodeURIComponent(o)}`);if(ri(i))throw new Error(`Ticket not found: ${e}`);return ni(i,this.instanceId,`${t}/${n}`)}async query(e){let t=typeof e.repo=="string"?e.repo.trim():"";if(t)return this.queryRepoIssues(t,e);let n=Hf(e);if(n)return this.querySearch(n,e);throw new Error("GitHub Issues query requires filter.repo ('owner/name') or filter.role ('assignee' | 'creator')")}async getComments(e){let{owner:t,repo:n,issueNumber:o}=xn(e),i=await this.request("GET",`/repos/${encodeURIComponent(t)}/${encodeURIComponent(n)}/issues/${encodeURIComponent(o)}/comments`);return(Array.isArray(i)?i:[]).map(a=>zf(a,e))}async postComment(e,t){let{owner:n,repo:o,issueNumber:i}=xn(e);await this.request("POST",`/repos/${encodeURIComponent(n)}/${encodeURIComponent(o)}/issues/${encodeURIComponent(i)}/comments`,{body:{body:t}})}async updateStatus(e,t){let{owner:n,repo:o,issueNumber:i}=xn(e);await this.request("PATCH",`/repos/${encodeURIComponent(n)}/${encodeURIComponent(o)}/issues/${encodeURIComponent(i)}`,{body:Kf(t)})}async queryRepoIssues(e,t){let{owner:n,name:o}=hc(e),i=[],s=new URLSearchParams;s.set("per_page",String(100)),vn(t.state)&&s.set("state",String(t.state)),vn(t.labels)&&s.set("labels",String(t.labels)),vn(t.assignee)&&s.set("assignee",String(t.assignee));for(let a=1;a<=10&&i.length<500;a++){s.set("page",String(a));let u=await this.request("GET",`/repos/${encodeURIComponent(n)}/${encodeURIComponent(o)}/issues?${s.toString()}`),c=Array.isArray(u)?u:[];if(c.length===0)break;for(let p of c)if(!ri(p)){if(i.length>=500)break;i.push(ni(p,this.instanceId,`${n}/${o}`))}if(c.length<100)break}return i}async querySearch(e,t){let n=this.requireUsername(),o=[Vf(e,n),"is:issue"];vn(t.state)&&o.push(`is:${String(t.state).trim().toLowerCase()}`);let i=o.join(" "),s=[];for(let a=1;a<=10&&s.length<500;a++){let u=new URLSearchParams({q:i,per_page:String(100),page:String(a)}),c=await this.request("GET",`/search/issues?${u.toString()}`),p=Array.isArray(c.items)?c.items:[];if(p.length===0)break;for(let m of p)if(!ri(m)){if(s.length>=500)break;s.push(ni(m,this.instanceId,Gf(m)))}if(p.length<100)break}return s}requireUsername(){if(!this.username)throw new Error(`GitHub Issues instance '${this.instanceId}' is not configured \u2014 missing config.username`);return this.username}async requireToken(){let e=await this.secrets.get(this.secretKey);if(!e)throw new Error(`GitHub Issues instance '${this.instanceId}' is not configured \u2014 missing SecretStore '${this.secretKey}'. Store the token with: POST /api/secrets/${this.secretKey} or npm --workspace apps/engine run set-secret -- ${this.secretKey} <value>`);return e}async request(e,t,n={}){let o=await this.requireToken(),i=`${Lf}${t}`,s={Authorization:`Bearer ${o}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":Jf};n.body!==void 0&&(s["Content-Type"]="application/json");let a=await this.fetchFn(i,{method:e,headers:s,...n.body!==void 0?{body:JSON.stringify(n.body)}:{}});if(!a.ok){let c=await a.text().catch(()=>"");throw new Error(`GitHub ${e} ${t} failed (${a.status}): ${c||a.statusText}`)}if(a.status===204)return;let u=await a.text();if(u)return JSON.parse(u)}}});var wt,y,h,J,R=l(()=>{"use strict";wt=class extends Error{constructor(e){super(e),this.name=this.constructor.name}},y=class extends wt{httpStatus=404},h=class extends wt{httpStatus=400},J=class extends wt{httpStatus=409}});function Zf(r){if(typeof r.jql=="string"&&r.jql.trim().length>0)return r.jql;let e=[];if(_n(r.project)&&e.push(`project = ${En(r.project)}`),_n(r.status)&&e.push(`status = ${En(r.status)}`),_n(r.assignee)&&e.push(`assignee = ${En(r.assignee)}`),_n(r.sprintId)){let t=r.sprintId;e.push(typeof t=="number"||/^\d+$/.test(String(t))?`sprint = ${Number(t)}`:`sprint = ${En(t)}`)}if(e.length===0)throw new h("Jira query requires jql or at least one of project, status, assignee, sprintId");return e.join(" AND ")}function _n(r){return r!=null&&r!==""}function En(r){return`"${String(r).replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function gc(r,e,t){let n=String(r.key??r.id??""),o=r.fields??{},i=gr(o.description);return{id:n,source:t,title:String(o.summary??""),...i?{description:i}:{},status:String(o.status?.name??""),...o.assignee?.displayName?{assignee:String(o.assignee.displayName)}:{},url:`${e.replace(/\/$/,"")}/browse/${n}`,raw:r}}var Qf,Xf,Yf,jn,Pn,wc=l(()=>{"use strict";R();Go();Qf="kno.jira.apiToken",Xf=50,Yf=10,jn=500,Pn=class{secrets;fetchFn;instanceId;baseUrl;email;secretKey;constructor(e,t,n=fetch){this.secrets=e,this.fetchFn=n,this.instanceId=t.instanceId,this.baseUrl=t.baseUrl?.trim()||void 0,this.email=t.email?.trim()||void 0,this.secretKey=t.secretKey?.trim()||Qf}async get(e){let{baseUrl:t}=await this.requireConfig(),n=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}`);return gc(n,t,this.instanceId)}async query(e){let{baseUrl:t}=await this.requireConfig(),n=Zf(e),o=[],i,s=new Set;for(let a=0;a<Yf&&o.length<jn;a++){let u={jql:n,maxResults:Math.min(Xf,jn-o.length),fields:["summary","description","status","assignee"]};i&&(u.nextPageToken=i);let c=await this.request("POST","/rest/api/3/search/jql",{body:u}),p=Array.isArray(c.issues)?c.issues:[];for(let b of p){if(o.length>=jn)break;o.push(gc(b,t,this.instanceId))}let m=typeof c.nextPageToken=="string"?c.nextPageToken:void 0;if(c.isLast===!0||!m||p.length===0||m===i||s.has(m))break;s.add(m),i=m}return o}async getComments(e){let t=[],n=0,o=100,i=jn;for(;t.length<i;){let s=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}/comment?startAt=${n}&maxResults=${o}`),a=Array.isArray(s.comments)?s.comments:[];for(let u of a)t.push({id:String(u.id??""),subjectId:e,body:gr(u.body),...u.author?.displayName?{author:u.author.displayName}:{},createdAt:u.created??"",raw:u});if(n+=a.length,a.length===0||typeof s.total=="number"&&n>=s.total||a.length<o)break}return t}async postComment(e,t){await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(e)}/comment`,{body:{body:mn(t)}})}async updateStatus(e,t){let n=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}/transitions`),o=Array.isArray(n.transitions)?n.transitions:[],i=t.trim().toLowerCase(),s=o.find(a=>(a.to?.name??"").trim().toLowerCase()===i);if(!s?.id){let a=o.map(c=>c.to?.name).filter(c=>typeof c=="string"&&c.length>0),u=a.length>0?a.join(", "):"(none)";throw new Error(`No Jira transition to status '${t}' from the current state. Available: ${u}`)}await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(e)}/transitions`,{body:{transition:{id:s.id}}})}async requireConfig(){let e=this.baseUrl,t=this.email,n=await this.secrets.get(this.secretKey);if(!e||!t||!n){let o=[];throw e||o.push("config.baseUrl"),t||o.push("config.email"),n||o.push(`SecretStore '${this.secretKey}'`),new Error(`Jira instance '${this.instanceId}' is not configured \u2014 missing ${o.join(", ")}. Set baseUrl and email on the provider instance, and store the API token with: POST /api/secrets/${this.secretKey} or npm --workspace apps/engine run set-secret -- ${this.secretKey} <value>`)}return{baseUrl:e,email:t,token:n}}async request(e,t,n={}){let{baseUrl:o,email:i,token:s}=await this.requireConfig(),a=`${o.replace(/\/$/,"")}${t}`,u={Authorization:`Basic ${Buffer.from(`${i}:${s}`).toString("base64")}`,Accept:"application/json"};n.body!==void 0&&(u["Content-Type"]="application/json");let c=await this.fetchFn(a,{method:e,headers:u,...n.body!==void 0?{body:JSON.stringify(n.body)}:{}});if(!c.ok){let m=await c.text().catch(()=>"");throw new Error(`Jira ${e} ${t} failed (${c.status}): ${m||c.statusText}`)}if(c.status===204)return;let p=await c.text();if(p)return JSON.parse(p)}}});import{randomUUID as em}from"node:crypto";function tm(r,e){return Object.entries(e).every(([t,n])=>r[t]===n)}var Rn,bc=l(()=>{"use strict";Rn=class{tickets;comments;instanceId;constructor(e=[],t){this.tickets=new Map(e.map(n=>[n.id,structuredClone(n)])),this.comments=new Map,this.instanceId=t}async get(e){let t=this.tickets.get(e);if(!t)throw new Error(`Ticket not found: ${e}`);return this.withSource(structuredClone(t))}async query(e){return[...this.tickets.values()].filter(t=>tm(t,e)).map(t=>this.withSource(structuredClone(t)))}async getComments(e){return await this.get(e),structuredClone(this.comments.get(e)??[])}async postComment(e,t){await this.get(e);let n=this.comments.get(e)??[];n.push({id:em(),subjectId:e,body:t,createdAt:new Date().toISOString()}),this.comments.set(e,n)}async updateStatus(e,t){let n=this.tickets.get(e);if(!n)throw new Error(`Ticket not found: ${e}`);n.status=t}withSource(e){return this.instanceId?{...e,source:this.instanceId}:e}}});function De(r,e){let t=r[e];return typeof t=="string"&&t.trim().length>0?t.trim():void 0}function kn(r){return new Error(`This workflow requires provider instance '${r}', which isn't configured`)}function rm(r){return r==="jira"||r==="github"?"ticket":r==="bitbucket"?"pull_request":r==="confluence"?"documentation":"any"}var Rv,F,Bt=l(()=>{"use strict";C();rc();nc();zo();lc();ti();mc();yc();wc();bc();Rv=Symbol("PROVIDER_REGISTRY");F=class r{tickets=new Map;repos=new Map;documentation=new Map;agents=new Map;instances=[];constructor(){}static fromSettings(e,t){let n=new r;return n.load(e,t),n}static fromMaps(e){let t=new r;for(let[n,o]of Object.entries(e.tickets??{}))t.tickets.set(n,o);for(let[n,o]of Object.entries(e.repos??{}))t.repos.set(n,o);for(let[n,o]of Object.entries(e.documentation??{}))t.documentation.set(n,o);for(let[n,o]of Object.entries(e.agents??{}))t.agents.set(n,o);return t.instances.push(...e.instances??[]),t}load(e,t){let n=new Set;for(let o of e){if(n.has(o.id))throw new Error(`Duplicate provider instance id '${o.id}'`);n.add(o.id),this.instances.push(o),this.instantiate(o,t)}}instantiate(e,t){if($t(e)){let o=De(e.config,"model");if(e.type==="claude"){this.agents.set(e.id,new ln(t,{secretKey:e.secretKey,model:o}));return}this.agents.set(e.id,new dn(t,{secretKey:e.secretKey,model:o}));return}if(!gt(e))throw new Error(`Unknown provider instance kind on '${e.id}'`);let n=rm(e.type);if(n!=="any"&&e.subjectType!==n)throw new Error(`Provider instance '${e.id}' type '${e.type}' cannot serve subjectType '${e.subjectType}'`);if(e.type==="jira"){this.tickets.set(e.id,new Pn(t,{instanceId:e.id,baseUrl:De(e.config,"baseUrl"),email:De(e.config,"email"),secretKey:e.secretKey}));return}if(e.type==="github"){this.tickets.set(e.id,new In(t,{instanceId:e.id,username:De(e.config,"username"),secretKey:e.secretKey}));return}if(e.type==="bitbucket"){this.repos.set(e.id,new bn(t,{instanceId:e.id,email:De(e.config,"email"),workspace:De(e.config,"workspace"),secretKey:e.secretKey}));return}if(e.type==="confluence"){this.documentation.set(e.id,new yn(t,{instanceId:e.id,baseUrl:De(e.config,"baseUrl"),email:De(e.config,"email"),secretKey:e.secretKey}));return}if(e.subjectType==="ticket"){this.tickets.set(e.id,new Rn([],e.id));return}if(e.subjectType==="pull_request"){this.repos.set(e.id,new Sn([],e.id));return}this.documentation.set(e.id,new gn([],{instanceId:e.id,type:De(e.config,"type")}))}getTicketProvider(e){let t=this.tickets.get(e);if(!t)throw kn(e);return t}getRepoProvider(e){let t=this.repos.get(e);if(!t)throw kn(e);return t}getDocumentationProvider(e){let t=this.documentation.get(e);if(!t)throw kn(e);return t}getAgentProvider(e){let t=this.agents.get(e);if(!t)throw kn(e);return t}getInstance(e){return this.instances.find(t=>t.id===e)}listInstances(e){return e==null?[...this.instances]:this.instances.filter(t=>gt(t)&&t.subjectType===e)}ticketInstanceIds(){return[...this.tickets.keys()]}repoInstanceIds(){return[...this.repos.keys()]}documentationInstanceIds(){return[...this.documentation.keys()]}}});function xc(r,e){switch(r){case"my-open-prs":return{role:"author",state:"OPEN"};case"reviewing":return{role:"reviewer",state:"OPEN"};case"repo-open-prs":{let t=typeof e.repoSlug=="string"?e.repoSlug.trim():"";if(!t)throw new h("Bitbucket template 'repo-open-prs' requires params.repoSlug");return{repoSlug:t,state:"OPEN"}}default:throw new y(`Unknown Bitbucket query template: ${r}`)}}var Sc,vc=l(()=>{"use strict";R();Sc=[{id:"my-open-prs",label:"My open pull requests",params:[]},{id:"reviewing",label:"Pull requests I'm reviewing",params:[]},{id:"repo-open-prs",label:"Open pull requests in a repository",params:[{name:"repoSlug",label:"Repository",type:"string",required:!0}]}]});function jc(r,e){switch(r){case"my-open-issues":return{role:"assignee",state:"open"};case"created-by-me":return{role:"creator",state:"open"};case"repo-open-issues":{let t=typeof e.repo=="string"?e.repo.trim():"";if(!t)throw new h("GitHub template 'repo-open-issues' requires params.repo");return{repo:t,state:"open"}}default:throw new y(`Unknown GitHub query template: ${r}`)}}var Ic,_c=l(()=>{"use strict";R();Ic=[{id:"my-open-issues",label:"My open issues",params:[]},{id:"created-by-me",label:"Issues I created",params:[]},{id:"repo-open-issues",label:"Open issues in a repository",params:[{name:"repo",label:"Repository (owner/name)",type:"string",required:!0}]}]});function Ac(r,e){switch(r){case"my-open-tickets":return{jql:"assignee = currentUser() AND statusCategory != Done"};case"created-by-me":return{jql:"reporter = currentUser() AND statusCategory != Done"};case"project-open-tickets":return{jql:`project = ${Rc(Pc(r,e))} AND statusCategory != Done`};case"current-sprint-tickets":return{jql:`project = ${Rc(Pc(r,e))} AND sprint in openSprints() AND statusCategory != Done`};default:throw new y(`Unknown Jira query template: ${r}`)}}function Pc(r,e){let t=typeof e.project=="string"?e.project.trim():"";if(!t)throw new h(`Jira template '${r}' requires params.project`);return t}function Rc(r){return`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}var Ec,kc,Cc=l(()=>{"use strict";R();Ec={name:"project",label:"Project key",type:"string",required:!0},kc=[{id:"my-open-tickets",label:"My open tickets",params:[]},{id:"created-by-me",label:"Tickets I created",params:[]},{id:"project-open-tickets",label:"Open tickets in a project",params:[Ec]},{id:"current-sprint-tickets",label:"Tickets in the current sprint",params:[Ec]}]});import{Inject as Oc,Injectable as im}from"@nestjs/common";var nm,om,Tc,$c,nt,oi=l(()=>{"use strict";C();R();Pe();Bt();vc();_c();Cc();nm=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},om=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},Tc=function(r,e){return function(t,n){e(t,n,r)}},$c={bitbucket:{list:()=>Sc,resolve:xc},github:{list:()=>Ic,resolve:jc},jira:{list:()=>kc,resolve:Ac}},nt=class{settings;registry;constructor(e,t){this.settings=e,this.registry=t}async list(e){let t=await this.providerType(e);return t?$c[t]?.list()??[]:[]}async resolve(e,t,n){let o=await this.providerType(e),i=o?$c[o]:void 0;if(!i)throw new y(`No query templates for provider instance '${e}'`);let s=i.list().find(a=>a.id===t);if(!s)throw new y(`Unknown query template '${t}' for provider instance '${e}'`);for(let a of s.params){if(!a.required)continue;let u=n[a.name];if(u==null||typeof u=="string"&&u.trim()==="")throw new h(`Template '${t}' requires params.${a.name}`)}return i.resolve(t,n)}async providerType(e){let n=(await this.settings.get()).providerInstances?.find(o=>o.id===e)??this.registry.getInstance(e);if(!(!n||!gt(n)))return n.type}};nt=nm([im(),Tc(0,Oc(P)),Tc(1,Oc(F)),om("design:paramtypes",[P,F])],nt)});import{Inject as Bc,Injectable as cm}from"@nestjs/common";var sm,am,qc,um,ot,ii=l(()=>{"use strict";C();Pe();zo();ti();Bt();sm=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},am=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},qc=function(r,e){return function(t,n){e(t,n,r)}},um={bitbucket:()=>ei,confluence:()=>hn},ot=class{settings;registry;constructor(e,t){this.settings=e,this.registry=t}async list(e){let n=(await this.settings.get()).providerInstances?.find(o=>o.id===e)??this.registry.getInstance(e);return!n||!gt(n)?[]:um[n.type]?.()??[]}};ot=sm([cm(),qc(0,Bc(P)),qc(1,Bc(F)),am("design:paramtypes",[P,F])],ot)});async function Dc(r){let e=r.fetchFn??fetch;return r.type==="claude"?fm(r.apiKey,e):mm(r.apiKey,e)}async function fm(r,e){let t=await e(lm,{method:"GET",headers:{"x-api-key":r,"anthropic-version":pm}});if(!t.ok)throw Fc("Claude",t.status);let n=await t.json();return(Array.isArray(n.data)?n.data:[]).flatMap(i=>{if(!i||typeof i!="object")return[];let s=i,a=typeof s.id=="string"?s.id:"";if(!a)return[];let u=typeof s.display_name=="string"&&s.display_name.trim()?s.display_name:a;return[{id:a,displayName:u}]})}async function mm(r,e){let t=await e(dm,{method:"GET",headers:{Authorization:`Basic ${Buffer.from(`${r}:`).toString("base64")}`}});if(!t.ok)throw Fc("Cursor",t.status);let n=await t.json();return(Array.isArray(n.items)?n.items:[]).flatMap(i=>{if(!i||typeof i!="object")return[];let s=i,a=typeof s.id=="string"?s.id:"";if(!a)return[];let u=typeof s.displayName=="string"&&s.displayName.trim()?s.displayName:a;return[{id:a,displayName:u}]})}function Fc(r,e){let t=new Error(`${r} rejected the API key (HTTP ${e}). Check the key and try again.`);return t.name="PreviewModelsAuthError",t}var lm,dm,pm,Nc=l(()=>{"use strict";lm="https://api.anthropic.com/v1/models",dm="https://api.cursor.com/v1/models",pm="2023-06-01"});import{Inject as ai,Injectable as gm}from"@nestjs/common";var hm,ym,si,An,it,ci=l(()=>{"use strict";C();Pe();Oe();R();Nc();hm=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},ym=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},si=function(r,e){return function(t,n){e(t,n,r)}},An="PREVIEW_MODELS_FETCH",it=class{settings;secrets;fetchFn;constructor(e,t,n){this.settings=e,this.secrets=t,this.fetchFn=n}async preview(e){let t=e.apiKey?.trim();if(t)return this.lookup(e.type,t);let n=e.instanceId?.trim();if(!n)throw new h("Provide apiKey or instanceId to preview models");let o=(await this.settings.get()).providerInstances?.find(s=>s.id===n);if(!o)throw new y(`Provider instance not found: ${n}`);if(!$t(o)||o.type!==e.type)throw new h(`Provider instance '${n}' is not a ${e.type} agent`);let i=await this.secrets.get(o.secretKey);if(!i)throw new h(`No API key stored for instance '${n}'. Enter a key to fetch models.`);return this.lookup(e.type,i)}async lookup(e,t){try{return await Dc({type:e,apiKey:t,fetchFn:this.fetchFn})}catch(n){throw n instanceof Error&&n.name==="PreviewModelsAuthError"?new h(n.message):new h(n instanceof Error?n.message:"Failed to fetch available models")}}};it=hm([gm(),si(0,ai(P)),si(1,ai(fe)),si(2,ai(An)),ym("design:paramtypes",[P,Function,Function])],it)});import{Module as bm}from"@nestjs/common";var wm,st,Cn=l(()=>{"use strict";wo();gs();Io();Oe();mr();Pe();Ko();Bt();oi();ii();ci();wm=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},st=class{};st=wm([bm({imports:[At,Re],providers:[{provide:F,useFactory:async(r,e)=>{let t=await r.get();return F.fromSettings(t.providerInstances??[],e)},inject:[P,fe]},{provide:er,useClass:Rr},rt,nt,ot,{provide:An,useValue:(r,e)=>fetch(r,e)},it],exports:[F,er,rt,nt,ot,it,An]})],st)});import{Injectable as xm}from"@nestjs/common";var Sm,ye,Tn=l(()=>{"use strict";Sm=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},ye=class{listeners=new Set;emit(e){for(let t of this.listeners)t(e)}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}};ye=Sm([xm()],ye)});import{Global as Im,Module as jm}from"@nestjs/common";var vm,at,On=l(()=>{"use strict";Tn();vm=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},at=class{};at=vm([Im(),jm({providers:[ye],exports:[ye]})],at)});import{Injectable as Pm}from"@nestjs/common";import{execFile as Rm}from"node:child_process";import{mkdirSync as ui,rmSync as km}from"node:fs";import{dirname as Am,join as $n,resolve as Jc}from"node:path";import{promisify as Cm}from"node:util";function Lc(r){return r==null?"":typeof r=="string"?r:r.toString("utf8")}function Uc(r){return $n(r,"worktrees")}function Om(r){let e=[],t;for(let n of r.split(/\r?\n/)){let o=n.trimEnd();if(o===""){t&&e.push(t),t=void 0;continue}if(o.startsWith("worktree ")){t&&e.push(t),t={path:o.slice(9)};continue}if(t&&o.startsWith("branch ")){let i=o.slice(7);t.branch=i.startsWith("refs/heads/")?i.slice(11):i}}return t&&e.push(t),e}var _m,Em,Tm,Fe,li=l(()=>{"use strict";_m=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Em=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},Tm=Cm(Rm),Fe=class{worktreesRoot;constructor(e){this.worktreesRoot=e,ui(this.worktreesRoot,{recursive:!0})}async createWorktree(e,t){let n=t.worktreePath??$n(this.worktreesRoot,e);return ui($n(n,".."),{recursive:!0}),await this.git(t.repoPath,["worktree","add","-b",t.branchName,n,t.baseBranch]),{worktreePath:n,branch:t.branchName}}async addWorktreeForExistingBranch(e){ui($n(e.worktreePath,".."),{recursive:!0});try{await this.git(e.repoPath,["fetch","origin",e.branch])}catch{}let t=await this.existingBranchStartPoint(e.repoPath,e.branch);return t.kind==="local"?await this.git(e.repoPath,["worktree","add",e.worktreePath,e.branch]):await this.git(e.repoPath,["worktree","add","--track","-b",e.branch,e.worktreePath,t.ref]),{worktreePath:e.worktreePath,branch:e.branch}}async listWorktrees(e){let{stdout:t}=await this.git(e,["worktree","list","--porcelain"]);return Om(t)}async resetWorktreeToRemote(e,t){try{await this.git(e,["fetch","origin",t])}catch{}let n=`origin/${t}`;try{await this.git(e,["rev-parse","--verify",n]),await this.git(e,["reset","--hard",n])}catch{await this.git(e,["reset","--hard",t])}await this.git(e,["clean","-fd"])}async removeWorktree(e){let t=Jc(e);try{let{stdout:n}=await this.git(t,["rev-parse","--git-common-dir"]),o=Jc(t,n.trim()),i=o.endsWith(".git")?Am(o):o;await this.git(i,["worktree","remove","--force",t])}catch{km(t,{recursive:!0,force:!0})}}async existingBranchStartPoint(e,t){try{return await this.git(e,["rev-parse","--verify",`refs/heads/${t}`]),{kind:"local"}}catch{let n=`origin/${t}`;return await this.git(e,["rev-parse","--verify",n]),{kind:"remote",ref:n}}}async checkout(e,t){await this.git(e,["checkout",t.branch])}async createBranch(e,t){t.baseBranch?await this.git(e,["checkout","-b",t.branchName,t.baseBranch]):await this.git(e,["checkout","-b",t.branchName])}async commit(e,t){return t.addAll!==!1&&await this.git(e,["add","-A"]),await this.git(e,["commit","-m",t.message]),{sha:(await this.git(e,["rev-parse","HEAD"])).stdout.trim()}}async push(e,t={}){let n=t.remote??"origin";t.branch?await this.git(e,["push",n,t.branch]):await this.git(e,["push",n,"HEAD"])}async git(e,t){try{let n=await Tm("git",t,{cwd:e,encoding:"utf8",windowsHide:!0});return{stdout:n.stdout??"",stderr:n.stderr??""}}catch(n){let o=n,i=Lc(o.stderr),s=Lc(o.stdout),a=i||s||o.message||"unknown git error";throw new Error(`git ${t.join(" ")} failed (cwd=${e}, code=${String(o.code??"?")}): ${a}`)}}};Fe=_m([Pm(),Em("design:paramtypes",[String])],Fe)});import{Module as qm}from"@nestjs/common";import{mkdirSync as Bm}from"node:fs";var $m,Mc,qn,Wc=l(()=>{"use strict";kr();li();$m=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Mc=rr();Bm(Mc,{recursive:!0});qn=class{};qn=$m([qm({providers:[{provide:Fe,useFactory:()=>new Fe(Uc(Mc))}],exports:[Fe]})],qn)});function Ft(r,e){return r.replace(/\{\{\s*([^}]+?)\s*\}\}/g,(t,n)=>{let o=di(e,n.trim());return o==null?"":typeof o=="string"?o:JSON.stringify(o)})}function di(r,e){let t=e.split(".").filter(Boolean),n=r;for(let o of t){if(n==null||typeof n!="object")return;n=n[o]}return n}function Dt(r,e){return typeof r=="string"?Ft(r,e):Array.isArray(r)?r.map(t=>Dt(t,e)):r&&typeof r=="object"?Object.fromEntries(Object.entries(r).map(([t,n])=>[t,Dt(n,e)])):r}var pi=l(()=>{"use strict"});function Vc(r){let e=r.path?.trim()||void 0,t=r.pattern?.trim()||void 0,n=r.source,o=r.source;if(e){if(r.source.trim()==="")return{kind:"no_match",sourceValue:r.source};let i;try{i=JSON.parse(r.source)}catch(a){let u=a instanceof Error?a.message:String(a);throw new Error(`Extract source is not valid JSON (required when path is set): ${u}`)}let s=Dm(i,e);if(n=s??i,s==null)return{kind:"no_match",sourceValue:n};o=s}if(t){let i=Hc(o),s;try{s=new RegExp(t)}catch(c){let p=c instanceof Error?c.message:String(c);throw new Error(`Invalid extract pattern: ${p}`)}let a=i.match(s);return a?{kind:"match",value:a[1]!==void 0?a[1]:a[0],sourceValue:n}:{kind:"no_match",sourceValue:n}}return{kind:"match",value:Hc(o),sourceValue:n}}function Dm(r,e){if(!(r==null||typeof r!="object"))return di(r,e)}function Hc(r){return typeof r=="string"?r:typeof r=="number"||typeof r=="boolean"||typeof r=="bigint"?String(r):r==null?"":JSON.stringify(r)}var Kc=l(()=>{"use strict";pi()});function Gc(r,e){switch(r){case"questionnaire":return fi(e);case"confirmation":return Fm(e);case"conversation":return Nm(e);default:return r}}function fi(r){if(typeof r=="string"&&r.trim())return[r.trim()];if(!r||typeof r!="object")return[];let e=r.questions;return Array.isArray(e)?e.map(t=>typeof t=="string"?t.trim():t&&typeof t=="object"&&"prompt"in t?String(t.prompt).trim():"").filter(Boolean):[]}function Fm(r){if(typeof r=="string"&&r.trim())return[r.trim()];if(!r||typeof r!="object")return[];let e=r;for(let t of["prompt","message","summary","question"]){let n=e[t];if(typeof n=="string"&&n.trim())return[n.trim()]}return"approved"in e&&!("questions"in e)?[]:fi(r)}function Nm(r){if(typeof r=="string"&&r.trim())return[r.trim()];if(!r||typeof r!="object")return[];let e=r;for(let t of["prompt","message","text"]){let n=e[t];if(typeof n=="string"&&n.trim())return[n.trim()]}return"suggestions"in e?[]:"questions"in e?fi(r):[]}var zc=l(()=>{"use strict"});function ct(r,e){for(let t of r){if(t.id===e)return t;if(t.iterations)for(let n of t.iterations){let o=ct(n.stepExecutions,e);if(o)return o}}}function bt(r,e,t,n){for(let o=0;o<r.length;o++){let i=r[o];if(i.id===e)return{execution:i,siblings:r,index:o,parentLoopExecutionId:t,iterationIndex:n};if(i.iterations)for(let s of i.iterations){let a=bt(s.stepExecutions,e,i.id,s.index);if(a)return a}}}function Q(r,e,t){return r.map(n=>n.id===e?t(n):n.iterations?{...n,iterations:n.iterations.map(o=>({...o,stepExecutions:Q(o.stepExecutions,e,t)}))}:n)}function mi(r,e,t,n){return t==null?[...r,e]:r.map(o=>{if(o.id===t){let i=[...o.iterations??[]],s=i.find(a=>a.index===n);if(s){let a={...s,stepExecutions:[...s.stepExecutions,e]},u=i.findIndex(c=>c.index===n);i[u]=a}else{let a={index:n,stepExecutions:[e],startedAt:e.startedAt??new Date().toISOString()};i.push(a),i.sort((u,c)=>u.index-c.index)}return{...o,iterations:i}}return o.iterations?{...o,iterations:o.iterations.map(i=>({...i,stepExecutions:mi(i.stepExecutions,e,t,n)}))}:o})}function Nt(r,e){for(let t of r){if(t.id===e)return t;if(t.type==="loop"){let n=Nt(t.steps,e);if(n)return n}}}function Qc(r,e,t){return Q(r,e,n=>{let o=(n.iterations??[]).map(i=>{if(i.index!==t)return i;let s=i.stepExecutions.every(a=>a.completedAt)?i.stepExecutions.map(a=>a.completedAt).reduce((a,u)=>a>u?a:u):void 0;return{...i,...s?{completedAt:s}:{}}});return{...n,iterations:o}})}function hi(r){let e=[];for(let t of r){t.childJobIds&&e.push(...t.childJobIds);for(let n of t.iterations??[])e.push(...hi(n.stepExecutions))}return e}var Xc=l(()=>{"use strict"});import{z as le}from"zod";function Yc(r,e){let t=Wm[r].safeParse(e);if(!t.success){let n=t.error.issues.map(o=>`${o.path.length?o.path.join("."):"(root)"}: ${o.message}`).join("; ");throw new Error(`Agent output failed validation for format '${r}': ${n}`)}return t.data}var Jm,Lm,Um,Mm,Wm,Zc=l(()=>{"use strict";Jm=le.object({questions:le.array(le.object({id:le.string(),prompt:le.string()}))}),Lm=le.object({approved:le.boolean()}),Um=le.object({suggestions:le.array(le.object({body:le.string()}))}),Mm=le.string(),Wm={questionnaire:Jm,confirmation:Lm,comment_suggestions:Um,free_text:Mm}});function ge(r){return r==="completed"||r==="failed"||r==="cancelled"}function yi(r,e){let t=new Map;for(let o of r){let i=e(o);if(i==null)continue;let s=t.get(i)??[];s.push(o),t.set(i,s)}if(t.size===0)return null;let n=[];for(let o of t.values()){let i=new Set(o.map(a=>a.retryOf).filter(a=>a!=null)),s=o.find(a=>!i.has(a.id));if(!s)return null;n.push(s)}return{activeJobs:n,allTerminal:n.every(o=>ge(o.status)),groupCount:t.size}}function eu(r){let e=r.every(n=>n.status==="completed"),t=r.every(n=>n.status==="failed"||n.status==="cancelled");return e?"completed":t?"failed":"completed_with_issues"}var gi=l(()=>{"use strict"});async function Bn(r,e,t){let n=await e.get(r);if(!n)throw new y(`SubjectView not found: ${r}`);if(!n.providerInstanceId)throw new h(`SubjectView '${r}' has no providerInstanceId \u2014 reconfigure the View to pick a provider instance`);if(n.subjectType==="ticket")return(await t.getTicketProvider(n.providerInstanceId).query(n.query)).map(i=>({subjectType:"ticket",...i}));if(n.subjectType==="pull_request")return(await t.getRepoProvider(n.providerInstanceId).query(n.query)).map(i=>({subjectType:"pull_request",...i}));if(n.subjectType==="documentation")return(await t.getDocumentationProvider(n.providerInstanceId).query(n.query)).map(i=>({subjectType:"documentation",...i}));throw new h(`Unsupported subjectType on view: ${n.subjectType}`)}var wi=l(()=>{"use strict";R()});import{Injectable as Vm}from"@nestjs/common";var Hm,St,bi=l(()=>{"use strict";Hm=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},St=class{requested=new Set;requestCancellation(e){this.requested.add(e)}isCancellationRequested(e){return this.requested.has(e)}clear(e){this.requested.delete(e)}};St=Hm([Vm()],St)});import{Logger as Km}from"@nestjs/common";import{readFile as Gm}from"node:fs/promises";async function tu(r,e,t=new Km("resolveContextFiles"),n=o=>Gm(o,"utf8")){let o=[];for(let i of r){let s=await e.get(i);if(!s){t.warn(`Context file '${i}' is no longer in the catalog; skipping`);continue}try{let a=await n(s.path);o.push({tier:s.tier,content:a,sourceRef:s.path})}catch(a){let u=a instanceof Error?a.message:String(a);throw new Error(`Cannot read context file '${s.name}' at ${s.path}: ${u}`)}}return o}var ru=l(()=>{"use strict"});import{basename as zm,dirname as Qm,join as Xm,resolve as br,sep as nu}from"node:path";function Ym(r){return r.replace(/-/g,"").slice(0,4)}function ou(r,e){return`${r}-${Ym(e)}`}function Si(r){return r.replace(/[\\/:*?"<>|]/g,"-")}function Dn(r){let e=br(r);return Xm(Qm(e),`${zm(e)}-worktrees`)}function Fn(r,e){let t=br(r),n=br(e);if(ut(t,n))return!0;let o=t.endsWith(nu)?t:t+nu,i=process.platform==="win32"?n.toLowerCase():n,s=process.platform==="win32"?o.toLowerCase():o;return i.startsWith(s)}function ut(r,e){let t=br(r),n=br(e);return process.platform==="win32"?t.toLowerCase()===n.toLowerCase():t===n}var xi=l(()=>{"use strict"});import{join as iu}from"node:path";async function su(r,e,t){let n={...e},o=await t.list();for(let i of r){if(i.type!=="localRepository")continue;let s=n[i.name];if(s==null||s==="")continue;let a=String(s),u=o.find(m=>m.id===a),c=o.find(m=>ut(m.localPath,a)),p=u??c;if(!p)throw new h(`Unknown local repository: ${a}`);n[i.name]=p.localPath}return n}async function au(r){let{job:e,params:t,git:n,jobs:o,localRepositories:i}=r,s=Nn(t,"repoPath"),a=t.mode==="existing-branch"?"existing-branch":"new-branch",u=(await i.list()).find(S=>ut(S.localPath,s)),c=u?.worktreeBasePath?.trim()?u.worktreeBasePath.trim():Dn(s);if(Fn(s,c)&&!ut(s,c))throw new Error(`Worktree base '${c}' must not be inside the repository at '${s}'`);if(a==="existing-branch")return Zm({job:e,repoPath:s,branch:Nn(t,"branch"),worktreeBase:c,explicitPath:typeof t.worktreePath=="string"?t.worktreePath:void 0,git:n,jobs:o});let p=Nn(t,"branchName"),m=ou(p,e.id),b=typeof t.worktreePath=="string"&&t.worktreePath.trim()!==""?t.worktreePath:iu(c,Si(m));return n.createWorktree(e.id,{repoPath:s,baseBranch:Nn(t,"baseBranch"),branchName:m,worktreePath:b})}async function Zm(r){let{job:e,repoPath:t,branch:n,worktreeBase:o,git:i,jobs:s}=r,a=await i.listWorktrees(t),u=a.filter(b=>b.branch===n&&!ut(b.path,t)),c=a.find(b=>b.branch===n&&ut(b.path,t));if(u.length===0){if(c)throw new Error(`branch ${n} is checked out in the repository working copy; refusing to reuse the main clone`);let b=r.explicitPath&&r.explicitPath.trim()!==""?r.explicitPath:iu(o,Si(n));return i.addWorktreeForExistingBranch({repoPath:t,branch:n,worktreePath:b})}let p=u[0].path,m=await eh(s,p);if(m&&!ge(m.status))throw new Error(`branch ${n} already has an active worktree in use by Job ${m.id}`);return m&&m.id!==e.id&&await s.update(m.id,{worktreeDeletedAt:new Date().toISOString()}),await i.resetWorktreeToRemote(p,n),{worktreePath:p,branch:n}}async function eh(r,e){let n=(await r.list({liveWorktree:!0})).filter(o=>o.worktreePath!=null&&ut(o.worktreePath,e));return n.find(o=>!ge(o.status))??n.sort((o,i)=>i.updatedAt.localeCompare(o.updatedAt))[0]}function Nn(r,e){let t=r[e];if(typeof t!="string"||t.trim()==="")throw new Error(`git step missing required param '${e}'`);return t}var cu=l(()=>{"use strict";R();xi();gi()});import{Inject as pe,Injectable as nh,Logger as oh}from"@nestjs/common";import{randomUUID as vi}from"node:crypto";import{exec as ih}from"node:child_process";import{promisify as sh}from"node:util";async function Ii(r,e,t){if(r.length===0)throw new Error(t);let n;for(let o of r)try{return await e(o)}catch(i){n=i}throw n instanceof Error?n:new Error(t)}function uu(r,e){let t=e[r.stepId];if(t==null||typeof t!="object")return r.type==="field_empty";let n=t[r.field];return r.type==="field_empty"?n==null?!0:typeof n=="string"||Array.isArray(n)?n.length===0:!1:n===r.value}function uh(r,e){let t=o=>{let i=[];for(let s of o)i.push(s),s.type==="loop"&&i.push(...t(s.steps));return i},n=o=>{let i=o.findIndex(s=>s.id===e);if(i>=0){for(let s=i-1;s>=0;s--)if(o[s].type==="agent")return o[s].id;return}for(let s of o)if(s.type==="loop"){let a=n(s.steps);if(a!==void 0||s.steps.some(u=>u.id===e))return a}};return n(r.steps)}function xt(r){let e={...r.context};return r.subjectContext?.mode==="single"&&(e.subject=r.subjectContext.subject),r.worktreePath&&(e.worktreePath=r.worktreePath),r.branch&&(e.branch=r.branch),e}function lh(r){if(r===null||typeof r!="object"||Array.isArray(r))throw new Error("Extract resume payload must be an object with an action");let e=r;if(e.action==="provide_value"){if(typeof e.value!="string")throw new Error("Extract resume action 'provide_value' requires a string value");return{action:"provide_value",value:e.value}}if(e.action==="continue"||e.action==="cancel")return{action:e.action};throw new Error(`Unknown extract resume action: ${String(e.action)}`)}function Jn(r){if(!r.worktreePath)throw new Error(`Job ${r.id} has no worktreePath; run create_worktree first`);return r.worktreePath}function vt(r,e){let t=r[e];if(typeof t!="string"||t.length===0)throw new Error(`Missing required string param '${e}'`);return t}function dh(r){if(r==="none")throw new Error("normalizeAppliesTo called with none");if(Array.isArray(r)){if(r.length!==1)throw new Error(`Workflow Runner requires appliesTo to be a single SubjectType (got ${JSON.stringify(r)})`);return r[0]}return r}function lu(r,e){for(let t of r)if(t.required&&(e[t.name]===void 0||e[t.name]===null))throw new h(`Missing required input: ${t.name}`)}var th,rh,de,ji,ah,ch,we,Ln=l(()=>{"use strict";mt();pr();Br();qr();Tn();li();Pe();Dr();Fr();Bt();wo();fn();R();pi();Kc();zc();Xc();Zc();gi();wi();bi();ru();cu();th=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},rh=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},de=function(r,e){return function(t,n){e(t,n,r)}},ah=sh(ih),ch=new Set(["agent","shell","git","provider_action"]),we=ji=class{workflows;jobs;batches;views;events;providers;notifications;contextFiles;localRepositories;git;settings;cancellation;logger=new oh(ji.name);childTerminalLocks=new Set;batchTerminalLocks=new Set;constructor(e,t,n,o,i,s,a,u,c,p,m,b){this.workflows=e,this.jobs=t,this.batches=n,this.views=o,this.events=i,this.providers=s,this.notifications=a,this.contextFiles=u,this.localRepositories=c,this.git=p,this.settings=m,this.cancellation=b,this.events.subscribe(S=>{let j=S;(j.type==="job_completed"||j.type==="job_failed"||j.type==="job_cancelled")&&this.onChildTerminal(j.jobId)})}async start(e){let t=await this.createJob(e);return this.emit({type:"job_started",jobId:t.id,timestamp:new Date().toISOString()}),this.runJob(t.id)}async launch(e){let t=await this.requireWorkflow(e.workflowId);if(t.subjectHandling!=="per-subject"&&t.subjectHandling!=="collection")throw new h(`Unsupported subjectHandling: ${String(t.subjectHandling)}`);lu(t.inputSchema,e.inputValues);let n=await this.resolveSelection(e.selection);if(t.subjectHandling==="collection"){let a=await this.createJob({workflowId:t.id,subjectContext:{mode:"collection",subjects:n},selection:e.selection,inputValues:e.inputValues});return this.emit({type:"job_started",jobId:a.id,timestamp:new Date().toISOString()}),this.runJob(a.id)}let o=new Date().toISOString(),i=await this.batches.create({id:vi(),workflowId:t.id,selection:e.selection,resolvedSubjects:n,status:"running",triggeredBy:e.triggeredBy,...e.notificationOverride?{notificationOverride:e.notificationOverride}:{},notificationSent:!1,createdAt:o}),s=[];for(let a=0;a<n.length;a++){let u=n[a],c=await this.createJob({workflowId:t.id,subjectContext:{mode:"single",subject:u},selection:e.selection,batchId:i.id,fanOutIndex:a,inputValues:e.inputValues});s.push(c)}for(let a of s)this.emit({type:"job_started",jobId:a.id,timestamp:new Date().toISOString()}),await this.runJob(a.id);return await this.batches.get(i.id)}async createJob(e){let t=e.workflowSnapshot?structuredClone(e.workflowSnapshot):await this.workflows.get(e.workflowId);if(!t)throw new y(`Workflow not found: ${e.workflowId}`);if(!e.subjectContext&&t.subjectHandling!=="per-subject")throw new h(`Workflow Runner only supports subjectHandling 'per-subject' at start() without an explicit subjectContext (got '${t.subjectHandling}')`);let n=await su(t.inputSchema,e.inputValues,this.localRepositories);lu(t.inputSchema,n);let o=e.subjectContext??await this.resolveSubjectContext(t,e.subjectId),i=new Date().toISOString();return this.jobs.create({id:vi(),workflowId:t.id,status:"pending",...o?{subjectContext:o}:{},...e.selection?{selection:e.selection}:{},...e.batchId?{batchId:e.batchId}:{},...e.parentJobId?{parentJobId:e.parentJobId}:{},...e.parentStepExecutionId?{parentStepExecutionId:e.parentStepExecutionId}:{},...e.fanOutIndex!=null?{fanOutIndex:e.fanOutIndex}:{},...e.retryOf?{retryOf:e.retryOf}:{},workflowSnapshot:structuredClone(t),context:{...n},stepHistory:[],createdAt:i,updatedAt:i})}async deleteWorktrees(e){if(e.length===0)throw new h("jobIds is required");let t=[];for(let s of e){let a=await this.jobs.get(s);if(!a)throw new y(`Job not found: ${s}`);t.push(a)}let n=t.find(s=>!ge(s.status));if(n)throw new J(`Cannot delete worktree for active Job ${n.id}`);let o=new Date().toISOString(),i=[];for(let s of t){s.worktreePath&&!s.worktreeDeletedAt&&await this.git.removeWorktree(s.worktreePath);let a=await this.jobs.update(s.id,{worktreeDeletedAt:o,updatedAt:o});i.push(a)}return i}async runJob(e){let t=await this.jobs.get(e);if(!t)throw new y(`Job not found: ${e}`);if(ge(t.status))return t;let n=await this.workflowForJob(t);if(t.status==="pending"&&(t=await this.persistJob({...t,status:"planning",updatedAt:new Date().toISOString()}),t.status==="cancelled"))return t;let o=await this.executeStepSequence(t,n,n.steps,void 0,void 0,0);return o.outcome!=="completed"?o.job:this.completeJob(o.job,n)}async resume(e,t){let n=await this.jobs.get(e);if(!n)throw new y(`Job not found: ${e}`);if(n.status!=="waiting_for_human")throw new J(`Job ${e} is not waiting for human input (status: ${n.status})`);let o=await this.workflowForJob(n),i=n.currentStepExecutionId;if(!i)throw new Error(`Job ${e} is waiting_for_human but has no currentStepExecutionId`);let s=ct(n.stepHistory,i);if(!s)throw new Error(`Paused execution ${i} not found on job ${e}`);if(s.type==="loop")return this.resumeAskHuman(n,o,s,t);if(s.type==="extract")return this.resumeExtract(n,o,s,t);if(s.type!=="interaction")throw new Error(`Paused execution ${i} has type '${s.type}'; expected interaction, extract, or loop`);let a=new Date().toISOString(),u=Q(n.stepHistory,i,j=>({...j,status:"completed",completedAt:a,output:t})),c=t!==null&&typeof t=="object"&&!Array.isArray(t)?t:{response:t};n=await this.persistJob({...n,status:"planning",context:{...n.context,[s.stepDefinitionId]:t},stepHistory:u,currentStepId:void 0,currentStepExecutionId:void 0,updatedAt:a}),this.emit({type:"human_answered",jobId:n.id,answers:c,timestamp:a});let p=bt(n.stepHistory,i);if(!p)throw new Error(`Could not locate frame for execution ${i}`);let m=this.sequenceForFrameOnJob(n,o,p),b=p.index+1,S=await this.executeStepSequence(n,o,m,p.parentLoopExecutionId,p.iterationIndex,b);return S.outcome!=="completed"?S.job:p.parentLoopExecutionId!=null&&p.iterationIndex!=null?this.continueLoopAfterBody(S.job,o,p.parentLoopExecutionId,p.iterationIndex):this.completeJob(S.job,o)}async retryFailedJob(e){let t=await this.jobs.get(e);if(!t)throw new y(`Job not found: ${e}`);if(t.status!=="failed")throw new J(`Job ${e} is not failed (status: ${t.status})`);let n=t.parentJobId!=null&&t.parentStepExecutionId!=null&&t.fanOutIndex!=null,o=t.batchId!=null&&t.fanOutIndex!=null;if(n){let a=await this.jobs.get(t.parentJobId);if(!a)throw new y(`Parent job not found: ${t.parentJobId}`);let u=await this.createJob({workflowId:t.workflowId,subjectContext:t.subjectContext,inputValues:{},parentJobId:t.parentJobId,parentStepExecutionId:t.parentStepExecutionId,fanOutIndex:t.fanOutIndex,retryOf:t.id,workflowSnapshot:t.workflowSnapshot}),c=Q(a.stepHistory,t.parentStepExecutionId,p=>({...p,status:"waiting_for_children",error:void 0,completedAt:void 0,childJobIds:[...p.childJobIds??[],u.id]}));return a=await this.persistJob({...a,status:"waiting_for_children",stepHistory:c,completedAt:void 0,updatedAt:new Date().toISOString()}),this.emitRetryLaunch(u.id,t.id),this.runJob(u.id),u}if(o){let a=await this.batches.get(t.batchId);if(!a)throw new y(`JobBatch not found: ${t.batchId}`);a.status!=="running"&&await this.batches.update(a.id,{status:"running",completedAt:null,notificationSent:!1});let u=await this.createJob({workflowId:t.workflowId,subjectContext:t.subjectContext,selection:t.selection,batchId:t.batchId,fanOutIndex:t.fanOutIndex,inputValues:{},retryOf:t.id,workflowSnapshot:t.workflowSnapshot});return this.emitRetryLaunch(u.id,t.id),this.runJob(u.id),u}let i=await this.workflowForJob(t),s=await this.createJob({workflowId:t.workflowId,subjectContext:t.subjectContext,selection:t.selection,inputValues:this.inputValuesFromContext(t.context,i),retryOf:t.id,workflowSnapshot:t.workflowSnapshot});return this.emitRetryLaunch(s.id,t.id),this.runJob(s.id),s}async retryFailedStep(e){let t=await this.jobs.get(e);if(!t)throw new y(`Job not found: ${e}`);if(t.status!=="failed")throw new J(`Job ${e} is not failed (status: ${t.status})`);let n=t.currentStepExecutionId;if(!n)throw new J(`Job ${e} has no currentStepExecutionId; cannot retry the failed step`);let o=ct(t.stepHistory,n);if(!o)throw new J(`Job ${e} currentStepExecutionId ${n} was not found in stepHistory`);if(o.type==="sub_workflow")throw new J("Step-level retry is not available for sub_workflow steps. Retry the specific failed child job instead.");if(!ch.has(o.type))throw new J(`Step-level retry is not available for '${o.type}' steps`);let i=await this.workflowForJob(t),s=bt(t.stepHistory,n);if(!s)throw new J(`Could not locate execution frame for ${n} on job ${e}`);let a=this.sequenceForFrameOnJob(t,i,s),u=a[s.index];if(!u||u.id!==o.stepDefinitionId)throw new J(`Failed step '${o.stepDefinitionId}' does not match sequence position ${s.index}`);let c=new Date().toISOString(),p={...t.context};delete p[o.stepDefinitionId];let m=await this.persistJob({...t,status:"planning",context:p,completedAt:void 0,currentStepId:o.stepDefinitionId,currentStepExecutionId:o.id,stepHistory:Q(t.stepHistory,o.id,S=>({...S,status:"running",error:void 0,completedAt:void 0,output:void 0,startedAt:c})),updatedAt:c}),b=await this.executeStepSequence(m,i,a,s.parentLoopExecutionId,s.iterationIndex,s.index,o.id);return b.outcome!=="completed"?b.job:s.parentLoopExecutionId!=null&&s.iterationIndex!=null?this.continueLoopAfterBody(b.job,i,s.parentLoopExecutionId,s.iterationIndex):this.completeJob(b.job,i)}async cancelJob(e){let t=await this.jobs.get(e);if(!t)throw new y(`Job not found: ${e}`);if(ge(t.status))throw new J(`Job ${e} is already terminal (status: ${t.status})`);for(let i of hi(t.stepHistory)){let s=await this.jobs.get(i);s&&!ge(s.status)&&await this.cancelJob(i)}let n=await this.jobs.get(e);if(ge(n.status))return n;this.cancellation.requestCancellation(e);let o=await this.persistCancelled(n);return(n.status==="waiting_for_human"||n.status==="waiting_for_children")&&this.cancellation.clear(e),await this.onBatchMemberTerminal(o.id),o}async cancelBatch(e){let t=await this.batches.get(e);if(!t)throw new y(`JobBatch not found: ${e}`);if(t.status!=="running")throw new J(`JobBatch ${e} is already terminal (status: ${t.status})`);let n=await this.jobs.list({batchId:e});for(let s of n)ge(s.status)||await this.cancelJob(s.id);let o=new Date().toISOString(),i=await this.batches.update(e,{status:"cancelled",completedAt:o});if(!i)throw new Error(`Failed to persist cancelled batch ${e}`);return this.emit({type:"batch_cancelled",batchId:i.id,timestamp:o}),i}async executeStepSequence(e,t,n,o,i,s,a){let u=e;for(let c=s;c<n.length;c++){let p=await this.stopIfCancelled(u);if(p)return{outcome:"cancelled",job:p};let m=n[c],b=new Date().toISOString(),S=c===s?a:void 0,j,N=u.stepHistory;if(S){let A=ct(u.stepHistory,S);if(!A)throw new Error(`Reuse execution ${S} not found on job ${u.id}`);j=A}else j={id:vi(),stepDefinitionId:m.id,type:m.type,status:"running",startedAt:b},N=mi(u.stepHistory,j,o,i);if(u=await this.persistJob({...u,status:u.status==="pending"?"planning":u.status,currentStepId:m.id,currentStepExecutionId:j.id,stepHistory:N,updatedAt:b}),u.status==="cancelled")return{outcome:"cancelled",job:u};this.emit({type:"step_started",jobId:u.id,stepDefinitionId:m.id,timestamp:b});try{let A=await this.dispatchStep(u,t,m,j.id,o,i);u=A.job;let Ke=await this.stopIfCancelled(u);if(Ke)return{outcome:"cancelled",job:Ke};if(A.outcome!=="completed")return A}catch(A){let Ke=await this.failJob(u,t,j.id,m.id,A);return Ke.status==="cancelled"?{outcome:"cancelled",job:Ke}:{outcome:"failed",job:Ke}}}return o!=null&&i!=null&&(u=await this.persistJob({...u,stepHistory:Qc(u.stepHistory,o,i),updatedAt:new Date().toISOString()})),{outcome:"completed",job:u}}async dispatchStep(e,t,n,o,i,s){switch(n.type){case"agent":return{outcome:"completed",job:await this.executeAgentStep(e,n,o)};case"interaction":return{outcome:"paused",job:await this.pauseForInteraction(e,t,n,o)};case"git":return{outcome:"completed",job:await this.executeGitStep(e,n,o)};case"provider_action":return{outcome:"completed",job:await this.executeProviderActionStep(e,n,o)};case"shell":return{outcome:"completed",job:await this.executeShellStep(e,n,o)};case"loop":return this.runLoopStep(e,t,n,o,i,s);case"sub_workflow":return this.runSubWorkflowStep(e,n,o);case"extract":return this.executeExtractStep(e,t,n,o);default:{let a=n;throw new h(`Step type '${a.type}' not yet supported by the Workflow Runner`)}}}async runLoopStep(e,t,n,o,i,s,a=0,u=n.maxIterations){let c=e,p=a;for(;;){if(p>=u)switch(n.onMaxIterations.action){case"fail":return c=await this.failExecution(c,t,o,n.id,`Loop '${n.id}' exceeded maxIterations (${u})`),{outcome:"failed",job:c};case"continue":return c=await this.finishExecution(c,o,n.id,{iterations:p,exitedOnMaxIterations:!0}),{outcome:"completed",job:c};case"ask_human":{let b={maxIterationsCheckpoint:!0,nextIteration:p,effectiveMaxIterations:u},S=new Date().toISOString(),j=Q(c.stepHistory,o,N=>({...N,status:"pending",output:b}));return c=await this.persistJob({...c,status:"waiting_for_human",currentStepId:n.id,currentStepExecutionId:o,stepHistory:j,updatedAt:S}),this.emit({type:"waiting_for_human",jobId:c.id,stepDefinitionId:n.id,interaction:"confirmation",data:b,questions:[`Loop '${n.id}' reached maxIterations (${u}). Extend, continue, or cancel?`],timestamp:S}),t.notificationPolicy.triggers.includes("on_needs_input")&&await this.notifications.send({title:`Input needed: ${t.name}`,body:`Job ${c.id} hit max iterations on loop '${n.id}'`,jobId:c.id}),{outcome:"paused",job:c}}default:{let b=n.onMaxIterations;throw new Error(`Unknown onMaxIterations action: ${JSON.stringify(b)}`)}}let m=await this.executeStepSequence(c,t,n.steps,o,p,0);if(c=m.job,m.outcome!=="completed")return m;if(uu(n.until,c.context))return c=await this.finishExecution(c,o,n.id,{iterations:p+1}),{outcome:"completed",job:c};p+=1}}async resumeAskHuman(e,t,n,o){let i=o,s=n.output;if(!s?.maxIterationsCheckpoint)throw new Error(`Loop execution ${n.id} is not at an ask_human checkpoint`);let a=Nt(t.steps,n.stepDefinitionId);if(!a||a.type!=="loop")throw new Error(`Loop step definition '${n.stepDefinitionId}' not found`);let u=bt(e.stepHistory,n.id),c=new Date().toISOString();if(i.action==="cancel")return await this.failExecution({...e,status:"planning",currentStepId:void 0,currentStepExecutionId:void 0,updatedAt:c},t,n.id,a.id,"Loop cancelled by human at maxIterations checkpoint");if(i.action==="continue"){let j=await this.persistJob({...e,status:"planning",currentStepId:void 0,currentStepExecutionId:void 0,stepHistory:Q(e.stepHistory,n.id,N=>({...N,status:"completed",completedAt:c,output:{iterations:s.nextIteration,exitedOnMaxIterations:!0,humanAction:"continue"}})),updatedAt:c});return this.emit({type:"human_answered",jobId:j.id,answers:i,timestamp:c}),this.emit({type:"step_completed",jobId:j.id,stepDefinitionId:a.id,timestamp:c}),u?.parentLoopExecutionId!=null&&u.iterationIndex!=null?this.continueLoopAfterBody(j,t,u.parentLoopExecutionId,u.iterationIndex):this.continueTopLevelAfter(j,t,a.id)}let p=typeof i.additionalIterations=="number"?i.additionalIterations:0,m=s.effectiveMaxIterations+p,b=await this.persistJob({...e,status:"planning",currentStepId:void 0,currentStepExecutionId:void 0,stepHistory:Q(e.stepHistory,n.id,j=>({...j,status:"running",output:void 0})),updatedAt:c});this.emit({type:"human_answered",jobId:b.id,answers:i,timestamp:c});let S=await this.runLoopStep(b,t,a,n.id,u?.parentLoopExecutionId,u?.iterationIndex,s.nextIteration,m);return S.outcome!=="completed"?S.job:u?.parentLoopExecutionId!=null&&u.iterationIndex!=null?this.continueLoopAfterBody(S.job,t,u.parentLoopExecutionId,u.iterationIndex):this.continueTopLevelAfter(S.job,t,a.id)}async resumeExtract(e,t,n,o){let i=lh(o),s=Nt(t.steps,n.stepDefinitionId);if(!s||s.type!=="extract")throw new Error(`Extract step definition '${n.stepDefinitionId}' not found`);let a=new Date().toISOString();if(i.action==="cancel")return this.failExecution({...e,status:"planning",currentStepId:void 0,currentStepExecutionId:void 0,updatedAt:a},t,n.id,s.id,`Extract '${s.id}' cancelled by human`);let u=i.action==="continue"?"":i.value,c=await this.finishExecution({...e,status:"planning",currentStepId:void 0,currentStepExecutionId:void 0,updatedAt:a},n.id,s.id,u);this.emit({type:"human_answered",jobId:c.id,answers:i,timestamp:a});let p=bt(e.stepHistory,n.id);if(!p)throw new Error(`Could not locate frame for execution ${n.id}`);let m=this.sequenceForFrameOnJob(c,t,p),b=p.index+1,S=await this.executeStepSequence(c,t,m,p.parentLoopExecutionId,p.iterationIndex,b);return S.outcome!=="completed"?S.job:p.parentLoopExecutionId!=null&&p.iterationIndex!=null?this.continueLoopAfterBody(S.job,t,p.parentLoopExecutionId,p.iterationIndex):this.completeJob(S.job,t)}async continueLoopAfterBody(e,t,n,o){let i=ct(e.stepHistory,n);if(!i)throw new Error(`Loop execution ${n} not found`);let s=Nt(t.steps,i.stepDefinitionId);if(!s||s.type!=="loop")throw new Error(`Loop step '${i.stepDefinitionId}' not found`);let a=bt(e.stepHistory,n),u=i.output?.effectiveMaxIterations??s.maxIterations,c=e;if(uu(s.until,c.context))c=await this.finishExecution(c,n,s.id,{iterations:o+1});else{let p=o+1,m=await this.runLoopStep(c,t,s,n,a?.parentLoopExecutionId,a?.iterationIndex,p,u);if(m.outcome!=="completed")return m.job;c=m.job}return a?.parentLoopExecutionId!=null&&a.iterationIndex!=null?this.continueLoopAfterBody(c,t,a.parentLoopExecutionId,a.iterationIndex):this.continueTopLevelAfter(c,t,s.id)}async continueTopLevelAfter(e,t,n){let o=t.steps.findIndex(s=>s.id===n),i=await this.executeStepSequence(e,t,t.steps,void 0,void 0,o+1);return i.outcome!=="completed"?i.job:this.completeJob(i.job,t)}sequenceForFrameOnJob(e,t,n){if(n.parentLoopExecutionId==null)return t.steps;let o=ct(e.stepHistory,n.parentLoopExecutionId);if(!o)throw new Error(`Parent loop execution ${n.parentLoopExecutionId} not found`);let i=Nt(t.steps,o.stepDefinitionId);if(!i||i.type!=="loop")throw new Error(`Parent loop step '${o.stepDefinitionId}' not found`);return i.steps}async runSubWorkflowStep(e,t,n){if(!e.subjectContext||e.subjectContext.mode!=="collection")throw new h(`sub_workflow steps require subjectContext.mode === 'collection' (job ${e.id})`);let o=e.subjectContext.subjects,i=[];for(let p=0;p<o.length;p++){let m=o[p],b=await this.createJob({workflowId:t.workflowId,subjectContext:{mode:"single",subject:m},inputValues:{},parentJobId:e.id,parentStepExecutionId:n,fanOutIndex:p});i.push(b)}let s=i.map(p=>p.id),a=new Date().toISOString(),u=Q(e.stepHistory,n,p=>({...p,status:"waiting_for_children",childJobIds:s})),c=await this.persistJob({...e,status:"waiting_for_children",currentStepId:t.id,currentStepExecutionId:n,stepHistory:u,updatedAt:a});for(let p of i)this.emit({type:"job_started",jobId:p.id,timestamp:a}),this.runJob(p.id);return{outcome:"paused",job:c}}async onChildTerminal(e){let t=await this.jobs.get(e);if(!t?.parentJobId||!t.parentStepExecutionId)return;let n=`${t.parentJobId}:${t.parentStepExecutionId}`;if(!this.childTerminalLocks.has(n)){this.childTerminalLocks.add(n);try{let o=(await this.jobs.list({parentJobId:t.parentJobId,parentStepExecutionId:t.parentStepExecutionId})).filter(A=>A.parentStepExecutionId===t.parentStepExecutionId),i=yi(o,A=>A.fanOutIndex);if(!i?.allTerminal)return;let{activeJobs:s}=i,a=await this.jobs.get(t.parentJobId);if(!a||a.status==="cancelled"||a.status!=="waiting_for_children"&&a.status!=="failed")return;let u=await this.workflowForJob(a),c=t.parentStepExecutionId,p=ct(a.stepHistory,c);if(!p||p.type!=="sub_workflow")return;let m=s.some(A=>A.status==="failed");if(s.some(A=>A.status==="cancelled"))return;if(m){await this.failExecution(a,u,c,p.stepDefinitionId,"One or more child jobs failed");return}let S=s.slice().sort((A,Ke)=>(A.fanOutIndex??0)-(Ke.fanOutIndex??0)).map(A=>({fanOutIndex:A.fanOutIndex,jobId:A.id,output:A.context})),j=new Date().toISOString();a=await this.persistJob({...a,status:"planning",context:{...a.context,[p.stepDefinitionId]:S},currentStepId:void 0,currentStepExecutionId:void 0,stepHistory:Q(a.stepHistory,c,A=>({...A,status:"completed",completedAt:j,output:S})),completedAt:void 0,updatedAt:j}),this.emit({type:"step_completed",jobId:a.id,stepDefinitionId:p.stepDefinitionId,timestamp:j});let N=await this.continueTopLevelAfter(a,u,p.stepDefinitionId)}finally{this.childTerminalLocks.delete(n)}}}async onBatchMemberTerminal(e){let t=await this.jobs.get(e);if(!t?.batchId)return;let n=t.batchId;if(!this.batchTerminalLocks.has(n)){this.batchTerminalLocks.add(n);try{let o=await this.batches.get(t.batchId);if(!o||o.status!=="running")return;let i=await this.jobs.list({batchId:o.id}),s=yi(i,m=>m.fanOutIndex);if(!s||s.groupCount!==o.resolvedSubjects.length||!s.allTerminal)return;let{activeJobs:a}=s,u=eu(a),c=new Date().toISOString(),p=await this.batches.update(o.id,{status:u,completedAt:c});if(!p)return;if(this.emit({type:"batch_completed",batchId:p.id,summary:a.map(m=>({jobId:m.id,status:m.status})),timestamp:c}),!p.notificationSent){let m=await this.workflowForJob(t),b=p.notificationOverride??m.notificationPolicy,S=u==="completed"?"on_complete":"on_fail";b.triggers.includes(S)&&await this.notifications.send({title:`Batch ${u}: ${m.name}`,body:`JobBatch ${p.id} finished with status '${u}' (${a.length} members)`,batchId:p.id}),await this.batches.update(p.id,{notificationSent:!0})}}finally{this.batchTerminalLocks.delete(n)}}}async resolveSelection(e){if(e.mode==="view")return Bn(e.viewId,this.views,this.providers);let t=[];for(let n of e.subjectIds)if(e.subjectType==="ticket"){let o=await this.getTicketById(n);t.push({subjectType:"ticket",...o})}else if(e.subjectType==="pull_request"){let o=await this.getPullRequestById(n);t.push({subjectType:"pull_request",...o})}else if(e.subjectType==="documentation"){let o=await this.getDocumentationById(n);t.push({subjectType:"documentation",...o})}else throw new h(`Unsupported subjectType: ${e.subjectType}`);return t}async executeAgentStep(e,t,n){let o=await tu(t.contextFileIds??[],this.contextFiles,this.logger),i=xt(e),s=Ft(t.objective,i),a=t.agentInstanceId??(await this.settings.get()).defaultAgentInstanceId;if(!a)throw new Error("No default agent instance configured (set EngineSettings.defaultAgentInstanceId)");let u=await this.providers.getAgentProvider(a).run({objective:s,outputFormat:t.outputFormat,knowledge:o,context:{...i,stepId:t.id},...e.worktreePath?{cwd:e.worktreePath}:{}}),c=Yc(t.outputFormat,u.parsed);return this.finishExecution(e,n,t.id,c)}async executeGitStep(e,t,n){let o=Dt(t.params,xt(e));switch(t.operation){case"create_worktree":{let i=await au({job:e,params:o,git:this.git,jobs:this.jobs,localRepositories:this.localRepositories});return this.finishExecution(e,n,t.id,i,{worktreePath:i.worktreePath,branch:i.branch})}case"create_branch":{let i=Jn(e),s=vt(o,"branchName");return await this.git.createBranch(i,{branchName:s,...typeof o.baseBranch=="string"?{baseBranch:o.baseBranch}:{}}),this.finishExecution(e,n,t.id,{branch:s},{branch:s})}case"checkout":{let i=Jn(e),s=vt(o,"branch");return await this.git.checkout(i,{branch:s}),this.finishExecution(e,n,t.id,{branch:s},{branch:s})}case"commit":{let i=Jn(e),s=await this.git.commit(i,{message:vt(o,"message"),addAll:o.addAll!==!1});return this.finishExecution(e,n,t.id,s)}case"push":{let i=Jn(e);return await this.git.push(i,{...typeof o.remote=="string"?{remote:o.remote}:{},...typeof o.branch=="string"?{branch:o.branch}:{}}),this.finishExecution(e,n,t.id,{remote:typeof o.remote=="string"?o.remote:"origin",branch:typeof o.branch=="string"?o.branch:e.branch})}default:{let i=t.operation;throw new Error(`Unknown git operation: ${i}`)}}}async executeProviderActionStep(e,t,n){if(!e.subjectContext||e.subjectContext.mode!=="single")throw new h(`provider_action steps require subjectContext.mode === 'single' (job ${e.id})`);let o=this.resolveProviderActionSubject(e,t);if(t.extendedAction)return this.executeExtendedProviderAction(e,t,n,o);let i=Dt(t.params??{},xt(e))??{},s=await this.dispatchPortableProviderAction(o,t.action,i);return this.finishExecution(e,n,t.id,s)}resolveProviderActionSubject(e,t){if(!t.target){let o=e.subjectContext;if(!o||o.mode!=="single")throw new h(`provider_action steps require subjectContext.mode === 'single' (job ${e.id})`);let i=o.subject;return{subjectType:i.subjectType,source:i.source,subjectId:i.id}}let n=Ft(t.target.subjectId,xt(e)).trim();if(!n)throw new Error(`provider_action '${t.id}' target.subjectId interpolated to an empty id`);return{subjectType:t.target.subjectType,source:t.target.source,subjectId:n}}async dispatchPortableProviderAction(e,t,n){let{subjectType:o,source:i,subjectId:s}=e;if(o==="documentation"){let u=this.providers.getDocumentationProvider(i);switch(t){case"get_subject":return u.get(s);case"get_content":return u.getContent(s);case"get_comments":return u.getComments(s);case"post_comment":return await u.postComment(s,vt(n,"body")),{posted:!0};case"update_status":throw new Error(`Provider action '${t}' is not valid for subject type 'documentation'`);default:{let c=t;throw new Error(`Unknown provider action: ${c}`)}}}let a=o==="ticket"?this.providers.getTicketProvider(i):o==="pull_request"?this.providers.getRepoProvider(i):null;if(!a)throw new Error(`Unsupported subjectType for provider_action: ${o}`);switch(t){case"get_subject":return a.get(s);case"get_comments":return a.getComments(s);case"post_comment":return await a.postComment(s,vt(n,"body")),{posted:!0};case"update_status":return await a.updateStatus(s,vt(n,"status")),{status:vt(n,"status")};case"get_content":throw new Error(`Provider action 'get_content' is not valid for subject type '${o}'`);default:{let u=t;throw new Error(`Unknown provider action: ${u}`)}}}async executeExtendedProviderAction(e,t,n,o){let i=t.extendedAction,s=o.subjectType==="documentation"?this.providers.getDocumentationProvider(i.providerId):o.subjectType==="ticket"?this.providers.getTicketProvider(i.providerId):o.subjectType==="pull_request"?this.providers.getRepoProvider(i.providerId):null;if(!s)throw new Error(`Unsupported subjectType for provider_action: ${o.subjectType}`);if(!oc(s))throw new Error(`Provider instance '${i.providerId}' does not support extended actions. Available: none`);let a=await s.listExtendedActions(),u=a.find(m=>m.actionId===i.actionId);if(!u)throw new Error(`Provider '${i.providerId}' has no extended action '${i.actionId}'. Available: ${qt(a)}`);let c=Dt(i.params??{},xt(e))??{};pn(u,c);let p=await s.executeExtendedAction(i.actionId,{...c,subjectId:o.subjectId});return this.finishExecution(e,n,t.id,p)}async executeShellStep(e,t,n){let o=Ft(t.command,xt(e)),i=e.worktreePath??process.cwd();try{let s=await ah(o,{cwd:i,windowsHide:!0});return this.finishExecution(e,n,t.id,{exitCode:0,stdout:String(s.stdout??""),stderr:String(s.stderr??"")})}catch(s){let a=s,u=a.stderr??"",c=a.stdout??"",p=typeof a.code=="number"?a.code:Number.parseInt(String(a.code??"1"),10)||1;throw new Error(`shell command failed (exit ${p}, cwd=${i}): ${u||c||a.message||o}`)}}async executeExtractStep(e,t,n,o){let i=Ft(n.source,xt(e)),s=Vc({source:i,path:n.path,pattern:n.pattern});if(s.kind==="match")return{outcome:"completed",job:await this.finishExecution(e,o,n.id,s.value)};switch(n.onNoMatch){case"fail":throw new Error(`Extract '${n.id}' did not match`);case"empty":return{outcome:"completed",job:await this.finishExecution(e,o,n.id,"")};case"ask_human":return{outcome:"paused",job:await this.pauseForExtract(e,t,n,o,s.sourceValue)};default:{let a=n.onNoMatch;throw new Error(`Unknown onNoMatch action: ${String(a)}`)}}}async pauseForExtract(e,t,n,o,i){let s=new Date().toISOString(),a=n.pattern?.trim()||void 0,u={extractNoMatch:!0,sourceValue:i,...a?{pattern:a}:{}},c={sourceValue:i,...a?{pattern:a}:{}},p=Q(e.stepHistory,o,b=>({...b,status:"pending",output:u})),m=await this.persistJob({...e,status:"waiting_for_human",currentStepId:n.id,currentStepExecutionId:o,stepHistory:p,updatedAt:s});return this.emit({type:"waiting_for_human",jobId:m.id,stepDefinitionId:n.id,interaction:"confirmation",data:c,questions:[`Extract '${n.id}' did not match. Provide a value, continue with empty, or cancel?`],timestamp:s}),t.notificationPolicy.triggers.includes("on_needs_input")&&await this.notifications.send({title:`Input needed: ${t.name}`,body:`Job ${m.id} needs a value for extract step '${n.id}'`,jobId:m.id}),m}async pauseForInteraction(e,t,n,o){let i=new Date().toISOString(),s=uh(t,n.id),a=s!=null?e.context[s]:void 0,u=Q(e.stepHistory,o,b=>({...b,status:"pending"})),c=await this.persistJob({...e,status:"waiting_for_human",currentStepId:n.id,currentStepExecutionId:o,stepHistory:u,updatedAt:i}),p=Gc(n.interaction,a);return this.emit({type:"waiting_for_human",jobId:c.id,stepDefinitionId:n.id,interaction:n.interaction,data:a,questions:p,timestamp:i}),t.notificationPolicy.triggers.includes("on_needs_input")&&n.notify!==!1&&await this.notifications.send({title:`Input needed: ${t.name}`,body:`Job ${c.id} is waiting for human input on step '${n.id}'`,jobId:c.id}),c}async finishExecution(e,t,n,o,i={}){let s=new Date().toISOString(),a=Q(e.stepHistory,t,c=>({...c,status:"completed",completedAt:s,output:o})),u=await this.persistJob({...e,...i,context:{...e.context,[n]:o},stepHistory:a,updatedAt:s});return this.emit({type:"step_completed",jobId:u.id,stepDefinitionId:n,timestamp:s}),u}async failExecution(e,t,n,o,i){return this.failJob(e,t,n,o,new Error(i))}async completeJob(e,t){let n=new Date().toISOString(),o=await this.persistJob({...e,status:"completed",currentStepId:void 0,currentStepExecutionId:void 0,completedAt:n,updatedAt:n});return o.status==="cancelled"||(this.emit({type:"job_completed",jobId:o.id,timestamp:n}),await this.onBatchMemberTerminal(o.id),!o.batchId&&t.notificationPolicy.triggers.includes("on_complete")&&await this.notifications.send({title:`Job completed: ${t.name}`,body:`Job ${o.id} completed successfully`,jobId:o.id})),o}async failJob(e,t,n,o,i){let s=i instanceof Error?i.message:String(i),a=new Date().toISOString(),u=Q(e.stepHistory,n,p=>({...p,status:"failed",completedAt:a,error:s})),c=await this.persistJob({...e,status:"failed",currentStepId:o,currentStepExecutionId:n,stepHistory:u,completedAt:a,updatedAt:a});return this.emit({type:"step_failed",jobId:c.id,stepDefinitionId:o,error:s,timestamp:a}),c.status==="cancelled"?(await this.onBatchMemberTerminal(c.id),c):(this.emit({type:"job_failed",jobId:c.id,error:s,timestamp:a}),await this.onBatchMemberTerminal(c.id),!c.batchId&&t.notificationPolicy.triggers.includes("on_fail")&&await this.notifications.send({title:`Job failed: ${t.name}`,body:`Job ${c.id} failed on step '${o}': ${s}`,jobId:c.id}),c)}async resolveSubjectContext(e,t){if(e.appliesTo==="none")return;let n=dh(e.appliesTo);if(!t)throw new Error(`Workflow '${e.id}' applies to '${n}' but no subjectId was provided`);if(n==="ticket")return{mode:"single",subject:{subjectType:"ticket",...await this.getTicketById(t)}};if(n==="pull_request")return{mode:"single",subject:{subjectType:"pull_request",...await this.getPullRequestById(t)}};if(n==="documentation")return{mode:"single",subject:{subjectType:"documentation",...await this.getDocumentationById(t)}};throw new Error(`Unsupported subjectType for workflow subject resolution: ${n}`)}async workflowForJob(e){return e.workflowSnapshot?e.workflowSnapshot:(this.logger.warn(`Job ${e.id} has no workflowSnapshot; falling back to live WorkflowDefinition ${e.workflowId}`),this.requireWorkflow(e.workflowId))}async requireWorkflow(e){let t=await this.workflows.get(e);if(!t)throw new y(`Workflow not found: ${e}`);return t}emitRetryLaunch(e,t){let n=new Date().toISOString();this.emit({type:"job_started",jobId:e,timestamp:n}),this.emit({type:"job_retried",jobId:e,retryOf:t,timestamp:n})}inputValuesFromContext(e,t){let n={};for(let o of t.inputSchema)Object.prototype.hasOwnProperty.call(e,o.name)&&(n[o.name]=e[o.name]);return n}async persistCancelled(e){let t=new Date().toISOString();return this.persistJob({...e,status:"cancelled",completedAt:e.completedAt??t,updatedAt:t})}async stopIfCancelled(e){return!this.cancellation.isCancellationRequested(e.id)&&e.status!=="cancelled"&&(await this.jobs.get(e.id))?.status!=="cancelled"?null:(this.cancellation.clear(e.id),e.status==="cancelled"?e:this.persistCancelled(e))}async persistJob(e){let t=await this.jobs.get(e.id),n=this.cancellation.isCancellationRequested(e.id)||t?.status==="cancelled"||e.status==="cancelled",o=n?"cancelled":e.status,i=n?t?.completedAt??e.completedAt??e.updatedAt:e.completedAt,s=await this.jobs.update(e.id,{status:o,context:e.context,currentStepId:e.currentStepId,currentStepExecutionId:e.currentStepExecutionId,stepHistory:e.stepHistory,worktreePath:e.worktreePath,branch:e.branch,updatedAt:e.updatedAt,completedAt:i});if(!s)throw new Error(`Failed to persist job ${e.id}`);return t?.status!=="cancelled"&&s.status==="cancelled"&&this.emit({type:"job_cancelled",jobId:s.id,timestamp:s.updatedAt}),s}emit(e){this.events.emit(e)}async getTicketById(e){return Ii(this.providers.ticketInstanceIds(),t=>this.providers.getTicketProvider(t).get(e),`Ticket not found: ${e}`)}async getPullRequestById(e){return Ii(this.providers.repoInstanceIds(),t=>this.providers.getRepoProvider(t).get(e),`Pull request not found: ${e}`)}async getDocumentationById(e){return Ii(this.providers.documentationInstanceIds(),t=>this.providers.getDocumentationProvider(t).get(e),`Documentation page not found: ${e}`)}};we=ji=th([nh(),de(0,pe(O)),de(1,pe(z)),de(2,pe(se)),de(3,pe(ie)),de(4,pe(ye)),de(5,pe(F)),de(6,pe(er)),de(7,pe(ae)),de(8,pe(ce)),de(9,pe(Fe)),de(10,pe(P)),de(11,pe(St)),rh("design:paramtypes",[O,z,se,ie,ye,F,Object,ae,ce,Fe,Object,St])],we)});import{Module as fh}from"@nestjs/common";var ph,Jt,_i=l(()=>{"use strict";mr();Cn();On();Wc();Ln();bi();ph=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Jt=class{};Jt=ph([fh({imports:[Re,st,at,qn],providers:[St,we],exports:[we]})],Jt)});import{Catch as hh}from"@nestjs/common";var mh,Un,du=l(()=>{"use strict";R();mh=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Un=class{catch(e,t){t.switchToHttp().getResponse().status(e.httpStatus).json({error:e.message})}};Un=mh([hh(wt)],Un)});var v,ne=l(()=>{"use strict";R();v=class{schema;constructor(e){this.schema=e}transform(e){let t=this.schema.safeParse(e);if(!t.success){let n=t.error.issues.map(o=>`${o.path.join(".")||"(root)"}: ${o.message}`).join("; ");throw new h(`Validation failed: ${n}`)}return t.data}}});import{randomUUID as yh}from"node:crypto";function gh(){return yh()}function Mn(r){let e=r.id??gh(),t=ca(r.steps),n=pu(r.steps,t);return{...r,id:e,steps:n}}function pu(r,e){return r.map(t=>{let n=t.id;return n||(n=ia(t.name,e),e.add(n)),t.type==="loop"?{...t,id:n,steps:pu(t.steps,e)}:{...t,id:n}})}var Ei=l(()=>{"use strict";C()});function fu(r,e,t){if(!r)throw new y(`Workflow not found: ${e}`);if(r.appliesTo==="none")throw new h(`Cannot bind a View to workflow '${e}' because appliesTo is 'none'`);if(!ja(r.appliesTo,t))throw new h(`subjectType '${t}' is not included in workflow '${e}' appliesTo`);return r}function mu(r,e){if(!r)throw new y(`Workflow not found: ${e}`);if(r.appliesTo!=="none")throw new h(`WorkflowShortcut requires appliesTo 'none', got '${String(r.appliesTo)}'`);if(r.subjectHandling!=="per-subject")throw new h(`WorkflowShortcut requires subjectHandling 'per-subject', got '${r.subjectHandling}'`);return r}function Wn(r){if(r.appliesTo==="none"&&r.subjectHandling==="collection")throw new h("Workflows with appliesTo 'none' must use subjectHandling 'per-subject'")}var Sr=l(()=>{"use strict";C();R()});function hu(r){return r.issues.map(e=>`${e.path.join(".")||"(root)"}: ${e.message}`).join("; ")}async function Hn(r,e){let t=tt.safeParse(e);if(!t.success)throw new h(`Validation failed: ${hu(t.error)}`);let n=Mn(t.data),o=ht.safeParse(n);if(!o.success)throw new h(`Validation failed: ${hu(o.error)}`);return Wn(o.data),r.create(o.data)}var Pi=l(()=>{"use strict";C();R();Sr();Ei()});import{Body as yu,Controller as wh,Delete as bh,Get as gu,HttpCode as Sh,Inject as xh,Param as Ri,Patch as vh,Post as Ih,Query as jh}from"@nestjs/common";var Lt,U,It,Ne,wu=l(()=>{"use strict";C();mt();R();ne();Ei();Pi();Sr();Lt=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},U=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},It=function(r,e){return function(t,n){e(t,n,r)}},Ne=class{workflows;constructor(e){this.workflows=e}async list(e){if(e!=null&&e!==""&&e!=="per-subject"&&e!=="collection")throw new h(`Invalid subjectHandling filter: ${e}`);return this.workflows.list(e?{subjectHandling:e}:{})}async get(e){let t=await this.workflows.get(e);if(!t)throw new y(`Workflow not found: ${e}`);return t}async create(e){return Hn(this.workflows,e)}async update(e,t){let n=Mn({...t,id:e}),o=ht.safeParse(n);if(!o.success){let u=o.error.issues.map(c=>`${c.path.join(".")||"(root)"}: ${c.message}`).join("; ");throw new h(`Validation failed: ${u}`)}Wn(o.data);let{id:i,...s}=o.data,a=await this.workflows.update(e,s);if(!a)throw new y(`Workflow not found: ${e}`);return a}async remove(e){if(!await this.workflows.get(e))throw new y(`Workflow not found: ${e}`);if(!await this.workflows.delete(e))throw new y(`Workflow not found: ${e}`)}};Lt([gu(),It(0,jh("subjectHandling")),U("design:type",Function),U("design:paramtypes",[String]),U("design:returntype",Promise)],Ne.prototype,"list",null);Lt([gu(":id"),It(0,Ri("id")),U("design:type",Function),U("design:paramtypes",[String]),U("design:returntype",Promise)],Ne.prototype,"get",null);Lt([Ih(),It(0,yu()),U("design:type",Function),U("design:paramtypes",[Object]),U("design:returntype",Promise)],Ne.prototype,"create",null);Lt([vh(":id"),It(0,Ri("id")),It(1,yu(new v(tt))),U("design:type",Function),U("design:paramtypes",[String,Object]),U("design:returntype",Promise)],Ne.prototype,"update",null);Lt([bh(":id"),Sh(204),It(0,Ri("id")),U("design:type",Function),U("design:paramtypes",[String]),U("design:returntype",Promise)],Ne.prototype,"remove",null);Ne=Lt([wh("workflows"),It(0,xh(O)),U("design:paramtypes",[O])],Ne)});function _h(r){return Su(r.workflowDefinition.steps,"steps")}function bu(r){let e=_h(r);if(e.length>0)throw new Error(`Workflow library entry '${r.id}' is not portable: ${e.join(", ")}`)}function Su(r,e){let t=[];return r.forEach((n,o)=>{let i=`${e}[${o}]`;n.type==="provider_action"&&(n.target&&t.push(`${i}.target`),n.extendedAction&&t.push(`${i}.extendedAction`)),n.type==="loop"&&t.push(...Su(n.steps,`${i}.steps`))}),t}var xu=l(()=>{"use strict"});function vu(){return structuredClone(ki)}function Iu(r){let e=ki.find(t=>t.id===r);return e?structuredClone(e):void 0}var Eh,Ph,ki,ju=l(()=>{"use strict";xu();Eh={id:"clarify-then-summarize",source:"example",name:"Clarify then summarize",description:"Asks clarifying questions in a loop until none remain, then summarizes the answers.",workflowDefinition:{name:"Clarify then summarize",description:"Asks clarifying questions in a loop until none remain, then summarizes the answers.",appliesTo:"none",subjectHandling:"per-subject",inputSchema:[{name:"topic",label:"Topic",type:"string",required:!0}],steps:[{type:"loop",name:"Clarify",steps:[{type:"agent",name:"Draft questions",objective:"Draft clarifying questions about {{topic}}. If you have no remaining questions, return an empty list.",outputFormat:"questionnaire"},{type:"interaction",name:"Collect answers",interaction:"questionnaire"}],until:{type:"field_empty",stepId:"draft-questions",field:"questions"},maxIterations:5,onMaxIterations:{action:"continue"}},{type:"agent",name:"Summarize",objective:"Produce a final summary for {{topic}} using these answers: {{collect-answers}}",outputFormat:"free_text"}],notificationPolicy:{triggers:["on_needs_input","on_complete","on_fail"]}}},Ph={id:"pr-review",source:"example",name:"PR Review",description:"Reviews a pull request for acceptance criteria, code quality, and test coverage.",workflowDefinition:{name:"PR Review",description:"Reviews a pull request for acceptance criteria, code quality, and test coverage.",appliesTo:"pull_request",subjectHandling:"per-subject",inputSchema:[{name:"repoPath",label:"Repository path",type:"localRepository",required:!0},{name:"ticketDescription",label:"Related ticket description (optional)",type:"string",required:!1}],steps:[{type:"git",name:"Prepare review worktree",operation:"create_worktree",params:{repoPath:"{{repoPath}}",baseBranch:"{{subject.sourceBranch}}",branchName:"review/{{subject.id}}"}},{type:"agent",name:"Build requirements checklist",objective:`Ticket: {{ticketDescription}}
|
|
24
24
|
PR title: {{subject.title}}
|
|
25
25
|
PR description: {{subject.description}}
|
|
26
26
|
|
|
@@ -30,5 +30,5 @@ Checklist: {{build-requirements-checklist}}`,outputFormat:"free_text"},{type:"sh
|
|
|
30
30
|
{{run-relevant-tests}}`,outputFormat:"free_text"},{type:"agent",name:"Generate combined review report",objective:`Combine into one markdown report: Summary, Acceptance Criteria, Findings by Role, Tests Run, Suggested PR Comments, Verdict (APPROVE/COMMENT/REQUEST_CHANGES).
|
|
31
31
|
Acceptance: {{acceptance-criteria-review}}
|
|
32
32
|
Code quality: {{code-quality-review}}
|
|
33
|
-
Testing: {{testing-review}}`,outputFormat:"free_text"}],notificationPolicy:{triggers:["on_fail","on_complete"]}}},Pi=[lh,ph];for(let r of Pi)uu(r)});import{Controller as dh,Get as fh,Inject as mh,Param as hh,Post as yh}from"@nestjs/common";var Ri,xt,hu,Jt,yu=l(()=>{"use strict";ft();E();mu();Ii();Ri=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},xt=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},hu=function(r,e){return function(t,n){e(t,n,r)}},Jt=class{workflows;constructor(e){this.workflows=e}list(){return du()}async add(e){let t=fu(e);if(!t)throw new y(`Workflow library entry not found: ${e}`);let n=structuredClone(t.workflowDefinition);return delete n.id,Hn(this.workflows,n)}};Ri([fh(),xt("design:type",Function),xt("design:paramtypes",[]),xt("design:returntype",Array)],Jt.prototype,"list",null);Ri([yh(":id/add"),hu(0,hh("id")),xt("design:type",Function),xt("design:paramtypes",[String]),xt("design:returntype",Promise)],Jt.prototype,"add",null);Jt=Ri([dh("workflow-library"),hu(0,mh(O)),xt("design:paramtypes",[O])],Jt)});import{Body as ki,Controller as wh,Delete as gh,Get as Ai,HttpCode as bh,Inject as Ei,Param as Vn,Patch as wu,Post as Sh,Query as xh}from"@nestjs/common";var ut,T,be,Se,gu=l(()=>{"use strict";C();qr();ft();E();ne();Sr();$t();hi();ut=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},T=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},be=function(r,e){return function(t,n){e(t,n,r)}},Se=class{views;workflows;providers;constructor(e,t,n){this.views=e,this.workflows=t,this.providers=n}async list(e){if(e!=null&&e!==""){let t=re.safeParse(e);if(!t.success)throw new h(`Invalid subjectType filter: ${e}`);return this.views.list({subjectType:t.data})}return this.views.list({})}async reorder(e){let t=[];for(let i of e.viewIds){let s=await this.views.get(i);if(!s)throw new h(`Unknown view id in reorder: ${i}`);t.push(s)}if(new Set(t.map(i=>i.subjectType)).size!==1)throw new h("All viewIds in a reorder request must share the same subjectType");return await this.views.reorder(e.viewIds)}async listSubjects(e){return Bn(e,this.views,this.providers)}async get(e){let t=await this.views.get(e);if(!t)throw new y(`SubjectView not found: ${e}`);return t}async create(e){return await this.assertBinding(e.workflowId,e.subjectType),this.views.create(e)}async update(e,t){let n=await this.views.get(e);if(!n)throw new y(`SubjectView not found: ${e}`);await this.assertBinding(t.workflowId??n.workflowId,t.subjectType??n.subjectType);let o=await this.views.update(e,t);if(!o)throw new y(`SubjectView not found: ${e}`);return o}async remove(e){if(!await this.views.delete(e))throw new y(`SubjectView not found: ${e}`)}async assertBinding(e,t){let n=await this.workflows.get(e);nu(n,e,t)}};ut([Ai(),be(0,xh("subjectType")),T("design:type",Function),T("design:paramtypes",[String]),T("design:returntype",Promise)],Se.prototype,"list",null);ut([wu("reorder"),be(0,ki(new v(Mr))),T("design:type",Function),T("design:paramtypes",[Object]),T("design:returntype",Promise)],Se.prototype,"reorder",null);ut([Ai(":id/subjects"),be(0,Vn("id")),T("design:type",Function),T("design:paramtypes",[String]),T("design:returntype",Promise)],Se.prototype,"listSubjects",null);ut([Ai(":id"),be(0,Vn("id")),T("design:type",Function),T("design:paramtypes",[String]),T("design:returntype",Promise)],Se.prototype,"get",null);ut([Sh(),be(0,ki(new v(Lr))),T("design:type",Function),T("design:paramtypes",[Object]),T("design:returntype",Promise)],Se.prototype,"create",null);ut([wu(":id"),be(0,Vn("id")),be(1,ki(new v(Ur))),T("design:type",Function),T("design:paramtypes",[String,Object]),T("design:returntype",Promise)],Se.prototype,"update",null);ut([gh(":id"),bh(204),be(0,Vn("id")),T("design:type",Function),T("design:paramtypes",[String]),T("design:returntype",Promise)],Se.prototype,"remove",null);Se=ut([wh("views"),be(0,Ei(ie)),be(1,Ei(O)),be(2,Ei(F)),T("design:paramtypes",[ie,O,F])],Se)});import{Body as Ci,Controller as vh,Delete as jh,Get as Su,HttpCode as Ih,Inject as bu,Param as Ti,Patch as xu,Post as _h}from"@nestjs/common";var vt,q,lt,Ee,vu=l(()=>{"use strict";C();Jo();ft();E();ne();Sr();vt=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},q=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},lt=function(r,e){return function(t,n){e(t,n,r)}},Ee=class{shortcuts;workflows;constructor(e,t){this.shortcuts=e,this.workflows=t}async list(){return this.shortcuts.list()}async reorder(e){for(let t of e.shortcutIds)if(!await this.shortcuts.get(t))throw new h(`Unknown shortcut id in reorder: ${t}`);return this.shortcuts.reorder(e.shortcutIds)}async get(e){let t=await this.shortcuts.get(e);if(!t)throw new y(`WorkflowShortcut not found: ${e}`);return t}async create(e){return await this.assertBinding(e.workflowId),this.shortcuts.create(e)}async update(e,t){let n=await this.shortcuts.get(e);if(!n)throw new y(`WorkflowShortcut not found: ${e}`);await this.assertBinding(t.workflowId??n.workflowId);let o=await this.shortcuts.update(e,t);if(!o)throw new y(`WorkflowShortcut not found: ${e}`);return o}async remove(e){if(!await this.shortcuts.delete(e))throw new y(`WorkflowShortcut not found: ${e}`)}async assertBinding(e){let t=await this.workflows.get(e);ou(t,e)}};vt([Su(),q("design:type",Function),q("design:paramtypes",[]),q("design:returntype",Promise)],Ee.prototype,"list",null);vt([xu("reorder"),lt(0,Ci(new v(en))),q("design:type",Function),q("design:paramtypes",[Object]),q("design:returntype",Promise)],Ee.prototype,"reorder",null);vt([Su(":id"),lt(0,Ti("id")),q("design:type",Function),q("design:paramtypes",[String]),q("design:returntype",Promise)],Ee.prototype,"get",null);vt([_h(),lt(0,Ci(new v(Yr))),q("design:type",Function),q("design:paramtypes",[Object]),q("design:returntype",Promise)],Ee.prototype,"create",null);vt([xu(":id"),lt(0,Ti("id")),lt(1,Ci(new v(Zr))),q("design:type",Function),q("design:paramtypes",[String,Object]),q("design:returntype",Promise)],Ee.prototype,"update",null);vt([jh(":id"),Ih(204),lt(0,Ti("id")),q("design:type",Function),q("design:paramtypes",[String]),q("design:returntype",Promise)],Ee.prototype,"remove",null);Ee=vt([vh("workflow-shortcuts"),lt(0,bu($e)),lt(1,bu(O)),q("design:paramtypes",[$e,O])],Ee)});function Kn(r,e,t=50){let n=r!=null&&r!==""?Number(r):t,o=e!=null&&e!==""?Number(e):0;return!Number.isFinite(n)||n<1?{limit:t,offset:Math.max(0,o||0)}:!Number.isFinite(o)||o<0?{limit:n,offset:0}:{limit:Math.floor(n),offset:Math.floor(o)}}function Gn(r,e,t){return r.slice(t,t+e)}var Oi=l(()=>{"use strict"});import{z as Q}from"zod";var zn,Qn,Xn,Yn,$i=l(()=>{"use strict";zn=Q.object({workflowId:Q.string().min(1),subjectId:Q.string().min(1).optional(),inputValues:Q.record(Q.string(),Q.unknown())}),Qn=Q.object({response:Q.unknown()}),Xn=Q.object({workflowId:Q.string().min(1),subjectIds:Q.array(Q.string().min(1))}),Yn=Q.object({jobIds:Q.array(Q.string().min(1)).min(1)})});import{Body as Zn,Controller as Ph,Get as Iu,HttpCode as _u,Inject as ju,Param as xr,Post as jt,Query as Fe}from"@nestjs/common";import"zod";function qi(r,e){if(!(r==null||r==="")){if(r==="true")return!0;if(r==="false")return!1;throw new h(`Invalid ${e} filter: ${r}`)}}var ke,k,$,Rh,oe,Pu=l(()=>{"use strict";Ln();lr();E();ne();Oi();$i();ke=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},k=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},$=function(r,e){return function(t,n){e(t,n,r)}},Rh=["pending","planning","waiting_for_human","waiting_for_children","implementing","testing","completed","failed","cancelled"];oe=class{jobs;runner;constructor(e,t){this.jobs=e,this.runner=t}async list(e,t,n,o,i,s,a,u,c){if(t!=null&&t!==""&&!Rh.includes(t))throw new h(`Invalid status filter: ${t}`);let d=qi(i,"topLevelOnly"),m=qi(s,"terminal"),b=qi(a,"liveWorktree"),{limit:S,offset:I}=Kn(u,c),N=await this.jobs.list({...e?{workflowId:e}:{},...t?{status:t}:{},...n?{batchId:n}:{},...o?{parentJobId:o}:{},...d===!0?{topLevelOnly:!0}:{},...m!==void 0?{terminal:m}:{},...b===!0?{liveWorktree:!0}:{}});return Gn(N,S,I)}async latestBySubject(e){return this.jobs.latestBySubject(e.workflowId,e.subjectIds)}async deleteWorktrees(e){return this.runner.deleteWorktrees(e.jobIds)}async get(e){let t=await this.jobs.get(e);if(!t)throw new y(`Job not found: ${e}`);return t}async create(e){return this.runner.start({workflowId:e.workflowId,...e.subjectId?{subjectId:e.subjectId}:{},inputValues:e.inputValues})}async resume(e,t){return this.runner.resume(e,t.response)}async retry(e){return this.runner.retryFailedJob(e)}async retryStep(e){return this.runner.retryFailedStep(e)}async cancel(e){return this.runner.cancelJob(e)}};ke([Iu(),$(0,Fe("workflowId")),$(1,Fe("status")),$(2,Fe("batchId")),$(3,Fe("parentJobId")),$(4,Fe("topLevelOnly")),$(5,Fe("terminal")),$(6,Fe("liveWorktree")),$(7,Fe("limit")),$(8,Fe("offset")),k("design:type",Function),k("design:paramtypes",[String,String,String,String,String,String,String,String,String]),k("design:returntype",Promise)],oe.prototype,"list",null);ke([jt("latest-by-subject"),_u(200),$(0,Zn(new v(Xn))),k("design:type",Function),k("design:paramtypes",[Object]),k("design:returntype",Promise)],oe.prototype,"latestBySubject",null);ke([jt("delete-worktrees"),_u(200),$(0,Zn(new v(Yn))),k("design:type",Function),k("design:paramtypes",[Object]),k("design:returntype",Promise)],oe.prototype,"deleteWorktrees",null);ke([Iu(":id"),$(0,xr("id")),k("design:type",Function),k("design:paramtypes",[String]),k("design:returntype",Promise)],oe.prototype,"get",null);ke([jt(),$(0,Zn(new v(zn))),k("design:type",Function),k("design:paramtypes",[Object]),k("design:returntype",Promise)],oe.prototype,"create",null);ke([jt(":id/resume"),$(0,xr("id")),$(1,Zn(new v(Qn))),k("design:type",Function),k("design:paramtypes",[String,Object]),k("design:returntype",Promise)],oe.prototype,"resume",null);ke([jt(":id/retry"),$(0,xr("id")),k("design:type",Function),k("design:paramtypes",[String]),k("design:returntype",Promise)],oe.prototype,"retry",null);ke([jt(":id/retry-step"),$(0,xr("id")),k("design:type",Function),k("design:paramtypes",[String]),k("design:returntype",Promise)],oe.prototype,"retryStep",null);ke([jt(":id/cancel"),$(0,xr("id")),k("design:type",Function),k("design:paramtypes",[String]),k("design:returntype",Promise)],oe.prototype,"cancel",null);oe=ke([Ph("jobs"),$(0,ju(z)),$(1,ju(ge)),k("design:paramtypes",[z,ge])],oe)});import{z as te}from"zod";var eo,to,Bi=l(()=>{"use strict";C();eo=te.discriminatedUnion("mode",[te.object({mode:te.literal("view"),viewId:te.string().min(1)}),te.object({mode:te.literal("manual"),subjectType:re,subjectIds:te.array(te.string().min(1))})]),to=te.object({workflowId:te.string().min(1),selection:eo,triggeredBy:te.enum(["schedule","view_bulk","multiselect"]),notificationOverride:pr.optional(),inputValues:te.record(te.string(),te.unknown())})});import{Body as Eh,Controller as kh,Get as Ni,Inject as Di,Param as Ji,Post as Ru,Query as Fi}from"@nestjs/common";import"zod";var Lt,M,Ae,Ne,Eu=l(()=>{"use strict";Ln();Br();lr();E();ne();Oi();Bi();Lt=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},M=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},Ae=function(r,e){return function(t,n){e(t,n,r)}},Ne=class{batches;jobs;runner;constructor(e,t,n){this.batches=e,this.jobs=t,this.runner=n}async list(e,t,n){let{limit:o,offset:i}=Kn(t,n),s=await this.batches.list(e?{workflowId:e}:{});return Gn(s,o,i)}async get(e){let t=await this.batches.get(e);if(!t)throw new y(`JobBatch not found: ${e}`);return t}async listJobs(e){if(!await this.batches.get(e))throw new y(`JobBatch not found: ${e}`);return this.jobs.list({batchId:e})}async launch(e){let t=await this.runner.launch({workflowId:e.workflowId,selection:e.selection,triggeredBy:e.triggeredBy,...e.notificationOverride?{notificationOverride:e.notificationOverride}:{},inputValues:e.inputValues});return"resolvedSubjects"in t&&"jobIds"in t?{kind:"batch",batch:t}:{kind:"job",job:t}}async cancel(e){return this.runner.cancelBatch(e)}};Lt([Ni(),Ae(0,Fi("workflowId")),Ae(1,Fi("limit")),Ae(2,Fi("offset")),M("design:type",Function),M("design:paramtypes",[String,String,String]),M("design:returntype",Promise)],Ne.prototype,"list",null);Lt([Ni(":id"),Ae(0,Ji("id")),M("design:type",Function),M("design:paramtypes",[String]),M("design:returntype",Promise)],Ne.prototype,"get",null);Lt([Ni(":id/jobs"),Ae(0,Ji("id")),M("design:type",Function),M("design:paramtypes",[String]),M("design:returntype",Promise)],Ne.prototype,"listJobs",null);Lt([Ru(),Ae(0,Eh(new v(to))),M("design:type",Function),M("design:paramtypes",[Object]),M("design:returntype",Promise)],Ne.prototype,"launch",null);Lt([Ru(":id/cancel"),Ae(0,Ji("id")),M("design:type",Function),M("design:paramtypes",[String]),M("design:returntype",Promise)],Ne.prototype,"cancel",null);Ne=Lt([kh("batches"),Ae(0,Di(se)),Ae(1,Di(z)),Ae(2,Di(ge)),M("design:paramtypes",[se,z,ge])],Ne)});import{Body as ku,Controller as Ah,Delete as Ch,Get as Au,HttpCode as Th,Inject as Oh,Param as Li,Patch as $h,Post as qh,Query as Bh}from"@nestjs/common";var Ut,W,It,Je,Cu=l(()=>{"use strict";C();Fo();E();ne();Ut=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},W=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},It=function(r,e){return function(t,n){e(t,n,r)}},Je=class{schedules;constructor(e){this.schedules=e}async list(e){if(e==null||e==="")return this.schedules.list();if(e!=="true"&&e!=="false")throw new h(`Invalid enabled filter: ${e}`);return this.schedules.list({enabled:e==="true"})}async get(e){let t=await this.schedules.get(e);if(!t)throw new y(`Schedule not found: ${e}`);return t}async create(e){return this.schedules.create(e)}async update(e,t){let n=await this.schedules.update(e,t);if(!n)throw new y(`Schedule not found: ${e}`);return n}async remove(e){if(!await this.schedules.delete(e))throw new y(`Schedule not found: ${e}`)}};Ut([Au(),It(0,Bh("enabled")),W("design:type",Function),W("design:paramtypes",[String]),W("design:returntype",Promise)],Je.prototype,"list",null);Ut([Au(":id"),It(0,Li("id")),W("design:type",Function),W("design:paramtypes",[String]),W("design:returntype",Promise)],Je.prototype,"get",null);Ut([qh(),It(0,ku(new v(Ct))),W("design:type",Function),W("design:paramtypes",[Object]),W("design:returntype",Promise)],Je.prototype,"create",null);Ut([$h(":id"),It(0,Li("id")),It(1,ku(new v(Ct.partial().omit({id:!0})))),W("design:type",Function),W("design:paramtypes",[String,Object]),W("design:returntype",Promise)],Je.prototype,"update",null);Ut([Ch(":id"),Th(204),It(0,Li("id")),W("design:type",Function),W("design:paramtypes",[String]),W("design:returntype",Promise)],Je.prototype,"remove",null);Je=Ut([Ah("schedules"),It(0,Oh(Oe)),W("design:paramtypes",[Oe])],Je)});import{Controller as Dh,Inject as Fh,Query as Tu,Sse as Nh}from"@nestjs/common";import{Observable as $u}from"rxjs";var Ou,ro,Ui,vr,qu=l(()=>{"use strict";Tn();Ou=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},ro=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},Ui=function(r,e){return function(t,n){e(t,n,r)}},vr=class{events;constructor(e){this.events=e}stream(e,t){return new $u(n=>{let o=this.events.subscribe(i=>{let s=i;e!=null&&e!==""&&(!("jobId"in s)||s.jobId!==e)||t!=null&&t!==""&&(!("batchId"in s)||s.batchId!==t)||n.next({data:s})});return()=>{o()}})}};Ou([Nh(),Ui(0,Tu("jobId")),Ui(1,Tu("batchId")),ro("design:type",Function),ro("design:paramtypes",[String,String]),ro("design:returntype",$u)],vr.prototype,"stream",null);vr=Ou([Dh("events"),Ui(0,Fh(ye)),ro("design:paramtypes",[ye])],vr)});import{extendZodWithOpenApi as Jh}from"@asteasolutions/zod-to-openapi";import{z as Lh}from"zod";var Bu=l(()=>{"use strict";Jh(Lh)});import{z as Du}from"zod";var no,Mi=l(()=>{"use strict";no=Du.object({value:Du.string().min(1)})});import{z as _t}from"zod";var Uh,Fu,Nu=l(()=>{"use strict";Uh=_t.object({name:_t.string().min(1),path:_t.string().min(1),isDirectory:_t.boolean()}),Fu=_t.object({path:_t.string().min(1),entries:_t.array(Uh)})});import{z as p}from"zod";function cy(r){let e=p.toJSONSchema(r),{$schema:t,...n}=e;return n}function Lu(r){let e=(t,n)=>r.registerComponent("schemas",t,cy(n)).ref;return{WorkflowDefinition:e("WorkflowDefinition",mt),WorkflowDefinitionInput:e("WorkflowDefinitionInput",et),UpdateWorkflowBody:e("UpdateWorkflowBody",ey),SubjectView:e("SubjectView",Jr),CreateSubjectViewBody:e("CreateSubjectViewBody",Lr),ReorderViewsBody:e("ReorderViewsBody",Mr),UpdateViewBody:e("UpdateViewBody",ry),WorkflowShortcut:e("WorkflowShortcut",Xr),CreateWorkflowShortcutBody:e("CreateWorkflowShortcutBody",Yr),UpdateWorkflowShortcutBody:e("UpdateWorkflowShortcutBody",Zr),ReorderShortcutsBody:e("ReorderShortcutsBody",en),Schedule:e("Schedule",Ct),UpdateScheduleBody:e("UpdateScheduleBody",ny),EngineSettings:e("EngineSettings",rn),UpdateSettingsBody:e("UpdateSettingsBody",iy),SettingsPatchResponse:e("SettingsPatchResponse",ay),ProviderInstanceConfig:e("ProviderInstanceConfig",tn),CreateProviderInstanceBody:e("CreateProviderInstanceBody",on),UpdateProviderInstanceBody:e("UpdateProviderInstanceBody",sn),ProviderInstanceMutationResponse:e("ProviderInstanceMutationResponse",sy),SetSecretBody:e("SetSecretBody",no),CreateJobBody:e("CreateJobBody",zn),ResumeJobBody:e("ResumeJobBody",Qn),LatestBySubjectBody:e("LatestBySubjectBody",Xn),LatestBySubjectResponse:e("LatestBySubjectResponse",oy),LaunchBody:e("LaunchBody",to),Job:e("Job",Wi),JobBatch:e("JobBatch",Ju),LaunchResponse:e("LaunchResponse",zh),HealthResponse:e("HealthResponse",Qh),ProviderStatus:e("ProviderStatus",Xh),QueryTemplate:e("QueryTemplate",zs),ProviderActionDescriptor:e("ProviderActionDescriptor",Qs),PreviewModelsBody:e("PreviewModelsBody",an),PreviewModel:e("PreviewModel",Ba),ResolveQueryTemplateBody:e("ResolveQueryTemplateBody",Nr),ResolveQueryTemplateResponse:e("ResolveQueryTemplateResponse",Xs),ErrorResponse:e("ErrorResponse",Yh),EngineEvent:e("EngineEvent",Zh),Subject:e("Subject",oo),WorkflowLibraryEntry:e("WorkflowLibraryEntry",ty),ContextFile:e("ContextFile",Hr),CreateContextFileBody:e("CreateContextFileBody",Vr),UpdateContextFileBody:e("UpdateContextFileBody",Kr),LocalRepository:e("LocalRepository",Gr),CreateLocalRepositoryBody:e("CreateLocalRepositoryBody",zr),UpdateLocalRepositoryBody:e("UpdateLocalRepositoryBody",Qr),DeleteWorktreesBody:e("DeleteWorktreesBody",Yn),FilesystemBrowseResult:e("FilesystemBrowseResult",Fu)}}var Mh,Wh,Hh,Vh,oo,Kh,Gh,Wi,Ju,zh,Qh,Xh,Yh,Zh,ey,ty,ry,ny,oy,iy,sy,ay,_,Hi,Vi=l(()=>{"use strict";Bu();C();$i();Bi();Mi();Nu();Mh=p.enum(["pending","planning","waiting_for_human","waiting_for_children","implementing","testing","completed","failed","cancelled"]),Wh=p.object({subjectType:p.literal("ticket"),id:p.string(),source:p.string().min(1),title:p.string(),description:p.string().optional(),status:p.string(),assignee:p.string().optional(),url:p.string().optional(),raw:p.record(p.string(),p.unknown()).optional()}),Hh=p.object({subjectType:p.literal("pull_request"),id:p.string(),source:p.string().min(1),title:p.string(),description:p.string().optional(),sourceBranch:p.string(),targetBranch:p.string(),author:p.string().optional(),url:p.string().optional(),raw:p.record(p.string(),p.unknown()).optional()}),Vh=p.object({subjectType:p.literal("documentation"),id:p.string(),source:p.string().min(1),title:p.string(),url:p.string().optional(),raw:p.record(p.string(),p.unknown()).optional()}),oo=p.discriminatedUnion("subjectType",[Wh,Hh,Vh]),Kh=p.discriminatedUnion("mode",[p.object({mode:p.literal("single"),subject:oo}),p.object({mode:p.literal("collection"),subjects:p.array(oo)})]),Gh=p.object({id:p.string(),stepDefinitionId:p.string(),type:p.string(),status:p.enum(["pending","running","waiting_for_children","completed","failed","skipped"]),startedAt:p.string().optional(),completedAt:p.string().optional(),output:p.unknown().optional(),error:p.string().optional(),childJobIds:p.array(p.string()).optional(),iterations:p.array(p.object({index:p.number().int(),stepExecutions:p.array(p.record(p.string(),p.unknown())),startedAt:p.string(),completedAt:p.string().optional()})).optional()}),Wi=p.object({id:p.string(),workflowId:p.string(),status:Mh,subjectContext:Kh.optional(),selection:eo.optional(),batchId:p.string().optional(),parentJobId:p.string().optional(),parentStepExecutionId:p.string().optional(),fanOutIndex:p.number().int().optional(),retryOf:p.string().optional(),workflowSnapshot:mt.optional(),context:p.record(p.string(),p.unknown()),worktreePath:p.string().optional(),branch:p.string().optional(),worktreeDeletedAt:p.string().optional(),currentStepId:p.string().optional(),currentStepExecutionId:p.string().optional(),stepHistory:p.array(Gh),createdAt:p.string(),updatedAt:p.string(),completedAt:p.string().optional()}),Ju=p.object({id:p.string(),workflowId:p.string(),selection:eo,resolvedSubjects:p.array(oo),jobIds:p.array(p.string()),status:p.enum(["running","completed","completed_with_issues","failed","cancelled"]),triggeredBy:p.enum(["schedule","view_bulk","multiselect"]),scheduleId:p.string().optional(),notificationOverride:pr.optional(),notificationSent:p.boolean(),createdAt:p.string(),completedAt:p.string().optional()}),zh=p.discriminatedUnion("kind",[p.object({kind:p.literal("job"),job:Wi}),p.object({kind:p.literal("batch"),batch:Ju})]),Qh=p.object({ok:p.boolean(),service:p.string(),timestamp:p.string()}),Xh=p.object({providerId:p.string(),secretKey:p.string(),configured:p.boolean()}),Yh=p.object({error:p.string()}),Zh=p.object({type:p.string(),timestamp:p.string()}).passthrough(),ey=et,ty=p.object({id:p.string().min(1),source:p.enum(["example","community","official"]),name:p.string().min(1),description:p.string(),workflowDefinition:et}),ry=Ur,ny=Ct.partial().omit({id:!0}),oy=p.record(p.string(),Wi.nullable()),iy=nn,sy=p.object({settings:rn,restartRequired:p.literal(!0)}),ay=p.object({settings:rn,restartRequired:p.boolean()}),_=p.object({id:p.string().min(1)}),Hi=p.object({limit:p.string().optional().openapi({description:"Max items to return (default 50)"}),offset:p.string().optional().openapi({description:"Number of items to skip (default 0)"})})});import{z as j}from"zod";function w(r,e){return{description:e,content:{"application/json":{schema:r}}}}function B(r){return{type:"array",items:r}}function g(r,...e){let t={400:"Validation error",404:"Resource not found",409:"Conflict"};return Object.fromEntries(e.map(n=>[String(n),w(r.ErrorResponse,t[n]??"Error")]))}function Uu(r,e){r.registerPath({method:"get",path:"/health",tags:["Health"],summary:"Health check",responses:{200:w(e.HealthResponse,"Service is healthy")}}),r.registerPath({method:"get",path:"/workflows",tags:["Workflows"],summary:"List workflow definitions",request:{query:j.object({subjectHandling:j.enum(["per-subject","collection"]).optional()})},responses:{200:w(B(e.WorkflowDefinition),"Workflow definitions"),...g(e,400)}}),r.registerPath({method:"get",path:"/workflows/{id}",tags:["Workflows"],summary:"Get a workflow definition",request:{params:_},responses:{200:w(e.WorkflowDefinition,"Workflow definition"),...g(e,404)}}),r.registerPath({method:"post",path:"/workflows",tags:["Workflows"],summary:"Create a workflow definition",request:{body:{required:!0,content:{"application/json":{schema:e.WorkflowDefinitionInput}}}},responses:{201:w(e.WorkflowDefinition,"Created workflow definition"),...g(e,400)}}),r.registerPath({method:"patch",path:"/workflows/{id}",tags:["Workflows"],summary:"Update a workflow definition",request:{params:_,body:{required:!0,content:{"application/json":{schema:e.UpdateWorkflowBody}}}},responses:{200:w(e.WorkflowDefinition,"Updated workflow definition"),...g(e,400,404)}}),r.registerPath({method:"delete",path:"/workflows/{id}",tags:["Workflows"],summary:"Delete a workflow definition",description:"Deletes the live workflow definition. Running Jobs keep executing from the snapshot captured at Job creation.",request:{params:_},responses:{204:{description:"Workflow deleted"},...g(e,404)}}),r.registerPath({method:"get",path:"/workflow-library",tags:["Workflow Library"],summary:"List bundled workflow library entries",responses:{200:w(B(e.WorkflowLibraryEntry),"Workflow library entries")}}),r.registerPath({method:"post",path:"/workflow-library/{id}/add",tags:["Workflow Library"],summary:"Copy a library entry into the workspace as a new workflow",request:{params:_},responses:{201:w(e.WorkflowDefinition,"Created workflow definition"),...g(e,400,404)}}),r.registerPath({method:"get",path:"/views",tags:["Views"],summary:"List subject views",request:{query:j.object({subjectType:re.optional()})},responses:{200:w(B(e.SubjectView),"Subject views"),...g(e,400)}}),r.registerPath({method:"get",path:"/views/{id}",tags:["Views"],summary:"Get a subject view",request:{params:_},responses:{200:w(e.SubjectView,"Subject view"),...g(e,404)}}),r.registerPath({method:"get",path:"/views/{id}/subjects",tags:["Views"],summary:"Preview subjects matching a view",description:"Live provider query for the View's saved filter. Same resolution path as launch() for { mode: 'view' }. Does not create Jobs or snapshots.",request:{params:_},responses:{200:w(B(e.Subject),"Matching subjects"),...g(e,404,400)}}),r.registerPath({method:"patch",path:"/views/reorder",tags:["Views"],summary:"Reorder views within a subject type group",request:{body:{required:!0,content:{"application/json":{schema:e.ReorderViewsBody}}}},responses:{200:w(B(e.SubjectView),"Reordered views for the subject type"),...g(e,400)}}),r.registerPath({method:"post",path:"/views",tags:["Views"],summary:"Create a subject view",request:{body:{required:!0,content:{"application/json":{schema:e.CreateSubjectViewBody}}}},responses:{201:w(e.SubjectView,"Created subject view"),...g(e,400)}}),r.registerPath({method:"patch",path:"/views/{id}",tags:["Views"],summary:"Update a subject view",request:{params:_,body:{required:!0,content:{"application/json":{schema:e.UpdateViewBody}}}},responses:{200:w(e.SubjectView,"Updated subject view"),...g(e,400,404)}}),r.registerPath({method:"delete",path:"/views/{id}",tags:["Views"],summary:"Delete a subject view",request:{params:_},responses:{204:{description:"Subject view deleted"},...g(e,404)}}),r.registerPath({method:"get",path:"/jobs",tags:["Jobs"],summary:"List jobs",request:{query:Hi.extend({workflowId:j.string().optional(),status:j.enum(["pending","planning","waiting_for_human","waiting_for_children","implementing","testing","completed","failed","cancelled"]).optional(),batchId:j.string().optional(),parentJobId:j.string().optional(),topLevelOnly:j.enum(["true","false"]).optional().openapi({description:"When true, exclude jobs that belong to a batch or a parent (sub_workflow) job"}),terminal:j.enum(["true","false"]).optional().openapi({description:"When true, only completed/failed/cancelled jobs. When false, only in-progress jobs. Omitted: no terminality filter."}),liveWorktree:j.enum(["true","false"]).optional().openapi({description:"When true, only jobs with a worktreePath that has not been deleted from the management page."})})},responses:{200:w(B(e.Job),"Jobs"),...g(e,400)}}),r.registerPath({method:"post",path:"/jobs/delete-worktrees",tags:["Jobs"],summary:"Delete live worktree folders for terminal jobs",request:{body:{required:!0,content:{"application/json":{schema:e.DeleteWorktreesBody}}}},responses:{200:w(B(e.Job),"Jobs after worktree deletion"),...g(e,400,404,409)}}),r.registerPath({method:"get",path:"/jobs/{id}",tags:["Jobs"],summary:"Get a job",request:{params:_},responses:{200:w(e.Job,"Job"),...g(e,404)}}),r.registerPath({method:"post",path:"/jobs",tags:["Jobs"],summary:"Start a single job",request:{body:{required:!0,content:{"application/json":{schema:e.CreateJobBody}}}},responses:{201:w(e.Job,"Started job"),...g(e,400,404)}}),r.registerPath({method:"post",path:"/jobs/latest-by-subject",tags:["Jobs"],summary:"Latest job per subject for a workflow",request:{body:{required:!0,content:{"application/json":{schema:e.LatestBySubjectBody}}}},responses:{200:w(e.LatestBySubjectResponse,"Latest job keyed by subject id"),...g(e,400)}}),r.registerPath({method:"post",path:"/jobs/{id}/resume",tags:["Jobs"],summary:"Resume a job waiting for human input",request:{params:_,body:{required:!0,content:{"application/json":{schema:e.ResumeJobBody}}}},responses:{200:w(e.Job,"Resumed job"),...g(e,400,404,409)}}),r.registerPath({method:"post",path:"/jobs/{id}/retry",tags:["Jobs"],summary:"Retry a failed job as a new linked job",request:{params:_},responses:{200:w(e.Job,"Retry job"),...g(e,404,409)}}),r.registerPath({method:"post",path:"/jobs/{id}/retry-step",tags:["Jobs"],summary:"Retry the failed step of a job in place",request:{params:_},responses:{200:w(e.Job,"Job after retrying the failed step"),...g(e,404,409)}}),r.registerPath({method:"post",path:"/jobs/{id}/cancel",tags:["Jobs"],summary:"Cancel a non-terminal job",request:{params:_},responses:{200:w(e.Job,"Cancelled job"),...g(e,404,409)}}),r.registerPath({method:"get",path:"/batches",tags:["Batches"],summary:"List job batches",request:{query:Hi.extend({workflowId:j.string().optional()})},responses:{200:w(B(e.JobBatch),"Job batches")}}),r.registerPath({method:"get",path:"/batches/{id}",tags:["Batches"],summary:"Get a job batch",request:{params:_},responses:{200:w(e.JobBatch,"Job batch"),...g(e,404)}}),r.registerPath({method:"get",path:"/batches/{id}/jobs",tags:["Batches"],summary:"List jobs in a batch",request:{params:_},responses:{200:w(B(e.Job),"Jobs in the batch"),...g(e,404)}}),r.registerPath({method:"post",path:"/batches",tags:["Batches"],summary:"Launch a per-subject batch or collection run",description:"Resolves subject selection and starts a JobBatch for per-subject workflows (even for one subject) or a single Job for collection workflows.",request:{body:{required:!0,content:{"application/json":{schema:e.LaunchBody}}}},responses:{201:w(e.LaunchResponse,"Launch result"),...g(e,400,404)}}),r.registerPath({method:"post",path:"/batches/{id}/cancel",tags:["Batches"],summary:"Cancel a running job batch",request:{params:_},responses:{200:w(e.JobBatch,"Cancelled batch"),...g(e,404,409)}}),r.registerPath({method:"get",path:"/workflow-shortcuts",tags:["Workflow shortcuts"],summary:"List workflow shortcuts",responses:{200:w(B(e.WorkflowShortcut),"Workflow shortcuts")}}),r.registerPath({method:"get",path:"/workflow-shortcuts/{id}",tags:["Workflow shortcuts"],summary:"Get a workflow shortcut",request:{params:_},responses:{200:w(e.WorkflowShortcut,"Workflow shortcut"),...g(e,404)}}),r.registerPath({method:"post",path:"/workflow-shortcuts",tags:["Workflow shortcuts"],summary:"Create a workflow shortcut",request:{body:{required:!0,content:{"application/json":{schema:e.CreateWorkflowShortcutBody}}}},responses:{201:w(e.WorkflowShortcut,"Created workflow shortcut"),...g(e,400,404)}}),r.registerPath({method:"patch",path:"/workflow-shortcuts/reorder",tags:["Workflow shortcuts"],summary:"Reorder workflow shortcuts",request:{body:{required:!0,content:{"application/json":{schema:e.ReorderShortcutsBody}}}},responses:{200:w(B(e.WorkflowShortcut),"Reordered workflow shortcuts"),...g(e,400)}}),r.registerPath({method:"patch",path:"/workflow-shortcuts/{id}",tags:["Workflow shortcuts"],summary:"Update a workflow shortcut",request:{params:_,body:{required:!0,content:{"application/json":{schema:e.UpdateWorkflowShortcutBody}}}},responses:{200:w(e.WorkflowShortcut,"Updated workflow shortcut"),...g(e,400,404)}}),r.registerPath({method:"delete",path:"/workflow-shortcuts/{id}",tags:["Workflow shortcuts"],summary:"Delete a workflow shortcut",request:{params:_},responses:{204:{description:"Workflow shortcut deleted"},...g(e,404)}}),r.registerPath({method:"get",path:"/context-files",tags:["Context Files"],summary:"List context files",responses:{200:w(B(e.ContextFile),"Context files")}}),r.registerPath({method:"get",path:"/context-files/{id}",tags:["Context Files"],summary:"Get a context file",request:{params:_},responses:{200:w(e.ContextFile,"Context file"),...g(e,404)}}),r.registerPath({method:"post",path:"/context-files",tags:["Context Files"],summary:"Create a context file",request:{body:{required:!0,content:{"application/json":{schema:e.CreateContextFileBody}}}},responses:{201:w(e.ContextFile,"Created context file"),...g(e,400)}}),r.registerPath({method:"patch",path:"/context-files/{id}",tags:["Context Files"],summary:"Update a context file",request:{params:_,body:{required:!0,content:{"application/json":{schema:e.UpdateContextFileBody}}}},responses:{200:w(e.ContextFile,"Updated context file"),...g(e,400,404)}}),r.registerPath({method:"delete",path:"/context-files/{id}",tags:["Context Files"],summary:"Delete a context file",request:{params:_},responses:{204:{description:"Context file deleted"},...g(e,404)}}),r.registerPath({method:"get",path:"/local-repositories",tags:["Local Repositories"],summary:"List local repositories",responses:{200:w(B(e.LocalRepository),"Local repositories")}}),r.registerPath({method:"get",path:"/local-repositories/{id}",tags:["Local Repositories"],summary:"Get a local repository",request:{params:_},responses:{200:w(e.LocalRepository,"Local repository"),...g(e,404)}}),r.registerPath({method:"post",path:"/local-repositories",tags:["Local Repositories"],summary:"Create a local repository",request:{body:{required:!0,content:{"application/json":{schema:e.CreateLocalRepositoryBody}}}},responses:{201:w(e.LocalRepository,"Created local repository"),...g(e,400)}}),r.registerPath({method:"patch",path:"/local-repositories/{id}",tags:["Local Repositories"],summary:"Update a local repository",request:{params:_,body:{required:!0,content:{"application/json":{schema:e.UpdateLocalRepositoryBody}}}},responses:{200:w(e.LocalRepository,"Updated local repository"),...g(e,400,404)}}),r.registerPath({method:"delete",path:"/local-repositories/{id}",tags:["Local Repositories"],summary:"Delete a local repository",request:{params:_},responses:{204:{description:"Local repository deleted"},...g(e,404)}}),r.registerPath({method:"get",path:"/filesystem/browse",tags:["Filesystem"],summary:"List a host directory",request:{query:j.object({path:j.string().optional()})},responses:{200:w(e.FilesystemBrowseResult,"Directory listing"),...g(e,400)}}),r.registerPath({method:"get",path:"/schedules",tags:["Schedules"],summary:"List schedules",request:{query:j.object({enabled:j.enum(["true","false"]).optional()})},responses:{200:w(B(e.Schedule),"Schedules"),...g(e,400)}}),r.registerPath({method:"get",path:"/schedules/{id}",tags:["Schedules"],summary:"Get a schedule",request:{params:_},responses:{200:w(e.Schedule,"Schedule"),...g(e,404)}}),r.registerPath({method:"post",path:"/schedules",tags:["Schedules"],summary:"Create a schedule",description:"CRUD only \u2014 creating or enabling a schedule does not cause it to fire yet.",request:{body:{required:!0,content:{"application/json":{schema:e.Schedule}}}},responses:{201:w(e.Schedule,"Created schedule"),...g(e,400)}}),r.registerPath({method:"patch",path:"/schedules/{id}",tags:["Schedules"],summary:"Update a schedule",request:{params:_,body:{required:!0,content:{"application/json":{schema:e.UpdateScheduleBody}}}},responses:{200:w(e.Schedule,"Updated schedule"),...g(e,400,404)}}),r.registerPath({method:"delete",path:"/schedules/{id}",tags:["Schedules"],summary:"Delete a schedule",request:{params:_},responses:{204:{description:"Schedule deleted"},...g(e,404)}}),r.registerPath({method:"get",path:"/providers/status",tags:["Providers"],summary:"Provider secret configuration status",description:"Reports whether each known provider API key is set. Returns key *names* only \u2014 never secret values.",responses:{200:w(B(e.ProviderStatus),"Provider configuration status")}}),r.registerPath({method:"post",path:"/providers/preview-models",tags:["Providers"],summary:"Preview models available to an agent API key",description:"Lookup only \u2014 does not persist settings or secrets. Send apiKey to try a typed key before save, or instanceId to use the already-stored key (never echoed).",request:{body:{required:!0,content:{"application/json":{schema:e.PreviewModelsBody}}}},responses:{200:w(B(e.PreviewModel),"Models available to the key"),...g(e,400,404)}}),r.registerPath({method:"get",path:"/providers/{providerId}/query-templates",tags:["Providers"],summary:"List query templates for a provider",description:"Named, pre-built query templates owned by the provider. Providers with none yet (e.g. documentation) return an empty list. The client never constructs `query` itself \u2014 it submits templateId + params to the resolve endpoint.",request:{params:j.object({providerId:j.string().min(1)})},responses:{200:w(B(e.QueryTemplate),"Query templates")}}),r.registerPath({method:"get",path:"/providers/{providerId}/actions",tags:["Providers"],summary:"List extended actions for a provider",description:"Opt-in capabilities beyond the portable five ProviderAction operations. Providers that do not implement ExtendedActionProvider return an empty list \u2014 that is a normal, expected case, not an error.",request:{params:j.object({providerId:j.string().min(1)})},responses:{200:w(B(e.ProviderActionDescriptor),"Extended actions")}}),r.registerPath({method:"post",path:"/providers/{providerId}/query-templates/{templateId}/resolve",tags:["Providers"],summary:"Resolve a query template to a concrete query",description:"Provider-specific query-shape knowledge stays server-side. Returns the `query` object to store on a SubjectView, along with template provenance the client attaches separately.",request:{params:j.object({providerId:j.string().min(1),templateId:j.string().min(1)}),body:{required:!0,content:{"application/json":{schema:e.ResolveQueryTemplateBody}}}},responses:{200:w(e.ResolveQueryTemplateResponse,"Resolved query"),...g(e,400,404)}}),r.registerPath({method:"get",path:"/settings",tags:["Settings"],summary:"Get engine settings",description:"Persisted provider configuration. Never includes secret values \u2014 those live in SecretStore.",responses:{200:w(e.EngineSettings,"Current engine settings")}}),r.registerPath({method:"patch",path:"/settings",tags:["Settings"],summary:"Update engine settings",description:"Partial merge. restartRequired is true when providerInstances is in the patch (instance bindings are boot-time). Changing defaultAgentInstanceId takes effect on the next agent step with no restart.",request:{body:{required:!0,content:{"application/json":{schema:e.UpdateSettingsBody}}}},responses:{200:w(e.SettingsPatchResponse,"Updated settings"),...g(e,400)}}),r.registerPath({method:"get",path:"/provider-instances",tags:["Settings"],summary:"List provider instances",responses:{200:w(B(e.ProviderInstanceConfig),"Configured provider instances")}}),r.registerPath({method:"post",path:"/provider-instances",tags:["Settings"],summary:"Create a provider instance",description:"Persists the instance. restartRequired is always true \u2014 bindings are boot-time. For agent instances, defaultAgent atomically replaces EngineSettings.defaultAgentInstanceId in the same write.",request:{body:{required:!0,content:{"application/json":{schema:e.CreateProviderInstanceBody}}}},responses:{201:w(e.ProviderInstanceMutationResponse,"Created instance settings"),...g(e,400,409)}}),r.registerPath({method:"get",path:"/provider-instances/{id}",tags:["Settings"],summary:"Get a provider instance",request:{params:j.object({id:j.string().min(1)})},responses:{200:w(e.ProviderInstanceConfig,"Provider instance"),...g(e,404)}}),r.registerPath({method:"patch",path:"/provider-instances/{id}",tags:["Settings"],summary:"Update a provider instance",request:{params:j.object({id:j.string().min(1)}),body:{required:!0,content:{"application/json":{schema:e.UpdateProviderInstanceBody}}}},responses:{200:w(e.ProviderInstanceMutationResponse,"Updated instance settings"),...g(e,400,404)}}),r.registerPath({method:"delete",path:"/provider-instances/{id}",tags:["Settings"],summary:"Delete a provider instance",request:{params:j.object({id:j.string().min(1)})},responses:{200:w(e.ProviderInstanceMutationResponse,"Updated settings after delete"),...g(e,404)}}),r.registerPath({method:"post",path:"/secrets/{key}",tags:["Settings"],summary:"Store a secret",description:"Writes to SecretStore. The response never includes the secret value.",request:{params:j.object({key:j.string().min(1)}),body:{required:!0,content:{"application/json":{schema:e.SetSecretBody}}}},responses:{204:{description:"Secret stored"},...g(e,400)}}),r.registerPath({method:"get",path:"/events",tags:["Events"],summary:"Subscribe to engine events (SSE)",description:"Server-Sent Events stream. Each event `data` field is a JSON EngineEvent. Optionally filter by jobId and/or batchId.",request:{query:j.object({jobId:j.string().optional(),batchId:j.string().optional()})},responses:{200:{description:"SSE stream of engine events",content:{"text/event-stream":{schema:e.EngineEvent}}}}})}var Mu=l(()=>{"use strict";C();Vi()});import{OpenAPIRegistry as uy,OpenApiGeneratorV31 as ly}from"@asteasolutions/zod-to-openapi";function Wu(){if(io)return io;let r=new uy,e=Lu(r);return Uu(r,e),io=new ly(r.definitions).generateDocument({openapi:"3.1.0",info:{title:"Knoflows Engine API",version:"0.1.0",description:"REST API for workflow definitions, jobs, batches, schedules, views, and live events."},servers:[{url:"/api"}]}),io}var io,Hu=l(()=>{"use strict";Vi();Mu()});import{Controller as py,Get as dy,Header as fy}from"@nestjs/common";var Vu,Ki,jr,Ku=l(()=>{"use strict";Hu();Vu=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Ki=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},jr=class{getOpenApiDocument(){return Wu()}};Vu([dy("openapi.json"),fy("Content-Type","application/json"),Ki("design:type",Function),Ki("design:paramtypes",[]),Ki("design:returntype",void 0)],jr.prototype,"getOpenApiDocument",null);jr=Vu([py()],jr)});import{Controller as my,Get as Gi,Inject as so,Param as ao,Post as Gu,Body as zu,HttpCode as Qu}from"@nestjs/common";var Mt,H,Ce,Le,Xu=l(()=>{"use strict";Vo();ni();oi();ai();C();ne();Mt=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},H=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},Ce=function(r,e){return function(t,n){e(t,n,r)}},Le=class{providerStatus;queryTemplates;extendedActions;previewModels;constructor(e,t,n,o){this.providerStatus=e,this.queryTemplates=t,this.extendedActions=n,this.previewModels=o}async status(){return this.providerStatus.list()}previewAvailableModels(e){return this.previewModels.preview(e)}listQueryTemplates(e){return this.queryTemplates.list(e)}listExtendedActions(e){return this.extendedActions.list(e)}async resolveQueryTemplate(e,t,n){return{query:await this.queryTemplates.resolve(e,t,n.params)}}};Mt([Gi("status"),H("design:type",Function),H("design:paramtypes",[]),H("design:returntype",Promise)],Le.prototype,"status",null);Mt([Gu("preview-models"),Qu(200),Ce(0,zu(new v(an))),H("design:type",Function),H("design:paramtypes",[Object]),H("design:returntype",Promise)],Le.prototype,"previewAvailableModels",null);Mt([Gi(":providerId/query-templates"),Ce(0,ao("providerId")),H("design:type",Function),H("design:paramtypes",[String]),H("design:returntype",Promise)],Le.prototype,"listQueryTemplates",null);Mt([Gi(":providerId/actions"),Ce(0,ao("providerId")),H("design:type",Function),H("design:paramtypes",[String]),H("design:returntype",Promise)],Le.prototype,"listExtendedActions",null);Mt([Gu(":providerId/query-templates/:templateId/resolve"),Qu(200),Ce(0,ao("providerId")),Ce(1,ao("templateId")),Ce(2,zu(new v(Nr))),H("design:type",Function),H("design:paramtypes",[String,String,Object]),H("design:returntype",Promise)],Le.prototype,"resolveQueryTemplate",null);Le=Mt([my("providers"),Ce(0,so(tt)),Ce(1,so(rt)),Ce(2,so(nt)),Ce(3,so(ot)),H("design:paramtypes",[tt,rt,nt,ot])],Le)});import{Body as hy,Controller as yy,Get as wy,Inject as gy,Patch as by}from"@nestjs/common";var zi,Pt,Yu,Wt,Zu=l(()=>{"use strict";C();Pe();ne();zi=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Pt=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},Yu=function(r,e){return function(t,n){e(t,n,r)}},Wt=class{settings;constructor(e){this.settings=e}get(){return this.settings.get()}async update(e){return{settings:await this.settings.update(e),restartRequired:Ua(e)}}};zi([wy(),Pt("design:type",Function),Pt("design:paramtypes",[]),Pt("design:returntype",Promise)],Wt.prototype,"get",null);zi([by(),Yu(0,hy(new v(nn))),Pt("design:type",Function),Pt("design:paramtypes",[Object]),Pt("design:returntype",Promise)],Wt.prototype,"update",null);Wt=zi([yy("settings"),Yu(0,gy(R)),Pt("design:paramtypes",[R])],Wt)});function Qi(r){let{current:e,instance:t,defaultAgent:n,isCreate:o}=r;return Tt(t)?n===!0?t.id:n===!1?e===t.id?null:e??null:o&&!e?t.id:e??null:e===t.id?null:e??null}function el(r){let{defaultAgent:e,...t}=r;return t}var tl=l(()=>{"use strict";C()});import{Body as rl,Controller as Sy,Delete as xy,Get as nl,HttpCode as vy,Inject as jy,Param as Xi,Patch as Iy,Post as _y}from"@nestjs/common";var Vt,V,Ht,Ue,ol=l(()=>{"use strict";C();Pe();E();ne();tl();Vt=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},V=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},Ht=function(r,e){return function(t,n){e(t,n,r)}},Ue=class{settings;constructor(e){this.settings=e}async list(){return(await this.settings.get()).providerInstances??[]}async get(e){let t=(await this.settings.get()).providerInstances?.find(n=>n.id===e);if(!t)throw new y(`Provider instance not found: ${e}`);return t}async create(e){let t=el(e),n=await this.settings.get(),o=[...n.providerInstances??[]];if(o.some(s=>s.id===t.id))throw new J(`Provider instance already exists: ${t.id}`);return o.push(t),{settings:await this.settings.update({providerInstances:o,defaultAgentInstanceId:Qi({current:n.defaultAgentInstanceId,instance:t,defaultAgent:e.defaultAgent,isCreate:!0})}),restartRequired:!0}}async update(e,t){let n=await this.settings.get(),o=[...n.providerInstances??[]],i=o.findIndex(c=>c.id===e);if(i<0)throw new y(`Provider instance not found: ${e}`);let a={...o[i],...t.displayName!=null?{displayName:t.displayName}:{},...t.config!=null?{config:t.config}:{},...t.secretKey!=null?{secretKey:t.secretKey}:{}};return t.expiresOn!==void 0&&(t.expiresOn?a.expiresOn=t.expiresOn:delete a.expiresOn),o[i]=a,{settings:await this.settings.update({providerInstances:o,defaultAgentInstanceId:Qi({current:n.defaultAgentInstanceId,instance:a,defaultAgent:t.defaultAgent,isCreate:!1})}),restartRequired:!0}}async remove(e){let t=await this.settings.get(),n=(t.providerInstances??[]).filter(s=>s.id!==e);if(n.length===(t.providerInstances??[]).length)throw new y(`Provider instance not found: ${e}`);let o=t.defaultAgentInstanceId===e?null:t.defaultAgentInstanceId??null;return{settings:await this.settings.update({providerInstances:n,defaultAgentInstanceId:o}),restartRequired:!0}}};Vt([nl(),V("design:type",Function),V("design:paramtypes",[]),V("design:returntype",Promise)],Ue.prototype,"list",null);Vt([nl(":id"),Ht(0,Xi("id")),V("design:type",Function),V("design:paramtypes",[String]),V("design:returntype",Promise)],Ue.prototype,"get",null);Vt([_y(),Ht(0,rl(new v(on))),V("design:type",Function),V("design:paramtypes",[Object]),V("design:returntype",Promise)],Ue.prototype,"create",null);Vt([Iy(":id"),Ht(0,Xi("id")),Ht(1,rl(new v(sn))),V("design:type",Function),V("design:paramtypes",[String,Object]),V("design:returntype",Promise)],Ue.prototype,"update",null);Vt([xy(":id"),vy(200),Ht(0,Xi("id")),V("design:type",Function),V("design:paramtypes",[String]),V("design:returntype",Promise)],Ue.prototype,"remove",null);Ue=Vt([Sy("provider-instances"),Ht(0,jy(R)),V("design:paramtypes",[R])],Ue)});import{Body as Py,Controller as Ry,HttpCode as Ey,Inject as ky,Param as Ay,Post as Cy}from"@nestjs/common";var il,co,Yi,Ir,sl=l(()=>{"use strict";Te();E();ne();Mi();il=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},co=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},Yi=function(r,e){return function(t,n){e(t,n,r)}},Ir=class{secrets;constructor(e){this.secrets=e}async set(e,t){let n=e.trim();if(!n)throw new h("Secret key must not be empty");await this.secrets.set(n,t.value)}};il([Cy(":key"),Ey(204),Yi(0,Ay("key")),Yi(1,Py(new v(no))),co("design:type",Function),co("design:paramtypes",[String,Object]),co("design:returntype",Promise)],Ir.prototype,"set",null);Ir=il([Ry("secrets"),Yi(0,ky(fe)),co("design:paramtypes",[Function])],Ir)});import{readFile as Ty}from"node:fs/promises";async function Zi(r){try{await Ty(r,"utf8")}catch(e){let t=e instanceof Error?e.message:String(e);throw new h(`Cannot read context file at '${r}': ${t}`)}}var al=l(()=>{"use strict";E()});import{Body as cl,Controller as Oy,Delete as $y,Get as ul,HttpCode as qy,Inject as By,Param as es,Patch as Dy,Post as Fy}from"@nestjs/common";import{randomUUID as Ny}from"node:crypto";var Gt,K,Kt,Me,ll=l(()=>{"use strict";C();Dr();E();ne();al();Gt=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},K=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},Kt=function(r,e){return function(t,n){e(t,n,r)}},Me=class{files;constructor(e){this.files=e}async list(){return this.files.list()}async get(e){let t=await this.files.get(e);if(!t)throw new y(`Context file not found: ${e}`);return t}async create(e){return await Zi(e.path),this.files.create({id:e.id??Ny(),name:e.name,description:e.description,tier:e.tier,path:e.path})}async update(e,t){let n=await this.files.get(e);if(!n)throw new y(`Context file not found: ${e}`);let o=t.path??n.path;await Zi(o);let i=await this.files.update(e,t);if(!i)throw new y(`Context file not found: ${e}`);return i}async remove(e){if(!await this.files.delete(e))throw new y(`Context file not found: ${e}`)}};Gt([ul(),K("design:type",Function),K("design:paramtypes",[]),K("design:returntype",Promise)],Me.prototype,"list",null);Gt([ul(":id"),Kt(0,es("id")),K("design:type",Function),K("design:paramtypes",[String]),K("design:returntype",Promise)],Me.prototype,"get",null);Gt([Fy(),Kt(0,cl(new v(Vr))),K("design:type",Function),K("design:paramtypes",[Object]),K("design:returntype",Promise)],Me.prototype,"create",null);Gt([Dy(":id"),Kt(0,es("id")),Kt(1,cl(new v(Kr))),K("design:type",Function),K("design:paramtypes",[String,Object]),K("design:returntype",Promise)],Me.prototype,"update",null);Gt([$y(":id"),qy(204),Kt(0,es("id")),K("design:type",Function),K("design:paramtypes",[String]),K("design:returntype",Promise)],Me.prototype,"remove",null);Me=Gt([Oy("context-files"),Kt(0,By(ae)),K("design:paramtypes",[ae])],Me)});import{execFile as Jy}from"node:child_process";import{stat as Ly}from"node:fs/promises";import{resolve as ts}from"node:path";import{promisify as Uy}from"node:util";async function rs(r){let e=ts(r);try{if((await My("git",["-C",e,"rev-parse","--is-inside-work-tree"],{encoding:"utf8",windowsHide:!0})).stdout.trim()!=="true")throw new Error("not a work tree")}catch(t){let n=t instanceof Error?t.message:String(t);throw new h(`'${r}' is not a git repository: ${n}`)}}async function ns(r,e){let t=ts(r),n=ts(e?.trim()?e.trim():Dn(t));if(Fn(t,n))throw new h(`Worktree base '${n}' must not be inside the repository at '${t}'`);try{if(!(await Ly(n)).isDirectory())throw new h(`Worktree base '${n}' exists and is not a directory`)}catch(o){if(o instanceof h)throw o}}var My,pl=l(()=>{"use strict";E();gi();My=Uy(Jy)});import{Body as dl,Controller as Wy,Delete as Hy,Get as fl,HttpCode as Vy,Inject as Ky,Param as os,Patch as Gy,Post as zy}from"@nestjs/common";import{randomUUID as Qy}from"node:crypto";var Qt,G,zt,We,ml=l(()=>{"use strict";C();Fr();E();ne();pl();Qt=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},G=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},zt=function(r,e){return function(t,n){e(t,n,r)}},We=class{repos;constructor(e){this.repos=e}async list(){return this.repos.list()}async get(e){let t=await this.repos.get(e);if(!t)throw new y(`Local repository not found: ${e}`);return t}async create(e){return await rs(e.localPath),await ns(e.localPath,e.worktreeBasePath),this.repos.create({id:e.id??Qy(),name:e.name,localPath:e.localPath,...e.worktreeBasePath?{worktreeBasePath:e.worktreeBasePath}:{}})}async update(e,t){let n=await this.repos.get(e);if(!n)throw new y(`Local repository not found: ${e}`);let o=t.localPath??n.localPath,i=t.worktreeBasePath!==void 0?t.worktreeBasePath:n.worktreeBasePath;await rs(o),await ns(o,i);let s=await this.repos.update(e,t);if(!s)throw new y(`Local repository not found: ${e}`);return s}async remove(e){if(!await this.repos.delete(e))throw new y(`Local repository not found: ${e}`)}};Qt([fl(),G("design:type",Function),G("design:paramtypes",[]),G("design:returntype",Promise)],We.prototype,"list",null);Qt([fl(":id"),zt(0,os("id")),G("design:type",Function),G("design:paramtypes",[String]),G("design:returntype",Promise)],We.prototype,"get",null);Qt([zy(),zt(0,dl(new v(zr))),G("design:type",Function),G("design:paramtypes",[Object]),G("design:returntype",Promise)],We.prototype,"create",null);Qt([Gy(":id"),zt(0,os("id")),zt(1,dl(new v(Qr))),G("design:type",Function),G("design:paramtypes",[String,Object]),G("design:returntype",Promise)],We.prototype,"update",null);Qt([Hy(":id"),Vy(204),zt(0,os("id")),G("design:type",Function),G("design:paramtypes",[String]),G("design:returntype",Promise)],We.prototype,"remove",null);We=Qt([Wy("local-repositories"),zt(0,Ky(ce)),G("design:paramtypes",[ce])],We)});import{readdir as Xy,stat as Yy}from"node:fs/promises";import{homedir as Zy}from"node:os";import{join as ew,resolve as tw}from"node:path";async function hl(r){let e=r?.trim()?r.trim():Zy(),t=tw(e),n;try{n=await Yy(t)}catch(i){throw new h(`Cannot browse '${t}': ${i instanceof Error?i.message:String(i)}`)}if(!n.isDirectory())throw new h(`Cannot browse '${t}': not a directory`);let o;try{o=(await Xy(t,{encoding:"utf8",withFileTypes:!0})).filter(s=>s.name!=="."&&s.name!=="..").map(s=>({name:s.name,path:ew(t,s.name),isDirectory:s.isDirectory()})).sort((s,a)=>s.isDirectory!==a.isDirectory?s.isDirectory?-1:1:s.name.localeCompare(a.name))}catch(i){throw new h(`Cannot browse '${t}': ${i instanceof Error?i.message:String(i)}`)}return{path:t,entries:o}}var yl=l(()=>{"use strict";E()});import{Controller as nw,Get as ow,Query as iw}from"@nestjs/common";var wl,is,rw,_r,gl=l(()=>{"use strict";yl();wl=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},is=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},rw=function(r,e){return function(t,n){e(t,n,r)}},_r=class{async browse(e){return hl(e)}};wl([ow("browse"),rw(0,iw("path")),is("design:type",Function),is("design:paramtypes",[String]),is("design:returntype",Promise)],_r.prototype,"browse",null);_r=wl([nw("filesystem")],_r)});import{Module as aw}from"@nestjs/common";import{APP_FILTER as cw}from"@nestjs/core";var sw,uo,bl=l(()=>{"use strict";dr();vi();On();tu();cu();yu();gu();vu();Pu();Eu();Cu();qu();Ku();Xu();Zu();ol();sl();ll();ml();gl();Cn();jo();sw=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},uo=class{};uo=sw([aw({imports:[Re,Ft,st,it,Et],controllers:[De,Jt,Se,Ee,oe,Ne,Je,vr,jr,Le,Wt,Ue,Ir,Me,We,_r],providers:[{provide:cw,useClass:Un}]})],uo)});import{Module as lw}from"@nestjs/common";var uw,lo,Sl=l(()=>{"use strict";us();ls();ps();Cn();On();dr();vi();bl();uw=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},lo=class{};lo=uw([lw({imports:[Pr,Rr,it,st,Re,Ft,uo],controllers:[Xt]})],lo)});import{apiReference as pw}from"@scalar/nestjs-api-reference";function xl(r){r.use("/api/docs",pw({url:"/api/openapi.json",pageTitle:"Knoflows Engine API"}))}var vl=l(()=>{"use strict"});import{createServer as dw}from"node:net";function jl(r){return typeof r=="object"&&r!==null&&"code"in r&&r.code==="EADDRINUSE"}async function ss(r,e=20){for(let t=0;t<e;t+=1){let n=r+t;if(await fw(n))return n}throw new Error(`No free port found in ${r}\u2013${r+e-1}`)}function fw(r){return new Promise(e=>{let t=dw();t.once("error",()=>{e(!1)}),t.once("listening",()=>{t.close(()=>e(!0))}),t.listen(r)})}var Il=l(()=>{"use strict"});import{Catch as yw,HttpStatus as po,NotFoundException as ww}from"@nestjs/common";import{existsSync as _l,statSync as gw}from"node:fs";import{extname as Pl,join as as,normalize as bw,relative as Sw,sep as xw}from"node:path";function Rl(r){return(e,t,n)=>{if(e.method!=="GET"&&e.method!=="HEAD"){n();return}if((e.path??"").startsWith("/api")){n();return}let o=vw(e.path??"/");if(o){let i=as(r,o);if(jw(r,i)){t.sendFile(o,{root:r},s=>{s&&n()});return}}if(El(e)){kl(t,r,i=>{i&&!t.headersSent&&t.status(po.NOT_FOUND).end()});return}t.status(po.NOT_FOUND).end()}}function El(r){if(r.method!=="GET"&&r.method!=="HEAD")return!1;let e=r.path??"";if(e.startsWith("/api"))return!1;let t=Pl(e);return!(t&&t!==".html")}function kl(r,e,t){r.sendFile("index.html",{root:e},t)}function vw(r){if(r==="/"||r==="")return"index.html";let e=bw(r.replace(/^\/+/,""));return!e||e==="."||e.startsWith("..")||!Pl(e)?null:e}function jw(r,e){if(!_l(e))return!1;try{if(!gw(e).isFile())return!1}catch{return!1}let t=Sw(r,e);return t!==""&&!t.startsWith(`..${xw}`)&&!t.startsWith("..")}function Al(r){return as(r,"index.html")}var mw,hw,fo,Cl=l(()=>{"use strict";mw=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},hw=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},fo=class{staticRoot;constructor(e){this.staticRoot=e}catch(e,t){let n=t.switchToHttp(),o=n.getRequest(),i=n.getResponse();if(El(o)&&_l(as(this.staticRoot,"index.html"))){kl(i,this.staticRoot,u=>{u&&!i.headersSent&&i.status(po.NOT_FOUND).json({statusCode:po.NOT_FOUND,message:"UI index.html could not be served"})});return}let s=e.getStatus(),a=e.getResponse();i.status(s).json(typeof a=="string"?{statusCode:s,message:a}:a)}};fo=mw([yw(ww),hw("design:paramtypes",[String])],fo)});import{existsSync as Iw}from"node:fs";import{dirname as _w,join as mo}from"node:path";import{fileURLToPath as Pw}from"node:url";function Tl(){let r=_w(Pw(import.meta.url)),e=[mo(r,"../static"),mo(r,"../../static"),mo(r,"static")];for(let t of e)if(Iw(mo(t,"index.html")))return t;return null}var Ol=l(()=>{"use strict"});var Cw={};import"reflect-metadata";import{existsSync as Rw}from"node:fs";import{Logger as Ew}from"@nestjs/common";import{NestFactory as kw}from"@nestjs/core";async function Aw(){let r=await kw.create(lo);r.enableCors(),r.setGlobalPrefix("api"),xl(r);let e=Tl(),t=e?Al(e):null;e&&t&&Rw(t)?(ho.log(`Serving UI from ${e}`),r.use(Rl(e)),r.useGlobalFilters(new fo(e))):ho.warn("No UI found (static/index.html missing). GET / will 404; /api still works. Rebuild with `npm run build:release` before publishing.");let n=Number(process.env.PORT??3e3);if(!Number.isInteger(n)||n<1||n>65535)throw new Error(`Invalid PORT: ${process.env.PORT}`);let o=await ss(n);for(let i=0;i<5;i+=1)try{await r.listen(o),o!==n?ho.warn(`Port ${n} is in use; listening on ${o} instead`):ho.log(`Listening on http://localhost:${o}`);return}catch(s){if(!jl(s))throw s;o=await ss(o+1)}throw new Error(`Could not bind a free port starting at ${n}`)}var ho,$l=l(()=>{"use strict";Sl();vl();Il();Cl();Ol();ho=new Ew("Bootstrap");Aw()});import{readFileSync as Tw}from"node:fs";function Ow(){let r=Tw(new URL("../package.json",import.meta.url),"utf8");return JSON.parse(r).version}var yo=process.argv.slice(2);yo.includes("--version")||yo.includes("-v")?console.log(Ow()):yo.includes("--help")||yo.includes("-h")?console.log(["Usage: knoflows [options]","","Starts the knoflows engine (REST API + bundled web client).","","Options:"," -v, --version Print the engine version and exit"," -h, --help Print this message and exit","","Environment:"," PORT Preferred HTTP port (default 3000). If taken, the next free port is used."," KNO_SQLITE_PATH SQLite file path, or :memory: for an ephemeral database"].join(`
|
|
34
|
-
`)):await Promise.resolve().then(()=>(
|
|
33
|
+
Testing: {{testing-review}}`,outputFormat:"free_text"}],notificationPolicy:{triggers:["on_fail","on_complete"]}}},ki=[Eh,Ph];for(let r of ki)bu(r)});import{Controller as Rh,Get as kh,Inject as Ah,Param as Ch,Post as Th}from"@nestjs/common";var Ai,jt,_u,Ut,Eu=l(()=>{"use strict";mt();R();ju();Pi();Ai=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},jt=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},_u=function(r,e){return function(t,n){e(t,n,r)}},Ut=class{workflows;constructor(e){this.workflows=e}list(){return vu()}async add(e){let t=Iu(e);if(!t)throw new y(`Workflow library entry not found: ${e}`);let n=structuredClone(t.workflowDefinition);return delete n.id,Hn(this.workflows,n)}};Ai([kh(),jt("design:type",Function),jt("design:paramtypes",[]),jt("design:returntype",Array)],Ut.prototype,"list",null);Ai([Th(":id/add"),_u(0,Ch("id")),jt("design:type",Function),jt("design:paramtypes",[String]),jt("design:returntype",Promise)],Ut.prototype,"add",null);Ut=Ai([Rh("workflow-library"),_u(0,Ah(O)),jt("design:paramtypes",[O])],Ut)});import{Body as Ti,Controller as Oh,Delete as $h,Get as Oi,HttpCode as qh,Inject as Ci,Param as Vn,Patch as Pu,Post as Bh,Query as Dh}from"@nestjs/common";var lt,T,be,Se,Ru=l(()=>{"use strict";C();qr();mt();R();ne();Sr();Bt();wi();lt=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},T=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},be=function(r,e){return function(t,n){e(t,n,r)}},Se=class{views;workflows;providers;constructor(e,t,n){this.views=e,this.workflows=t,this.providers=n}async list(e){if(e!=null&&e!==""){let t=re.safeParse(e);if(!t.success)throw new h(`Invalid subjectType filter: ${e}`);return this.views.list({subjectType:t.data})}return this.views.list({})}async reorder(e){let t=[];for(let i of e.viewIds){let s=await this.views.get(i);if(!s)throw new h(`Unknown view id in reorder: ${i}`);t.push(s)}if(new Set(t.map(i=>i.subjectType)).size!==1)throw new h("All viewIds in a reorder request must share the same subjectType");return await this.views.reorder(e.viewIds)}async listSubjects(e){return Bn(e,this.views,this.providers)}async get(e){let t=await this.views.get(e);if(!t)throw new y(`SubjectView not found: ${e}`);return t}async create(e){return await this.assertBinding(e.workflowId,e.subjectType),this.views.create(e)}async update(e,t){let n=await this.views.get(e);if(!n)throw new y(`SubjectView not found: ${e}`);await this.assertBinding(t.workflowId??n.workflowId,t.subjectType??n.subjectType);let o=await this.views.update(e,t);if(!o)throw new y(`SubjectView not found: ${e}`);return o}async remove(e){if(!await this.views.delete(e))throw new y(`SubjectView not found: ${e}`)}async assertBinding(e,t){let n=await this.workflows.get(e);fu(n,e,t)}};lt([Oi(),be(0,Dh("subjectType")),T("design:type",Function),T("design:paramtypes",[String]),T("design:returntype",Promise)],Se.prototype,"list",null);lt([Pu("reorder"),be(0,Ti(new v(Mr))),T("design:type",Function),T("design:paramtypes",[Object]),T("design:returntype",Promise)],Se.prototype,"reorder",null);lt([Oi(":id/subjects"),be(0,Vn("id")),T("design:type",Function),T("design:paramtypes",[String]),T("design:returntype",Promise)],Se.prototype,"listSubjects",null);lt([Oi(":id"),be(0,Vn("id")),T("design:type",Function),T("design:paramtypes",[String]),T("design:returntype",Promise)],Se.prototype,"get",null);lt([Bh(),be(0,Ti(new v(Lr))),T("design:type",Function),T("design:paramtypes",[Object]),T("design:returntype",Promise)],Se.prototype,"create",null);lt([Pu(":id"),be(0,Vn("id")),be(1,Ti(new v(Ur))),T("design:type",Function),T("design:paramtypes",[String,Object]),T("design:returntype",Promise)],Se.prototype,"update",null);lt([$h(":id"),qh(204),be(0,Vn("id")),T("design:type",Function),T("design:paramtypes",[String]),T("design:returntype",Promise)],Se.prototype,"remove",null);Se=lt([Oh("views"),be(0,Ci(ie)),be(1,Ci(O)),be(2,Ci(F)),T("design:paramtypes",[ie,O,F])],Se)});import{Body as $i,Controller as Fh,Delete as Nh,Get as Au,HttpCode as Jh,Inject as ku,Param as qi,Patch as Cu,Post as Lh}from"@nestjs/common";var _t,q,dt,ke,Tu=l(()=>{"use strict";C();Jo();mt();R();ne();Sr();_t=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},q=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},dt=function(r,e){return function(t,n){e(t,n,r)}},ke=class{shortcuts;workflows;constructor(e,t){this.shortcuts=e,this.workflows=t}async list(){return this.shortcuts.list()}async reorder(e){for(let t of e.shortcutIds)if(!await this.shortcuts.get(t))throw new h(`Unknown shortcut id in reorder: ${t}`);return this.shortcuts.reorder(e.shortcutIds)}async get(e){let t=await this.shortcuts.get(e);if(!t)throw new y(`WorkflowShortcut not found: ${e}`);return t}async create(e){return await this.assertBinding(e.workflowId),this.shortcuts.create(e)}async update(e,t){let n=await this.shortcuts.get(e);if(!n)throw new y(`WorkflowShortcut not found: ${e}`);await this.assertBinding(t.workflowId??n.workflowId);let o=await this.shortcuts.update(e,t);if(!o)throw new y(`WorkflowShortcut not found: ${e}`);return o}async remove(e){if(!await this.shortcuts.delete(e))throw new y(`WorkflowShortcut not found: ${e}`)}async assertBinding(e){let t=await this.workflows.get(e);mu(t,e)}};_t([Au(),q("design:type",Function),q("design:paramtypes",[]),q("design:returntype",Promise)],ke.prototype,"list",null);_t([Cu("reorder"),dt(0,$i(new v(en))),q("design:type",Function),q("design:paramtypes",[Object]),q("design:returntype",Promise)],ke.prototype,"reorder",null);_t([Au(":id"),dt(0,qi("id")),q("design:type",Function),q("design:paramtypes",[String]),q("design:returntype",Promise)],ke.prototype,"get",null);_t([Lh(),dt(0,$i(new v(Yr))),q("design:type",Function),q("design:paramtypes",[Object]),q("design:returntype",Promise)],ke.prototype,"create",null);_t([Cu(":id"),dt(0,qi("id")),dt(1,$i(new v(Zr))),q("design:type",Function),q("design:paramtypes",[String,Object]),q("design:returntype",Promise)],ke.prototype,"update",null);_t([Nh(":id"),Jh(204),dt(0,qi("id")),q("design:type",Function),q("design:paramtypes",[String]),q("design:returntype",Promise)],ke.prototype,"remove",null);ke=_t([Fh("workflow-shortcuts"),dt(0,ku(qe)),dt(1,ku(O)),q("design:paramtypes",[qe,O])],ke)});function Kn(r,e,t=50){let n=r!=null&&r!==""?Number(r):t,o=e!=null&&e!==""?Number(e):0;return!Number.isFinite(n)||n<1?{limit:t,offset:Math.max(0,o||0)}:!Number.isFinite(o)||o<0?{limit:n,offset:0}:{limit:Math.floor(n),offset:Math.floor(o)}}function Gn(r,e,t){return r.slice(t,t+e)}var Bi=l(()=>{"use strict"});import{z as X}from"zod";var zn,Qn,Xn,Yn,Di=l(()=>{"use strict";zn=X.object({workflowId:X.string().min(1),subjectId:X.string().min(1).optional(),inputValues:X.record(X.string(),X.unknown())}),Qn=X.object({response:X.unknown()}),Xn=X.object({workflowId:X.string().min(1),subjectIds:X.array(X.string().min(1))}),Yn=X.object({jobIds:X.array(X.string().min(1)).min(1)})});import{Body as Zn,Controller as Uh,Get as $u,HttpCode as qu,Inject as Ou,Param as xr,Post as Et,Query as Je}from"@nestjs/common";import"zod";function Fi(r,e){if(!(r==null||r==="")){if(r==="true")return!0;if(r==="false")return!1;throw new h(`Invalid ${e} filter: ${r}`)}}var Ae,k,$,Mh,oe,Bu=l(()=>{"use strict";Ln();pr();R();ne();Bi();Di();Ae=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},k=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},$=function(r,e){return function(t,n){e(t,n,r)}},Mh=["pending","planning","waiting_for_human","waiting_for_children","implementing","testing","completed","failed","cancelled"];oe=class{jobs;runner;constructor(e,t){this.jobs=e,this.runner=t}async list(e,t,n,o,i,s,a,u,c){if(t!=null&&t!==""&&!Mh.includes(t))throw new h(`Invalid status filter: ${t}`);let p=Fi(i,"topLevelOnly"),m=Fi(s,"terminal"),b=Fi(a,"liveWorktree"),{limit:S,offset:j}=Kn(u,c),N=await this.jobs.list({...e?{workflowId:e}:{},...t?{status:t}:{},...n?{batchId:n}:{},...o?{parentJobId:o}:{},...p===!0?{topLevelOnly:!0}:{},...m!==void 0?{terminal:m}:{},...b===!0?{liveWorktree:!0}:{}});return Gn(N,S,j)}async latestBySubject(e){return this.jobs.latestBySubject(e.workflowId,e.subjectIds)}async deleteWorktrees(e){return this.runner.deleteWorktrees(e.jobIds)}async get(e){let t=await this.jobs.get(e);if(!t)throw new y(`Job not found: ${e}`);return t}async create(e){return this.runner.start({workflowId:e.workflowId,...e.subjectId?{subjectId:e.subjectId}:{},inputValues:e.inputValues})}async resume(e,t){return this.runner.resume(e,t.response)}async retry(e){return this.runner.retryFailedJob(e)}async retryStep(e){return this.runner.retryFailedStep(e)}async cancel(e){return this.runner.cancelJob(e)}};Ae([$u(),$(0,Je("workflowId")),$(1,Je("status")),$(2,Je("batchId")),$(3,Je("parentJobId")),$(4,Je("topLevelOnly")),$(5,Je("terminal")),$(6,Je("liveWorktree")),$(7,Je("limit")),$(8,Je("offset")),k("design:type",Function),k("design:paramtypes",[String,String,String,String,String,String,String,String,String]),k("design:returntype",Promise)],oe.prototype,"list",null);Ae([Et("latest-by-subject"),qu(200),$(0,Zn(new v(Xn))),k("design:type",Function),k("design:paramtypes",[Object]),k("design:returntype",Promise)],oe.prototype,"latestBySubject",null);Ae([Et("delete-worktrees"),qu(200),$(0,Zn(new v(Yn))),k("design:type",Function),k("design:paramtypes",[Object]),k("design:returntype",Promise)],oe.prototype,"deleteWorktrees",null);Ae([$u(":id"),$(0,xr("id")),k("design:type",Function),k("design:paramtypes",[String]),k("design:returntype",Promise)],oe.prototype,"get",null);Ae([Et(),$(0,Zn(new v(zn))),k("design:type",Function),k("design:paramtypes",[Object]),k("design:returntype",Promise)],oe.prototype,"create",null);Ae([Et(":id/resume"),$(0,xr("id")),$(1,Zn(new v(Qn))),k("design:type",Function),k("design:paramtypes",[String,Object]),k("design:returntype",Promise)],oe.prototype,"resume",null);Ae([Et(":id/retry"),$(0,xr("id")),k("design:type",Function),k("design:paramtypes",[String]),k("design:returntype",Promise)],oe.prototype,"retry",null);Ae([Et(":id/retry-step"),$(0,xr("id")),k("design:type",Function),k("design:paramtypes",[String]),k("design:returntype",Promise)],oe.prototype,"retryStep",null);Ae([Et(":id/cancel"),$(0,xr("id")),k("design:type",Function),k("design:paramtypes",[String]),k("design:returntype",Promise)],oe.prototype,"cancel",null);oe=Ae([Uh("jobs"),$(0,Ou(z)),$(1,Ou(we)),k("design:paramtypes",[z,we])],oe)});import{z as te}from"zod";var eo,to,Ni=l(()=>{"use strict";C();eo=te.discriminatedUnion("mode",[te.object({mode:te.literal("view"),viewId:te.string().min(1)}),te.object({mode:te.literal("manual"),subjectType:re,subjectIds:te.array(te.string().min(1))})]),to=te.object({workflowId:te.string().min(1),selection:eo,triggeredBy:te.enum(["schedule","view_bulk","multiselect"]),notificationOverride:fr.optional(),inputValues:te.record(te.string(),te.unknown())})});import{Body as Wh,Controller as Hh,Get as Ui,Inject as Ji,Param as Mi,Post as Du,Query as Li}from"@nestjs/common";import"zod";var Mt,M,Ce,Le,Fu=l(()=>{"use strict";Ln();Br();pr();R();ne();Bi();Ni();Mt=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},M=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},Ce=function(r,e){return function(t,n){e(t,n,r)}},Le=class{batches;jobs;runner;constructor(e,t,n){this.batches=e,this.jobs=t,this.runner=n}async list(e,t,n){let{limit:o,offset:i}=Kn(t,n),s=await this.batches.list(e?{workflowId:e}:{});return Gn(s,o,i)}async get(e){let t=await this.batches.get(e);if(!t)throw new y(`JobBatch not found: ${e}`);return t}async listJobs(e){if(!await this.batches.get(e))throw new y(`JobBatch not found: ${e}`);return this.jobs.list({batchId:e})}async launch(e){let t=await this.runner.launch({workflowId:e.workflowId,selection:e.selection,triggeredBy:e.triggeredBy,...e.notificationOverride?{notificationOverride:e.notificationOverride}:{},inputValues:e.inputValues});return"resolvedSubjects"in t&&"jobIds"in t?{kind:"batch",batch:t}:{kind:"job",job:t}}async cancel(e){return this.runner.cancelBatch(e)}};Mt([Ui(),Ce(0,Li("workflowId")),Ce(1,Li("limit")),Ce(2,Li("offset")),M("design:type",Function),M("design:paramtypes",[String,String,String]),M("design:returntype",Promise)],Le.prototype,"list",null);Mt([Ui(":id"),Ce(0,Mi("id")),M("design:type",Function),M("design:paramtypes",[String]),M("design:returntype",Promise)],Le.prototype,"get",null);Mt([Ui(":id/jobs"),Ce(0,Mi("id")),M("design:type",Function),M("design:paramtypes",[String]),M("design:returntype",Promise)],Le.prototype,"listJobs",null);Mt([Du(),Ce(0,Wh(new v(to))),M("design:type",Function),M("design:paramtypes",[Object]),M("design:returntype",Promise)],Le.prototype,"launch",null);Mt([Du(":id/cancel"),Ce(0,Mi("id")),M("design:type",Function),M("design:paramtypes",[String]),M("design:returntype",Promise)],Le.prototype,"cancel",null);Le=Mt([Hh("batches"),Ce(0,Ji(se)),Ce(1,Ji(z)),Ce(2,Ji(we)),M("design:paramtypes",[se,z,we])],Le)});import{Body as Nu,Controller as Vh,Delete as Kh,Get as Ju,HttpCode as Gh,Inject as zh,Param as Wi,Patch as Qh,Post as Xh,Query as Yh}from"@nestjs/common";var Wt,W,Pt,Ue,Lu=l(()=>{"use strict";C();Fo();R();ne();Wt=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},W=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},Pt=function(r,e){return function(t,n){e(t,n,r)}},Ue=class{schedules;constructor(e){this.schedules=e}async list(e){if(e==null||e==="")return this.schedules.list();if(e!=="true"&&e!=="false")throw new h(`Invalid enabled filter: ${e}`);return this.schedules.list({enabled:e==="true"})}async get(e){let t=await this.schedules.get(e);if(!t)throw new y(`Schedule not found: ${e}`);return t}async create(e){return this.schedules.create(e)}async update(e,t){let n=await this.schedules.update(e,t);if(!n)throw new y(`Schedule not found: ${e}`);return n}async remove(e){if(!await this.schedules.delete(e))throw new y(`Schedule not found: ${e}`)}};Wt([Ju(),Pt(0,Yh("enabled")),W("design:type",Function),W("design:paramtypes",[String]),W("design:returntype",Promise)],Ue.prototype,"list",null);Wt([Ju(":id"),Pt(0,Wi("id")),W("design:type",Function),W("design:paramtypes",[String]),W("design:returntype",Promise)],Ue.prototype,"get",null);Wt([Xh(),Pt(0,Nu(new v(Ot))),W("design:type",Function),W("design:paramtypes",[Object]),W("design:returntype",Promise)],Ue.prototype,"create",null);Wt([Qh(":id"),Pt(0,Wi("id")),Pt(1,Nu(new v(Ot.partial().omit({id:!0})))),W("design:type",Function),W("design:paramtypes",[String,Object]),W("design:returntype",Promise)],Ue.prototype,"update",null);Wt([Kh(":id"),Gh(204),Pt(0,Wi("id")),W("design:type",Function),W("design:paramtypes",[String]),W("design:returntype",Promise)],Ue.prototype,"remove",null);Ue=Wt([Vh("schedules"),Pt(0,zh($e)),W("design:paramtypes",[$e])],Ue)});import{Controller as Zh,Inject as ey,Query as Uu,Sse as ty}from"@nestjs/common";import{Observable as Wu}from"rxjs";var Mu,ro,Hi,vr,Hu=l(()=>{"use strict";Tn();Mu=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},ro=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},Hi=function(r,e){return function(t,n){e(t,n,r)}},vr=class{events;constructor(e){this.events=e}stream(e,t){return new Wu(n=>{let o=this.events.subscribe(i=>{let s=i;e!=null&&e!==""&&(!("jobId"in s)||s.jobId!==e)||t!=null&&t!==""&&(!("batchId"in s)||s.batchId!==t)||n.next({data:s})});return()=>{o()}})}};Mu([ty(),Hi(0,Uu("jobId")),Hi(1,Uu("batchId")),ro("design:type",Function),ro("design:paramtypes",[String,String]),ro("design:returntype",Wu)],vr.prototype,"stream",null);vr=Mu([Zh("events"),Hi(0,ey(ye)),ro("design:paramtypes",[ye])],vr)});import{extendZodWithOpenApi as ry}from"@asteasolutions/zod-to-openapi";import{z as ny}from"zod";var Vu=l(()=>{"use strict";ry(ny)});import{z as Ku}from"zod";var no,Vi=l(()=>{"use strict";no=Ku.object({value:Ku.string().min(1)})});import{z as xe}from"zod";var HE,oy,Gu,zu=l(()=>{"use strict";HE=xe.object({path:xe.string().optional(),mode:xe.enum(["directories","files"]).optional(),extensions:xe.string().optional()}),oy=xe.object({name:xe.string().min(1),path:xe.string().min(1),isDirectory:xe.boolean()}),Gu=xe.object({path:xe.string().min(1),entries:xe.array(oy)})});import{z as d}from"zod";function jy(r){let e=d.toJSONSchema(r),{$schema:t,...n}=e;return n}function Xu(r){let e=(t,n)=>r.registerComponent("schemas",t,jy(n)).ref;return{WorkflowDefinition:e("WorkflowDefinition",ht),WorkflowDefinitionInput:e("WorkflowDefinitionInput",tt),UpdateWorkflowBody:e("UpdateWorkflowBody",yy),SubjectView:e("SubjectView",Jr),CreateSubjectViewBody:e("CreateSubjectViewBody",Lr),ReorderViewsBody:e("ReorderViewsBody",Mr),UpdateViewBody:e("UpdateViewBody",wy),WorkflowShortcut:e("WorkflowShortcut",Xr),CreateWorkflowShortcutBody:e("CreateWorkflowShortcutBody",Yr),UpdateWorkflowShortcutBody:e("UpdateWorkflowShortcutBody",Zr),ReorderShortcutsBody:e("ReorderShortcutsBody",en),Schedule:e("Schedule",Ot),UpdateScheduleBody:e("UpdateScheduleBody",by),EngineSettings:e("EngineSettings",rn),UpdateSettingsBody:e("UpdateSettingsBody",xy),SettingsPatchResponse:e("SettingsPatchResponse",Iy),ProviderInstanceConfig:e("ProviderInstanceConfig",tn),CreateProviderInstanceBody:e("CreateProviderInstanceBody",on),UpdateProviderInstanceBody:e("UpdateProviderInstanceBody",sn),ProviderInstanceMutationResponse:e("ProviderInstanceMutationResponse",vy),SetSecretBody:e("SetSecretBody",no),CreateJobBody:e("CreateJobBody",zn),ResumeJobBody:e("ResumeJobBody",Qn),LatestBySubjectBody:e("LatestBySubjectBody",Xn),LatestBySubjectResponse:e("LatestBySubjectResponse",Sy),LaunchBody:e("LaunchBody",to),Job:e("Job",Ki),JobBatch:e("JobBatch",Qu),LaunchResponse:e("LaunchResponse",dy),HealthResponse:e("HealthResponse",py),ProviderStatus:e("ProviderStatus",fy),QueryTemplate:e("QueryTemplate",ea),ProviderActionDescriptor:e("ProviderActionDescriptor",ta),PreviewModelsBody:e("PreviewModelsBody",an),PreviewModel:e("PreviewModel",Wa),ResolveQueryTemplateBody:e("ResolveQueryTemplateBody",Nr),ResolveQueryTemplateResponse:e("ResolveQueryTemplateResponse",ra),ErrorResponse:e("ErrorResponse",my),EngineEvent:e("EngineEvent",hy),Subject:e("Subject",oo),WorkflowLibraryEntry:e("WorkflowLibraryEntry",gy),ContextFile:e("ContextFile",Hr),CreateContextFileBody:e("CreateContextFileBody",Vr),UpdateContextFileBody:e("UpdateContextFileBody",Kr),LocalRepository:e("LocalRepository",Gr),CreateLocalRepositoryBody:e("CreateLocalRepositoryBody",zr),UpdateLocalRepositoryBody:e("UpdateLocalRepositoryBody",Qr),DeleteWorktreesBody:e("DeleteWorktreesBody",Yn),FilesystemBrowseResult:e("FilesystemBrowseResult",Gu)}}var iy,sy,ay,cy,oo,uy,ly,Ki,Qu,dy,py,fy,my,hy,yy,gy,wy,by,Sy,xy,vy,Iy,_,Gi,zi=l(()=>{"use strict";Vu();C();Di();Ni();Vi();zu();iy=d.enum(["pending","planning","waiting_for_human","waiting_for_children","implementing","testing","completed","failed","cancelled"]),sy=d.object({subjectType:d.literal("ticket"),id:d.string(),source:d.string().min(1),title:d.string(),description:d.string().optional(),status:d.string(),assignee:d.string().optional(),url:d.string().optional(),raw:d.record(d.string(),d.unknown()).optional()}),ay=d.object({subjectType:d.literal("pull_request"),id:d.string(),source:d.string().min(1),title:d.string(),description:d.string().optional(),sourceBranch:d.string(),targetBranch:d.string(),author:d.string().optional(),url:d.string().optional(),raw:d.record(d.string(),d.unknown()).optional()}),cy=d.object({subjectType:d.literal("documentation"),id:d.string(),source:d.string().min(1),title:d.string(),url:d.string().optional(),raw:d.record(d.string(),d.unknown()).optional()}),oo=d.discriminatedUnion("subjectType",[sy,ay,cy]),uy=d.discriminatedUnion("mode",[d.object({mode:d.literal("single"),subject:oo}),d.object({mode:d.literal("collection"),subjects:d.array(oo)})]),ly=d.object({id:d.string(),stepDefinitionId:d.string(),type:d.string(),status:d.enum(["pending","running","waiting_for_children","completed","failed","skipped"]),startedAt:d.string().optional(),completedAt:d.string().optional(),output:d.unknown().optional(),error:d.string().optional(),childJobIds:d.array(d.string()).optional(),iterations:d.array(d.object({index:d.number().int(),stepExecutions:d.array(d.record(d.string(),d.unknown())),startedAt:d.string(),completedAt:d.string().optional()})).optional()}),Ki=d.object({id:d.string(),workflowId:d.string(),status:iy,subjectContext:uy.optional(),selection:eo.optional(),batchId:d.string().optional(),parentJobId:d.string().optional(),parentStepExecutionId:d.string().optional(),fanOutIndex:d.number().int().optional(),retryOf:d.string().optional(),workflowSnapshot:ht.optional(),context:d.record(d.string(),d.unknown()),worktreePath:d.string().optional(),branch:d.string().optional(),worktreeDeletedAt:d.string().optional(),currentStepId:d.string().optional(),currentStepExecutionId:d.string().optional(),stepHistory:d.array(ly),createdAt:d.string(),updatedAt:d.string(),completedAt:d.string().optional()}),Qu=d.object({id:d.string(),workflowId:d.string(),selection:eo,resolvedSubjects:d.array(oo),jobIds:d.array(d.string()),status:d.enum(["running","completed","completed_with_issues","failed","cancelled"]),triggeredBy:d.enum(["schedule","view_bulk","multiselect"]),scheduleId:d.string().optional(),notificationOverride:fr.optional(),notificationSent:d.boolean(),createdAt:d.string(),completedAt:d.string().optional()}),dy=d.discriminatedUnion("kind",[d.object({kind:d.literal("job"),job:Ki}),d.object({kind:d.literal("batch"),batch:Qu})]),py=d.object({ok:d.boolean(),service:d.string(),timestamp:d.string()}),fy=d.object({providerId:d.string(),secretKey:d.string(),configured:d.boolean()}),my=d.object({error:d.string()}),hy=d.object({type:d.string(),timestamp:d.string()}).passthrough(),yy=tt,gy=d.object({id:d.string().min(1),source:d.enum(["example","community","official"]),name:d.string().min(1),description:d.string(),workflowDefinition:tt}),wy=Ur,by=Ot.partial().omit({id:!0}),Sy=d.record(d.string(),Ki.nullable()),xy=nn,vy=d.object({settings:rn,restartRequired:d.literal(!0)}),Iy=d.object({settings:rn,restartRequired:d.boolean()}),_=d.object({id:d.string().min(1)}),Gi=d.object({limit:d.string().optional().openapi({description:"Max items to return (default 50)"}),offset:d.string().optional().openapi({description:"Number of items to skip (default 0)"})})});import{z as I}from"zod";function g(r,e){return{description:e,content:{"application/json":{schema:r}}}}function B(r){return{type:"array",items:r}}function w(r,...e){let t={400:"Validation error",404:"Resource not found",409:"Conflict"};return Object.fromEntries(e.map(n=>[String(n),g(r.ErrorResponse,t[n]??"Error")]))}function Yu(r,e){r.registerPath({method:"get",path:"/health",tags:["Health"],summary:"Health check",responses:{200:g(e.HealthResponse,"Service is healthy")}}),r.registerPath({method:"get",path:"/workflows",tags:["Workflows"],summary:"List workflow definitions",request:{query:I.object({subjectHandling:I.enum(["per-subject","collection"]).optional()})},responses:{200:g(B(e.WorkflowDefinition),"Workflow definitions"),...w(e,400)}}),r.registerPath({method:"get",path:"/workflows/{id}",tags:["Workflows"],summary:"Get a workflow definition",request:{params:_},responses:{200:g(e.WorkflowDefinition,"Workflow definition"),...w(e,404)}}),r.registerPath({method:"post",path:"/workflows",tags:["Workflows"],summary:"Create a workflow definition",request:{body:{required:!0,content:{"application/json":{schema:e.WorkflowDefinitionInput}}}},responses:{201:g(e.WorkflowDefinition,"Created workflow definition"),...w(e,400)}}),r.registerPath({method:"patch",path:"/workflows/{id}",tags:["Workflows"],summary:"Update a workflow definition",request:{params:_,body:{required:!0,content:{"application/json":{schema:e.UpdateWorkflowBody}}}},responses:{200:g(e.WorkflowDefinition,"Updated workflow definition"),...w(e,400,404)}}),r.registerPath({method:"delete",path:"/workflows/{id}",tags:["Workflows"],summary:"Delete a workflow definition",description:"Deletes the live workflow definition. Running Jobs keep executing from the snapshot captured at Job creation.",request:{params:_},responses:{204:{description:"Workflow deleted"},...w(e,404)}}),r.registerPath({method:"get",path:"/workflow-library",tags:["Workflow Library"],summary:"List bundled workflow library entries",responses:{200:g(B(e.WorkflowLibraryEntry),"Workflow library entries")}}),r.registerPath({method:"post",path:"/workflow-library/{id}/add",tags:["Workflow Library"],summary:"Copy a library entry into the workspace as a new workflow",request:{params:_},responses:{201:g(e.WorkflowDefinition,"Created workflow definition"),...w(e,400,404)}}),r.registerPath({method:"get",path:"/views",tags:["Views"],summary:"List subject views",request:{query:I.object({subjectType:re.optional()})},responses:{200:g(B(e.SubjectView),"Subject views"),...w(e,400)}}),r.registerPath({method:"get",path:"/views/{id}",tags:["Views"],summary:"Get a subject view",request:{params:_},responses:{200:g(e.SubjectView,"Subject view"),...w(e,404)}}),r.registerPath({method:"get",path:"/views/{id}/subjects",tags:["Views"],summary:"Preview subjects matching a view",description:"Live provider query for the View's saved filter. Same resolution path as launch() for { mode: 'view' }. Does not create Jobs or snapshots.",request:{params:_},responses:{200:g(B(e.Subject),"Matching subjects"),...w(e,404,400)}}),r.registerPath({method:"patch",path:"/views/reorder",tags:["Views"],summary:"Reorder views within a subject type group",request:{body:{required:!0,content:{"application/json":{schema:e.ReorderViewsBody}}}},responses:{200:g(B(e.SubjectView),"Reordered views for the subject type"),...w(e,400)}}),r.registerPath({method:"post",path:"/views",tags:["Views"],summary:"Create a subject view",request:{body:{required:!0,content:{"application/json":{schema:e.CreateSubjectViewBody}}}},responses:{201:g(e.SubjectView,"Created subject view"),...w(e,400)}}),r.registerPath({method:"patch",path:"/views/{id}",tags:["Views"],summary:"Update a subject view",request:{params:_,body:{required:!0,content:{"application/json":{schema:e.UpdateViewBody}}}},responses:{200:g(e.SubjectView,"Updated subject view"),...w(e,400,404)}}),r.registerPath({method:"delete",path:"/views/{id}",tags:["Views"],summary:"Delete a subject view",request:{params:_},responses:{204:{description:"Subject view deleted"},...w(e,404)}}),r.registerPath({method:"get",path:"/jobs",tags:["Jobs"],summary:"List jobs",request:{query:Gi.extend({workflowId:I.string().optional(),status:I.enum(["pending","planning","waiting_for_human","waiting_for_children","implementing","testing","completed","failed","cancelled"]).optional(),batchId:I.string().optional(),parentJobId:I.string().optional(),topLevelOnly:I.enum(["true","false"]).optional().openapi({description:"When true, exclude jobs that belong to a batch or a parent (sub_workflow) job"}),terminal:I.enum(["true","false"]).optional().openapi({description:"When true, only completed/failed/cancelled jobs. When false, only in-progress jobs. Omitted: no terminality filter."}),liveWorktree:I.enum(["true","false"]).optional().openapi({description:"When true, only jobs with a worktreePath that has not been deleted from the management page."})})},responses:{200:g(B(e.Job),"Jobs"),...w(e,400)}}),r.registerPath({method:"post",path:"/jobs/delete-worktrees",tags:["Jobs"],summary:"Delete live worktree folders for terminal jobs",request:{body:{required:!0,content:{"application/json":{schema:e.DeleteWorktreesBody}}}},responses:{200:g(B(e.Job),"Jobs after worktree deletion"),...w(e,400,404,409)}}),r.registerPath({method:"get",path:"/jobs/{id}",tags:["Jobs"],summary:"Get a job",request:{params:_},responses:{200:g(e.Job,"Job"),...w(e,404)}}),r.registerPath({method:"post",path:"/jobs",tags:["Jobs"],summary:"Start a single job",request:{body:{required:!0,content:{"application/json":{schema:e.CreateJobBody}}}},responses:{201:g(e.Job,"Started job"),...w(e,400,404)}}),r.registerPath({method:"post",path:"/jobs/latest-by-subject",tags:["Jobs"],summary:"Latest job per subject for a workflow",request:{body:{required:!0,content:{"application/json":{schema:e.LatestBySubjectBody}}}},responses:{200:g(e.LatestBySubjectResponse,"Latest job keyed by subject id"),...w(e,400)}}),r.registerPath({method:"post",path:"/jobs/{id}/resume",tags:["Jobs"],summary:"Resume a job waiting for human input",request:{params:_,body:{required:!0,content:{"application/json":{schema:e.ResumeJobBody}}}},responses:{200:g(e.Job,"Resumed job"),...w(e,400,404,409)}}),r.registerPath({method:"post",path:"/jobs/{id}/retry",tags:["Jobs"],summary:"Retry a failed job as a new linked job",request:{params:_},responses:{200:g(e.Job,"Retry job"),...w(e,404,409)}}),r.registerPath({method:"post",path:"/jobs/{id}/retry-step",tags:["Jobs"],summary:"Retry the failed step of a job in place",request:{params:_},responses:{200:g(e.Job,"Job after retrying the failed step"),...w(e,404,409)}}),r.registerPath({method:"post",path:"/jobs/{id}/cancel",tags:["Jobs"],summary:"Cancel a non-terminal job",request:{params:_},responses:{200:g(e.Job,"Cancelled job"),...w(e,404,409)}}),r.registerPath({method:"get",path:"/batches",tags:["Batches"],summary:"List job batches",request:{query:Gi.extend({workflowId:I.string().optional()})},responses:{200:g(B(e.JobBatch),"Job batches")}}),r.registerPath({method:"get",path:"/batches/{id}",tags:["Batches"],summary:"Get a job batch",request:{params:_},responses:{200:g(e.JobBatch,"Job batch"),...w(e,404)}}),r.registerPath({method:"get",path:"/batches/{id}/jobs",tags:["Batches"],summary:"List jobs in a batch",request:{params:_},responses:{200:g(B(e.Job),"Jobs in the batch"),...w(e,404)}}),r.registerPath({method:"post",path:"/batches",tags:["Batches"],summary:"Launch a per-subject batch or collection run",description:"Resolves subject selection and starts a JobBatch for per-subject workflows (even for one subject) or a single Job for collection workflows.",request:{body:{required:!0,content:{"application/json":{schema:e.LaunchBody}}}},responses:{201:g(e.LaunchResponse,"Launch result"),...w(e,400,404)}}),r.registerPath({method:"post",path:"/batches/{id}/cancel",tags:["Batches"],summary:"Cancel a running job batch",request:{params:_},responses:{200:g(e.JobBatch,"Cancelled batch"),...w(e,404,409)}}),r.registerPath({method:"get",path:"/workflow-shortcuts",tags:["Workflow shortcuts"],summary:"List workflow shortcuts",responses:{200:g(B(e.WorkflowShortcut),"Workflow shortcuts")}}),r.registerPath({method:"get",path:"/workflow-shortcuts/{id}",tags:["Workflow shortcuts"],summary:"Get a workflow shortcut",request:{params:_},responses:{200:g(e.WorkflowShortcut,"Workflow shortcut"),...w(e,404)}}),r.registerPath({method:"post",path:"/workflow-shortcuts",tags:["Workflow shortcuts"],summary:"Create a workflow shortcut",request:{body:{required:!0,content:{"application/json":{schema:e.CreateWorkflowShortcutBody}}}},responses:{201:g(e.WorkflowShortcut,"Created workflow shortcut"),...w(e,400,404)}}),r.registerPath({method:"patch",path:"/workflow-shortcuts/reorder",tags:["Workflow shortcuts"],summary:"Reorder workflow shortcuts",request:{body:{required:!0,content:{"application/json":{schema:e.ReorderShortcutsBody}}}},responses:{200:g(B(e.WorkflowShortcut),"Reordered workflow shortcuts"),...w(e,400)}}),r.registerPath({method:"patch",path:"/workflow-shortcuts/{id}",tags:["Workflow shortcuts"],summary:"Update a workflow shortcut",request:{params:_,body:{required:!0,content:{"application/json":{schema:e.UpdateWorkflowShortcutBody}}}},responses:{200:g(e.WorkflowShortcut,"Updated workflow shortcut"),...w(e,400,404)}}),r.registerPath({method:"delete",path:"/workflow-shortcuts/{id}",tags:["Workflow shortcuts"],summary:"Delete a workflow shortcut",request:{params:_},responses:{204:{description:"Workflow shortcut deleted"},...w(e,404)}}),r.registerPath({method:"get",path:"/context-files",tags:["Context Files"],summary:"List context files",responses:{200:g(B(e.ContextFile),"Context files")}}),r.registerPath({method:"get",path:"/context-files/{id}",tags:["Context Files"],summary:"Get a context file",request:{params:_},responses:{200:g(e.ContextFile,"Context file"),...w(e,404)}}),r.registerPath({method:"post",path:"/context-files",tags:["Context Files"],summary:"Create a context file",request:{body:{required:!0,content:{"application/json":{schema:e.CreateContextFileBody}}}},responses:{201:g(e.ContextFile,"Created context file"),...w(e,400)}}),r.registerPath({method:"patch",path:"/context-files/{id}",tags:["Context Files"],summary:"Update a context file",request:{params:_,body:{required:!0,content:{"application/json":{schema:e.UpdateContextFileBody}}}},responses:{200:g(e.ContextFile,"Updated context file"),...w(e,400,404)}}),r.registerPath({method:"delete",path:"/context-files/{id}",tags:["Context Files"],summary:"Delete a context file",request:{params:_},responses:{204:{description:"Context file deleted"},...w(e,404)}}),r.registerPath({method:"get",path:"/local-repositories",tags:["Local Repositories"],summary:"List local repositories",responses:{200:g(B(e.LocalRepository),"Local repositories")}}),r.registerPath({method:"get",path:"/local-repositories/{id}",tags:["Local Repositories"],summary:"Get a local repository",request:{params:_},responses:{200:g(e.LocalRepository,"Local repository"),...w(e,404)}}),r.registerPath({method:"post",path:"/local-repositories",tags:["Local Repositories"],summary:"Create a local repository",request:{body:{required:!0,content:{"application/json":{schema:e.CreateLocalRepositoryBody}}}},responses:{201:g(e.LocalRepository,"Created local repository"),...w(e,400)}}),r.registerPath({method:"patch",path:"/local-repositories/{id}",tags:["Local Repositories"],summary:"Update a local repository",request:{params:_,body:{required:!0,content:{"application/json":{schema:e.UpdateLocalRepositoryBody}}}},responses:{200:g(e.LocalRepository,"Updated local repository"),...w(e,400,404)}}),r.registerPath({method:"delete",path:"/local-repositories/{id}",tags:["Local Repositories"],summary:"Delete a local repository",request:{params:_},responses:{204:{description:"Local repository deleted"},...w(e,404)}}),r.registerPath({method:"get",path:"/filesystem/browse",tags:["Filesystem"],summary:"List a host directory",request:{query:I.object({path:I.string().optional(),mode:I.enum(["directories","files"]).optional(),extensions:I.string().optional()})},responses:{200:g(e.FilesystemBrowseResult,"Directory listing"),...w(e,400)}}),r.registerPath({method:"get",path:"/schedules",tags:["Schedules"],summary:"List schedules",request:{query:I.object({enabled:I.enum(["true","false"]).optional()})},responses:{200:g(B(e.Schedule),"Schedules"),...w(e,400)}}),r.registerPath({method:"get",path:"/schedules/{id}",tags:["Schedules"],summary:"Get a schedule",request:{params:_},responses:{200:g(e.Schedule,"Schedule"),...w(e,404)}}),r.registerPath({method:"post",path:"/schedules",tags:["Schedules"],summary:"Create a schedule",description:"CRUD only \u2014 creating or enabling a schedule does not cause it to fire yet.",request:{body:{required:!0,content:{"application/json":{schema:e.Schedule}}}},responses:{201:g(e.Schedule,"Created schedule"),...w(e,400)}}),r.registerPath({method:"patch",path:"/schedules/{id}",tags:["Schedules"],summary:"Update a schedule",request:{params:_,body:{required:!0,content:{"application/json":{schema:e.UpdateScheduleBody}}}},responses:{200:g(e.Schedule,"Updated schedule"),...w(e,400,404)}}),r.registerPath({method:"delete",path:"/schedules/{id}",tags:["Schedules"],summary:"Delete a schedule",request:{params:_},responses:{204:{description:"Schedule deleted"},...w(e,404)}}),r.registerPath({method:"get",path:"/providers/status",tags:["Providers"],summary:"Provider secret configuration status",description:"Reports whether each known provider API key is set. Returns key *names* only \u2014 never secret values.",responses:{200:g(B(e.ProviderStatus),"Provider configuration status")}}),r.registerPath({method:"post",path:"/providers/preview-models",tags:["Providers"],summary:"Preview models available to an agent API key",description:"Lookup only \u2014 does not persist settings or secrets. Send apiKey to try a typed key before save, or instanceId to use the already-stored key (never echoed).",request:{body:{required:!0,content:{"application/json":{schema:e.PreviewModelsBody}}}},responses:{200:g(B(e.PreviewModel),"Models available to the key"),...w(e,400,404)}}),r.registerPath({method:"get",path:"/providers/{providerId}/query-templates",tags:["Providers"],summary:"List query templates for a provider",description:"Named, pre-built query templates owned by the provider. Providers with none yet (e.g. documentation) return an empty list. The client never constructs `query` itself \u2014 it submits templateId + params to the resolve endpoint.",request:{params:I.object({providerId:I.string().min(1)})},responses:{200:g(B(e.QueryTemplate),"Query templates")}}),r.registerPath({method:"get",path:"/providers/{providerId}/actions",tags:["Providers"],summary:"List extended actions for a provider",description:"Opt-in capabilities beyond the portable five ProviderAction operations. Providers that do not implement ExtendedActionProvider return an empty list \u2014 that is a normal, expected case, not an error.",request:{params:I.object({providerId:I.string().min(1)})},responses:{200:g(B(e.ProviderActionDescriptor),"Extended actions")}}),r.registerPath({method:"post",path:"/providers/{providerId}/query-templates/{templateId}/resolve",tags:["Providers"],summary:"Resolve a query template to a concrete query",description:"Provider-specific query-shape knowledge stays server-side. Returns the `query` object to store on a SubjectView, along with template provenance the client attaches separately.",request:{params:I.object({providerId:I.string().min(1),templateId:I.string().min(1)}),body:{required:!0,content:{"application/json":{schema:e.ResolveQueryTemplateBody}}}},responses:{200:g(e.ResolveQueryTemplateResponse,"Resolved query"),...w(e,400,404)}}),r.registerPath({method:"get",path:"/settings",tags:["Settings"],summary:"Get engine settings",description:"Persisted provider configuration. Never includes secret values \u2014 those live in SecretStore.",responses:{200:g(e.EngineSettings,"Current engine settings")}}),r.registerPath({method:"patch",path:"/settings",tags:["Settings"],summary:"Update engine settings",description:"Partial merge. restartRequired is true when providerInstances is in the patch (instance bindings are boot-time). Changing defaultAgentInstanceId takes effect on the next agent step with no restart.",request:{body:{required:!0,content:{"application/json":{schema:e.UpdateSettingsBody}}}},responses:{200:g(e.SettingsPatchResponse,"Updated settings"),...w(e,400)}}),r.registerPath({method:"get",path:"/provider-instances",tags:["Settings"],summary:"List provider instances",responses:{200:g(B(e.ProviderInstanceConfig),"Configured provider instances")}}),r.registerPath({method:"post",path:"/provider-instances",tags:["Settings"],summary:"Create a provider instance",description:"Persists the instance. restartRequired is always true \u2014 bindings are boot-time. For agent instances, defaultAgent atomically replaces EngineSettings.defaultAgentInstanceId in the same write.",request:{body:{required:!0,content:{"application/json":{schema:e.CreateProviderInstanceBody}}}},responses:{201:g(e.ProviderInstanceMutationResponse,"Created instance settings"),...w(e,400,409)}}),r.registerPath({method:"get",path:"/provider-instances/{id}",tags:["Settings"],summary:"Get a provider instance",request:{params:I.object({id:I.string().min(1)})},responses:{200:g(e.ProviderInstanceConfig,"Provider instance"),...w(e,404)}}),r.registerPath({method:"patch",path:"/provider-instances/{id}",tags:["Settings"],summary:"Update a provider instance",request:{params:I.object({id:I.string().min(1)}),body:{required:!0,content:{"application/json":{schema:e.UpdateProviderInstanceBody}}}},responses:{200:g(e.ProviderInstanceMutationResponse,"Updated instance settings"),...w(e,400,404)}}),r.registerPath({method:"delete",path:"/provider-instances/{id}",tags:["Settings"],summary:"Delete a provider instance",request:{params:I.object({id:I.string().min(1)})},responses:{200:g(e.ProviderInstanceMutationResponse,"Updated settings after delete"),...w(e,404)}}),r.registerPath({method:"post",path:"/secrets/{key}",tags:["Settings"],summary:"Store a secret",description:"Writes to SecretStore. The response never includes the secret value.",request:{params:I.object({key:I.string().min(1)}),body:{required:!0,content:{"application/json":{schema:e.SetSecretBody}}}},responses:{204:{description:"Secret stored"},...w(e,400)}}),r.registerPath({method:"get",path:"/events",tags:["Events"],summary:"Subscribe to engine events (SSE)",description:"Server-Sent Events stream. Each event `data` field is a JSON EngineEvent. Optionally filter by jobId and/or batchId.",request:{query:I.object({jobId:I.string().optional(),batchId:I.string().optional()})},responses:{200:{description:"SSE stream of engine events",content:{"text/event-stream":{schema:e.EngineEvent}}}}})}var Zu=l(()=>{"use strict";C();zi()});import{OpenAPIRegistry as _y,OpenApiGeneratorV31 as Ey}from"@asteasolutions/zod-to-openapi";function el(){if(io)return io;let r=new _y,e=Xu(r);return Yu(r,e),io=new Ey(r.definitions).generateDocument({openapi:"3.1.0",info:{title:"Knoflows Engine API",version:"0.1.0",description:"REST API for workflow definitions, jobs, batches, schedules, views, and live events."},servers:[{url:"/api"}]}),io}var io,tl=l(()=>{"use strict";zi();Zu()});import{Controller as Py,Get as Ry,Header as ky}from"@nestjs/common";var rl,Qi,Ir,nl=l(()=>{"use strict";tl();rl=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Qi=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},Ir=class{getOpenApiDocument(){return el()}};rl([Ry("openapi.json"),ky("Content-Type","application/json"),Qi("design:type",Function),Qi("design:paramtypes",[]),Qi("design:returntype",void 0)],Ir.prototype,"getOpenApiDocument",null);Ir=rl([Py()],Ir)});import{Controller as Ay,Get as Xi,Inject as so,Param as ao,Post as ol,Body as il,HttpCode as sl}from"@nestjs/common";var Ht,H,Te,Me,al=l(()=>{"use strict";Ko();oi();ii();ci();C();ne();Ht=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},H=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},Te=function(r,e){return function(t,n){e(t,n,r)}},Me=class{providerStatus;queryTemplates;extendedActions;previewModels;constructor(e,t,n,o){this.providerStatus=e,this.queryTemplates=t,this.extendedActions=n,this.previewModels=o}async status(){return this.providerStatus.list()}previewAvailableModels(e){return this.previewModels.preview(e)}listQueryTemplates(e){return this.queryTemplates.list(e)}listExtendedActions(e){return this.extendedActions.list(e)}async resolveQueryTemplate(e,t,n){return{query:await this.queryTemplates.resolve(e,t,n.params)}}};Ht([Xi("status"),H("design:type",Function),H("design:paramtypes",[]),H("design:returntype",Promise)],Me.prototype,"status",null);Ht([ol("preview-models"),sl(200),Te(0,il(new v(an))),H("design:type",Function),H("design:paramtypes",[Object]),H("design:returntype",Promise)],Me.prototype,"previewAvailableModels",null);Ht([Xi(":providerId/query-templates"),Te(0,ao("providerId")),H("design:type",Function),H("design:paramtypes",[String]),H("design:returntype",Promise)],Me.prototype,"listQueryTemplates",null);Ht([Xi(":providerId/actions"),Te(0,ao("providerId")),H("design:type",Function),H("design:paramtypes",[String]),H("design:returntype",Promise)],Me.prototype,"listExtendedActions",null);Ht([ol(":providerId/query-templates/:templateId/resolve"),sl(200),Te(0,ao("providerId")),Te(1,ao("templateId")),Te(2,il(new v(Nr))),H("design:type",Function),H("design:paramtypes",[String,String,Object]),H("design:returntype",Promise)],Me.prototype,"resolveQueryTemplate",null);Me=Ht([Ay("providers"),Te(0,so(rt)),Te(1,so(nt)),Te(2,so(ot)),Te(3,so(it)),H("design:paramtypes",[rt,nt,ot,it])],Me)});import{Body as Cy,Controller as Ty,Get as Oy,Inject as $y,Patch as qy}from"@nestjs/common";var Yi,Rt,cl,Vt,ul=l(()=>{"use strict";C();Pe();ne();Yi=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Rt=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},cl=function(r,e){return function(t,n){e(t,n,r)}},Vt=class{settings;constructor(e){this.settings=e}get(){return this.settings.get()}async update(e){return{settings:await this.settings.update(e),restartRequired:Qa(e)}}};Yi([Oy(),Rt("design:type",Function),Rt("design:paramtypes",[]),Rt("design:returntype",Promise)],Vt.prototype,"get",null);Yi([qy(),cl(0,Cy(new v(nn))),Rt("design:type",Function),Rt("design:paramtypes",[Object]),Rt("design:returntype",Promise)],Vt.prototype,"update",null);Vt=Yi([Ty("settings"),cl(0,$y(P)),Rt("design:paramtypes",[P])],Vt)});function Zi(r){let{current:e,instance:t,defaultAgent:n,isCreate:o}=r;return $t(t)?n===!0?t.id:n===!1?e===t.id?null:e??null:o&&!e?t.id:e??null:e===t.id?null:e??null}function ll(r){let{defaultAgent:e,...t}=r;return t}var dl=l(()=>{"use strict";C()});import{Body as pl,Controller as By,Delete as Dy,Get as fl,HttpCode as Fy,Inject as Ny,Param as es,Patch as Jy,Post as Ly}from"@nestjs/common";var Gt,V,Kt,We,ml=l(()=>{"use strict";C();Pe();R();ne();dl();Gt=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},V=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},Kt=function(r,e){return function(t,n){e(t,n,r)}},We=class{settings;constructor(e){this.settings=e}async list(){return(await this.settings.get()).providerInstances??[]}async get(e){let t=(await this.settings.get()).providerInstances?.find(n=>n.id===e);if(!t)throw new y(`Provider instance not found: ${e}`);return t}async create(e){let t=ll(e),n=await this.settings.get(),o=[...n.providerInstances??[]];if(o.some(s=>s.id===t.id))throw new J(`Provider instance already exists: ${t.id}`);return o.push(t),{settings:await this.settings.update({providerInstances:o,defaultAgentInstanceId:Zi({current:n.defaultAgentInstanceId,instance:t,defaultAgent:e.defaultAgent,isCreate:!0})}),restartRequired:!0}}async update(e,t){let n=await this.settings.get(),o=[...n.providerInstances??[]],i=o.findIndex(c=>c.id===e);if(i<0)throw new y(`Provider instance not found: ${e}`);let a={...o[i],...t.displayName!=null?{displayName:t.displayName}:{},...t.config!=null?{config:t.config}:{},...t.secretKey!=null?{secretKey:t.secretKey}:{}};return t.expiresOn!==void 0&&(t.expiresOn?a.expiresOn=t.expiresOn:delete a.expiresOn),o[i]=a,{settings:await this.settings.update({providerInstances:o,defaultAgentInstanceId:Zi({current:n.defaultAgentInstanceId,instance:a,defaultAgent:t.defaultAgent,isCreate:!1})}),restartRequired:!0}}async remove(e){let t=await this.settings.get(),n=(t.providerInstances??[]).filter(s=>s.id!==e);if(n.length===(t.providerInstances??[]).length)throw new y(`Provider instance not found: ${e}`);let o=t.defaultAgentInstanceId===e?null:t.defaultAgentInstanceId??null;return{settings:await this.settings.update({providerInstances:n,defaultAgentInstanceId:o}),restartRequired:!0}}};Gt([fl(),V("design:type",Function),V("design:paramtypes",[]),V("design:returntype",Promise)],We.prototype,"list",null);Gt([fl(":id"),Kt(0,es("id")),V("design:type",Function),V("design:paramtypes",[String]),V("design:returntype",Promise)],We.prototype,"get",null);Gt([Ly(),Kt(0,pl(new v(on))),V("design:type",Function),V("design:paramtypes",[Object]),V("design:returntype",Promise)],We.prototype,"create",null);Gt([Jy(":id"),Kt(0,es("id")),Kt(1,pl(new v(sn))),V("design:type",Function),V("design:paramtypes",[String,Object]),V("design:returntype",Promise)],We.prototype,"update",null);Gt([Dy(":id"),Fy(200),Kt(0,es("id")),V("design:type",Function),V("design:paramtypes",[String]),V("design:returntype",Promise)],We.prototype,"remove",null);We=Gt([By("provider-instances"),Kt(0,Ny(P)),V("design:paramtypes",[P])],We)});import{Body as Uy,Controller as My,HttpCode as Wy,Inject as Hy,Param as Vy,Post as Ky}from"@nestjs/common";var hl,co,ts,jr,yl=l(()=>{"use strict";Oe();R();ne();Vi();hl=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},co=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},ts=function(r,e){return function(t,n){e(t,n,r)}},jr=class{secrets;constructor(e){this.secrets=e}async set(e,t){let n=e.trim();if(!n)throw new h("Secret key must not be empty");await this.secrets.set(n,t.value)}};hl([Ky(":key"),Wy(204),ts(0,Vy("key")),ts(1,Uy(new v(no))),co("design:type",Function),co("design:paramtypes",[String,Object]),co("design:returntype",Promise)],jr.prototype,"set",null);jr=hl([My("secrets"),ts(0,Hy(fe)),co("design:paramtypes",[Function])],jr)});import{readFile as Gy}from"node:fs/promises";async function rs(r){try{await Gy(r,"utf8")}catch(e){let t=e instanceof Error?e.message:String(e);throw new h(`Cannot read context file at '${r}': ${t}`)}}var gl=l(()=>{"use strict";R()});import{Body as wl,Controller as zy,Delete as Qy,Get as bl,HttpCode as Xy,Inject as Yy,Param as ns,Patch as Zy,Post as eg}from"@nestjs/common";import{randomUUID as tg}from"node:crypto";var Qt,K,zt,He,Sl=l(()=>{"use strict";C();Dr();R();ne();gl();Qt=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},K=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},zt=function(r,e){return function(t,n){e(t,n,r)}},He=class{files;constructor(e){this.files=e}async list(){return this.files.list()}async get(e){let t=await this.files.get(e);if(!t)throw new y(`Context file not found: ${e}`);return t}async create(e){return await rs(e.path),this.files.create({id:e.id??tg(),name:e.name,description:e.description,tier:e.tier,path:e.path})}async update(e,t){let n=await this.files.get(e);if(!n)throw new y(`Context file not found: ${e}`);let o=t.path??n.path;await rs(o);let i=await this.files.update(e,t);if(!i)throw new y(`Context file not found: ${e}`);return i}async remove(e){if(!await this.files.delete(e))throw new y(`Context file not found: ${e}`)}};Qt([bl(),K("design:type",Function),K("design:paramtypes",[]),K("design:returntype",Promise)],He.prototype,"list",null);Qt([bl(":id"),zt(0,ns("id")),K("design:type",Function),K("design:paramtypes",[String]),K("design:returntype",Promise)],He.prototype,"get",null);Qt([eg(),zt(0,wl(new v(Vr))),K("design:type",Function),K("design:paramtypes",[Object]),K("design:returntype",Promise)],He.prototype,"create",null);Qt([Zy(":id"),zt(0,ns("id")),zt(1,wl(new v(Kr))),K("design:type",Function),K("design:paramtypes",[String,Object]),K("design:returntype",Promise)],He.prototype,"update",null);Qt([Qy(":id"),Xy(204),zt(0,ns("id")),K("design:type",Function),K("design:paramtypes",[String]),K("design:returntype",Promise)],He.prototype,"remove",null);He=Qt([zy("context-files"),zt(0,Yy(ae)),K("design:paramtypes",[ae])],He)});import{execFile as rg}from"node:child_process";import{stat as ng}from"node:fs/promises";import{resolve as os}from"node:path";import{promisify as og}from"node:util";async function is(r){let e=os(r);try{if((await ig("git",["-C",e,"rev-parse","--is-inside-work-tree"],{encoding:"utf8",windowsHide:!0})).stdout.trim()!=="true")throw new Error("not a work tree")}catch(t){let n=t instanceof Error?t.message:String(t);throw new h(`'${r}' is not a git repository: ${n}`)}}async function ss(r,e){let t=os(r),n=os(e?.trim()?e.trim():Dn(t));if(Fn(t,n))throw new h(`Worktree base '${n}' must not be inside the repository at '${t}'`);try{if(!(await ng(n)).isDirectory())throw new h(`Worktree base '${n}' exists and is not a directory`)}catch(o){if(o instanceof h)throw o}}var ig,xl=l(()=>{"use strict";R();xi();ig=og(rg)});import{Body as vl,Controller as sg,Delete as ag,Get as Il,HttpCode as cg,Inject as ug,Param as as,Patch as lg,Post as dg}from"@nestjs/common";import{randomUUID as pg}from"node:crypto";var Yt,G,Xt,Ve,jl=l(()=>{"use strict";C();Fr();R();ne();xl();Yt=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},G=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},Xt=function(r,e){return function(t,n){e(t,n,r)}},Ve=class{repos;constructor(e){this.repos=e}async list(){return this.repos.list()}async get(e){let t=await this.repos.get(e);if(!t)throw new y(`Local repository not found: ${e}`);return t}async create(e){return await is(e.localPath),await ss(e.localPath,e.worktreeBasePath),this.repos.create({id:e.id??pg(),name:e.name,localPath:e.localPath,...e.worktreeBasePath?{worktreeBasePath:e.worktreeBasePath}:{}})}async update(e,t){let n=await this.repos.get(e);if(!n)throw new y(`Local repository not found: ${e}`);let o=t.localPath??n.localPath,i=t.worktreeBasePath!==void 0?t.worktreeBasePath:n.worktreeBasePath;await is(o),await ss(o,i);let s=await this.repos.update(e,t);if(!s)throw new y(`Local repository not found: ${e}`);return s}async remove(e){if(!await this.repos.delete(e))throw new y(`Local repository not found: ${e}`)}};Yt([Il(),G("design:type",Function),G("design:paramtypes",[]),G("design:returntype",Promise)],Ve.prototype,"list",null);Yt([Il(":id"),Xt(0,as("id")),G("design:type",Function),G("design:paramtypes",[String]),G("design:returntype",Promise)],Ve.prototype,"get",null);Yt([dg(),Xt(0,vl(new v(zr))),G("design:type",Function),G("design:paramtypes",[Object]),G("design:returntype",Promise)],Ve.prototype,"create",null);Yt([lg(":id"),Xt(0,as("id")),Xt(1,vl(new v(Qr))),G("design:type",Function),G("design:paramtypes",[String,Object]),G("design:returntype",Promise)],Ve.prototype,"update",null);Yt([ag(":id"),cg(204),Xt(0,as("id")),G("design:type",Function),G("design:paramtypes",[String]),G("design:returntype",Promise)],Ve.prototype,"remove",null);Ve=Yt([sg("local-repositories"),Xt(0,ug(ce)),G("design:paramtypes",[ce])],Ve)});import{readdir as fg,stat as mg}from"node:fs/promises";import{homedir as hg}from"node:os";import{join as yg,resolve as gg}from"node:path";async function _l(r,e={}){let t=r?.trim()?r.trim():hg(),n=gg(t),o;try{o=await mg(n)}catch(s){throw new h(`Cannot browse '${n}': ${s instanceof Error?s.message:String(s)}`)}if(!o.isDirectory())throw new h(`Cannot browse '${n}': not a directory`);let i;try{i=(await fg(n,{encoding:"utf8",withFileTypes:!0})).filter(a=>a.name!=="."&&a.name!=="..").map(a=>({name:a.name,path:yg(n,a.name),isDirectory:a.isDirectory()})).filter(a=>wg(a,e)).sort((a,u)=>a.isDirectory!==u.isDirectory?a.isDirectory?-1:1:a.name.localeCompare(u.name))}catch(s){throw new h(`Cannot browse '${n}': ${s instanceof Error?s.message:String(s)}`)}return{path:n,entries:i}}function El(r){if(r==null||r.trim()==="")return;let e=r.split(",").map(t=>Rl(t)).filter(t=>t!=null);return e.length>0?e:void 0}function Pl(r){if(!(r==null||r.trim()==="")){if(r==="directories"||r==="files")return r;throw new h(`Invalid browse mode '${r}'`)}}function wg(r,e){if(e.mode==="directories")return r.isDirectory;if(r.isDirectory)return!0;let t=e.extensions?.map(o=>Rl(o)).filter(Boolean);if(!t?.length)return!0;let n=r.name.toLowerCase();return t.some(o=>n.endsWith(o))}function Rl(r){let e=r.trim().toLowerCase();if(e.length!==0)return e.startsWith(".")?e:`.${e}`}var kl=l(()=>{"use strict";R()});import{Controller as bg,Get as Sg,Query as ls}from"@nestjs/common";var Al,cs,us,_r,Cl=l(()=>{"use strict";kl();Al=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},cs=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},us=function(r,e){return function(t,n){e(t,n,r)}},_r=class{async browse(e,t,n){return _l(e,{mode:Pl(t),extensions:El(n)})}};Al([Sg("browse"),us(0,ls("path")),us(1,ls("mode")),us(2,ls("extensions")),cs("design:type",Function),cs("design:paramtypes",[String,String,String]),cs("design:returntype",Promise)],_r.prototype,"browse",null);_r=Al([bg("filesystem")],_r)});import{Module as vg}from"@nestjs/common";import{APP_FILTER as Ig}from"@nestjs/core";var xg,uo,Tl=l(()=>{"use strict";mr();_i();On();du();wu();Eu();Ru();Tu();Bu();Fu();Lu();Hu();nl();al();ul();ml();yl();Sl();jl();Cl();Cn();Io();xg=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},uo=class{};uo=xg([vg({imports:[Re,Jt,at,st,At],controllers:[Ne,Ut,Se,ke,oe,Le,Ue,vr,Ir,Me,Vt,We,jr,He,Ve,_r],providers:[{provide:Ig,useClass:Un}]})],uo)});import{Module as _g}from"@nestjs/common";var jg,lo,Ol=l(()=>{"use strict";ms();hs();ys();Cn();On();mr();_i();Tl();jg=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},lo=class{};lo=jg([_g({imports:[Er,Pr,st,at,Re,Jt,uo],controllers:[Zt]})],lo)});import{apiReference as Eg}from"@scalar/nestjs-api-reference";function $l(r){r.use("/api/docs",Eg({url:"/api/openapi.json",pageTitle:"Knoflows Engine API"}))}var ql=l(()=>{"use strict"});import{createServer as Pg}from"node:net";function Bl(r){return typeof r=="object"&&r!==null&&"code"in r&&r.code==="EADDRINUSE"}async function ds(r,e=20){for(let t=0;t<e;t+=1){let n=r+t;if(await Rg(n))return n}throw new Error(`No free port found in ${r}\u2013${r+e-1}`)}function Rg(r){return new Promise(e=>{let t=Pg();t.once("error",()=>{e(!1)}),t.once("listening",()=>{t.close(()=>e(!0))}),t.listen(r)})}var Dl=l(()=>{"use strict"});import{Catch as Cg,HttpStatus as po,NotFoundException as Tg}from"@nestjs/common";import{existsSync as Fl,statSync as Og}from"node:fs";import{extname as Nl,join as ps,normalize as $g,relative as qg,sep as Bg}from"node:path";function Jl(r){return(e,t,n)=>{if(e.method!=="GET"&&e.method!=="HEAD"){n();return}if((e.path??"").startsWith("/api")){n();return}let o=Dg(e.path??"/");if(o){let i=ps(r,o);if(Fg(r,i)){t.sendFile(o,{root:r},s=>{s&&n()});return}}if(Ll(e)){Ul(t,r,i=>{i&&!t.headersSent&&t.status(po.NOT_FOUND).end()});return}t.status(po.NOT_FOUND).end()}}function Ll(r){if(r.method!=="GET"&&r.method!=="HEAD")return!1;let e=r.path??"";if(e.startsWith("/api"))return!1;let t=Nl(e);return!(t&&t!==".html")}function Ul(r,e,t){r.sendFile("index.html",{root:e},t)}function Dg(r){if(r==="/"||r==="")return"index.html";let e=$g(r.replace(/^\/+/,""));return!e||e==="."||e.startsWith("..")||!Nl(e)?null:e}function Fg(r,e){if(!Fl(e))return!1;try{if(!Og(e).isFile())return!1}catch{return!1}let t=qg(r,e);return t!==""&&!t.startsWith(`..${Bg}`)&&!t.startsWith("..")}function Ml(r){return ps(r,"index.html")}var kg,Ag,fo,Wl=l(()=>{"use strict";kg=function(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i},Ag=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},fo=class{staticRoot;constructor(e){this.staticRoot=e}catch(e,t){let n=t.switchToHttp(),o=n.getRequest(),i=n.getResponse();if(Ll(o)&&Fl(ps(this.staticRoot,"index.html"))){Ul(i,this.staticRoot,u=>{u&&!i.headersSent&&i.status(po.NOT_FOUND).json({statusCode:po.NOT_FOUND,message:"UI index.html could not be served"})});return}let s=e.getStatus(),a=e.getResponse();i.status(s).json(typeof a=="string"?{statusCode:s,message:a}:a)}};fo=kg([Cg(Tg),Ag("design:paramtypes",[String])],fo)});import{existsSync as Ng}from"node:fs";import{dirname as Jg,join as mo}from"node:path";import{fileURLToPath as Lg}from"node:url";function Hl(){let r=Jg(Lg(import.meta.url)),e=[mo(r,"../static"),mo(r,"../../static"),mo(r,"static")];for(let t of e)if(Ng(mo(t,"index.html")))return t;return null}var Vl=l(()=>{"use strict"});var Vg={};import"reflect-metadata";import{existsSync as Ug}from"node:fs";import{Logger as Mg}from"@nestjs/common";import{NestFactory as Wg}from"@nestjs/core";async function Hg(){let r=await Wg.create(lo);r.enableCors(),r.setGlobalPrefix("api"),$l(r);let e=Hl(),t=e?Ml(e):null;e&&t&&Ug(t)?(ho.log(`Serving UI from ${e}`),r.use(Jl(e)),r.useGlobalFilters(new fo(e))):ho.warn("No UI found (static/index.html missing). GET / will 404; /api still works. Rebuild with `npm run build:release` before publishing.");let n=Number(process.env.PORT??3e3);if(!Number.isInteger(n)||n<1||n>65535)throw new Error(`Invalid PORT: ${process.env.PORT}`);let o=await ds(n);for(let i=0;i<5;i+=1)try{await r.listen(o),o!==n?ho.warn(`Port ${n} is in use; listening on ${o} instead`):ho.log(`Listening on http://localhost:${o}`);return}catch(s){if(!Bl(s))throw s;o=await ds(o+1)}throw new Error(`Could not bind a free port starting at ${n}`)}var ho,Kl=l(()=>{"use strict";Ol();ql();Dl();Wl();Vl();ho=new Mg("Bootstrap");Hg()});import{readFileSync as Kg}from"node:fs";function Gg(){let r=Kg(new URL("../package.json",import.meta.url),"utf8");return JSON.parse(r).version}var yo=process.argv.slice(2);yo.includes("--version")||yo.includes("-v")?console.log(Gg()):yo.includes("--help")||yo.includes("-h")?console.log(["Usage: knoflows [options]","","Starts the knoflows engine (REST API + bundled web client).","","Options:"," -v, --version Print the engine version and exit"," -h, --help Print this message and exit","","Environment:"," PORT Preferred HTTP port (default 3000). If taken, the next free port is used."," KNO_SQLITE_PATH SQLite file path, or :memory: for an ephemeral database"].join(`
|
|
34
|
+
`)):await Promise.resolve().then(()=>(Kl(),Vg));
|