@knoflows/engine 0.1.0-alpha.10 → 0.1.0-alpha.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist/engine.js +12 -12
  2. package/package.json +1 -1
  3. package/static/assets/i18n/en.json +18 -0
  4. package/static/assets/i18n/es.json +18 -0
  5. package/static/{chunk-BFkZ796p.js → chunk-03U2wfYJ.js} +1 -1
  6. package/static/{chunk-jct1_zOr.js → chunk-6rAx_awr.js} +1 -1
  7. package/static/{chunk-3mppll1n.js → chunk-BGEuPXoV.js} +1 -1
  8. package/static/{chunk-hZzW00VR.js → chunk-BLVF0pVH.js} +1 -1
  9. package/static/{chunk-CJRNatUw.js → chunk-BfWasMGf.js} +1 -1
  10. package/static/{chunk-B8MrNxxk.js → chunk-Bvpl_AF9.js} +1 -1
  11. package/static/{chunk-CEcbtdnK.js → chunk-C2eCmH-q.js} +1 -1
  12. package/static/{chunk-DjibVmY7.js → chunk-CAjGF9LB.js} +1 -1
  13. package/static/{chunk-BAc0DRm8.js → chunk-CT8olEiD.js} +1 -1
  14. package/static/chunk-CUsAuTTX.js +1 -0
  15. package/static/chunk-CgXl_TS9.js +1 -0
  16. package/static/{chunk-BbcTWKT2.js → chunk-CqGGDoIh.js} +1 -1
  17. package/static/{chunk-tYnBYi0l.js → chunk-Crj-4pl_.js} +1 -1
  18. package/static/{chunk-DNOjVPY0.js → chunk-Ct30cLzT.js} +1 -1
  19. package/static/{chunk-wbdetocK.js → chunk-Cw0wBuEr.js} +3 -3
  20. package/static/chunk-CxICQyU8.js +1 -0
  21. package/static/{chunk-B2hO-qT3.js → chunk-DGHakffX.js} +1 -1
  22. package/static/chunk-DIakbH9x.js +1 -0
  23. package/static/{chunk-BjZIiizu.js → chunk-DIntI-KR.js} +1 -1
  24. package/static/{chunk-W5GAgssE.js → chunk-DPWE5cPY.js} +1 -1
  25. package/static/{chunk-Cd8F2jeN.js → chunk-DU6MKU0d.js} +1 -1
  26. package/static/{chunk-Cf_xd8ER.js → chunk-DUR5PalP.js} +1 -1
  27. package/static/{chunk-2KSNHCgb.js → chunk-DWLHaSHg.js} +1 -1
  28. package/static/{chunk-CDWIMt6y.js → chunk-D_R_EFd2.js} +1 -1
  29. package/static/{chunk-Ojn34cvU.js → chunk-DinAvqzQ.js} +1 -1
  30. package/static/{chunk-CWbxWv5I.js → chunk-DlsGU_Dk.js} +1 -1
  31. package/static/{chunk-DblClAqu.js → chunk-DwA32gts.js} +1 -1
  32. package/static/{chunk-DQnMulwi.js → chunk-IOVwMLns.js} +1 -1
  33. package/static/{chunk-cHfOiAJm.js → chunk-L_FnMwpH.js} +1 -1
  34. package/static/{chunk-XLpSkczx.js → chunk-NAyA7aWR.js} +1 -1
  35. package/static/{chunk-eSxb3-OU.js → chunk-TNH96m0D.js} +1 -1
  36. package/static/{chunk-CJDp11v5.js → chunk-Vz5kd858.js} +1 -1
  37. package/static/{chunk-BUuwGTt7.js → chunk-dUlsh7QS.js} +6 -6
  38. package/static/{chunk-A4AkMf2s.js → chunk-h3oyPsBC.js} +1 -1
  39. package/static/{chunk-BVw7xkK9.js → chunk-hKpVm95g.js} +1 -1
  40. package/static/chunk-qYK5KaAK.js +1 -0
  41. package/static/{chunk-mzyds3TS.js → chunk-qwukwlIj.js} +1 -1
  42. package/static/{chunk-CgqRVtSF.js → chunk-vPa4eOmU.js} +1 -1
  43. package/static/index.html +1 -1
  44. package/static/{main-MNK6ZYDO.js → main-HV5WDK2F.js} +1 -1
  45. package/static/chunk-6BQlxALO.js +0 -1
  46. package/static/chunk-BNOYZq-b.js +0 -1
  47. package/static/chunk-BhGgxvgu.js +0 -1
  48. package/static/chunk-D6YfO72h.js +0 -1
  49. 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:ar(a[1]),type:a[2]})}return{name:ar(e[1]),createSql:`${r};`,columns:o}}function kp(r){let e=r.match(/^ALTER TABLE\s+(`[^`]+`|"[^"]+"|\w+)\s+ADD(?:\s+COLUMN)?\s+(`[^`]+`|"[^"]+"|\w+)\s+(\w+)/i);return e?{table:ar(e[1]),name:ar(e[2]),type:e[3]}:null}function Ap(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:ar(e[1]),sql:`${t};`}}function ar(r){return r.replace(/^["`]|["`]$/g,"")}function sr(r){return`\`${r.replace(/`/g,"")}\``}function Cp(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(!cr(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 ${sr(s.name)} ADD COLUMN ${sr(u.name)} ${u.type}`),a.add(u.name),o.push(`${s.name}.${u.name}`))}for(let s of e.alterColumns)cr(r,s.table)&&($r(r,s.table).includes(s.name)||(r.exec(`ALTER TABLE ${sr(s.table)} ADD COLUMN ${sr(s.name)} ${s.type}`),o.push(`${s.table}.${s.name}`)));for(let s of e.indexes)qs(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 cr(r,e){return r.prepare("SELECT 1 AS ok FROM sqlite_master WHERE type = 'table' AND name = ?").get(e)!=null}function qs(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(${sr(e)})`).all().map(n=>n.name)}function Bs(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(!cr(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)qs(r,o.name)||t.push(`missing index '${o.name}'`);return t}function $o(r,e){let t=Bs(r,e);if(t.length>0)throw new he(`schema is incomplete after migrate (${t.join("; ")})`)}function Ds(r){let e=new Set($r(r,dt));if(!e.has("hash"))throw new he(`migrations table '${dt}' is missing required columns`);if(!e.has("name"))throw new he(`migrations table '${dt}' is missing column 'name' \u2014 journal is from an interrupted upgrade`);return r.prepare(`SELECT name, hash FROM ${dt}`).all()}function Tp(r,e){let t=new Map(e.map(n=>[n.name,n]));for(let n of Ds(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 Op(r,e){r.exec(`
4
- CREATE TABLE IF NOT EXISTS ${dt} (
2
+ var l=(r,e)=>()=>(r&&(e=r(r=0)),e);import{Controller as Ul,Get as Ml}from"@nestjs/common";var ps,go,Xt,ds=l(()=>{"use strict";ps=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)},Xt=class{getHealth(){return{ok:!0,service:"kno-engine",timestamp:new Date().toISOString()}}};ps([Ml(),go("design:type",Function),go("design:paramtypes",[]),go("design:returntype",Object)],Xt.prototype,"getHealth",null);Xt=ps([Ul("health")],Xt)});import{Module as Hl}from"@nestjs/common";var Wl,Pr,fs=l(()=>{"use strict";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},Pr=class{};Pr=Wl([Hl({})],Pr)});import{Module as Kl}from"@nestjs/common";var Vl,Er,ms=l(()=>{"use strict";Vl=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=Vl([Kl({})],Er)});var Yt,wo=l(()=>{"use strict";Yt=Symbol("NOTIFICATION_PROVIDER")});var Rr,hs=l(()=>{"use strict";Rr=class{async send(e){console.log("[notification]",JSON.stringify(e))}}});import{existsSync as ys}from"node:fs";import{dirname as Gl,join as Zt}from"node:path";import{fileURLToPath as zl}from"node:url";function er(){let r=Gl(zl(import.meta.url)),e=Zt(r,"../data"),t=Zt(r,"../../data");return ys(Zt(e,"kno.db"))?e:ys(Zt(t,"kno.db"))?t:e}function gs(){return Zt(er(),"kno.db")}var kr=l(()=>{"use strict"});import{createCipheriv as Ql,createDecipheriv as Xl,randomBytes as ws}from"node:crypto";import{mkdir as bs,readFile as Ss,writeFile as xs}from"node:fs/promises";import{join as So}from"node:path";function Et(r){return`kno.${r}.apiKey`}function tp(r){return So(r,"secrets")}function js(r){return new xo(tp(r.dataDir),r.keyring)}function rp(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,vs,Yl,bo,Zl,ep,xo,fe,Oe=l(()=>{"use strict";Ar="kno-flows";vs="aes-256-gcm",Yl=12,bo=32,Zl="master.key",ep="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 rp(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 Ss(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 bs(this.secretsDir,{recursive:!0}),await xs(this.storePath(),JSON.stringify(e,null,2),{encoding:"utf8",mode:384})}async encrypt(e){let t=await this.loadOrCreateMasterKey(),n=ws(Yl),o=Ql(vs,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=Xl(vs,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 bs(this.secretsDir,{recursive:!0});let e=this.masterKeyPath();try{let n=(await Ss(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=ws(bo);return await xs(e,t.toString("hex"),{encoding:"utf8",mode:384}),this.masterKey=t,t}storePath(){return So(this.secretsDir,ep)}masterKeyPath(){return So(this.secretsDir,Zl)}};fe=Symbol("SECRET_STORE")});import{Module as op}from"@nestjs/common";import{mkdirSync as ip}from"node:fs";var np,Is,Rt,jo=l(()=>{"use strict";kr();Oe();np=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=er();ip(Is,{recursive:!0});Rt=class{};Rt=np([op({providers:[{provide:fe,useFactory:()=>js({dataDir:Is})}],exports:[fe]})],Rt)});import{index as sp,sqliteTable as ap,text as ve}from"drizzle-orm/sqlite-core";var Ke,Io=l(()=>{"use strict";Ke=ap("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=>[sp("workflow_definitions_subject_handling_idx").on(r.subjectHandling)])});import{index as _s,integer as cp,sqliteTable as up,text as Ge}from"drizzle-orm/sqlite-core";var je,_o=l(()=>{"use strict";je=up("subject_views",{id:Ge("id").primaryKey(),name:Ge("name").notNull(),subjectType:Ge("subject_type").$type().notNull(),workflowId:Ge("workflow_id").notNull(),query:Ge("query",{mode:"json"}).$type().notNull(),description:Ge("description"),queryTemplate:Ge("query_template",{mode:"json"}).$type(),providerInstanceId:Ge("provider_instance_id").notNull().default(""),order:cp("order").notNull().default(0)},r=>[_s("subject_views_subject_type_idx").on(r.subjectType),_s("subject_views_subject_type_order_idx").on(r.subjectType,r.order)])});import{index as Ps,integer as lp,sqliteTable as pp,text as Ie}from"drizzle-orm/sqlite-core";var ze,Cr=l(()=>{"use strict";ze=pp("job_batches",{id:Ie("id").primaryKey(),workflowId:Ie("workflow_id").notNull(),selection:Ie("selection",{mode:"json"}).$type().notNull(),resolvedSubjects:Ie("resolved_subjects",{mode:"json"}).$type().notNull(),status:Ie("status",{enum:["running","completed","completed_with_issues","failed","cancelled"]}).notNull(),triggeredBy:Ie("triggered_by",{enum:["schedule","view_bulk","multiselect"]}).notNull(),scheduleId:Ie("schedule_id"),notificationOverride:Ie("notification_override",{mode:"json"}).$type(),notificationSent:lp("notification_sent",{mode:"boolean"}).notNull(),createdAt:Ie("created_at").notNull(),completedAt:Ie("completed_at")},r=>[Ps("job_batches_workflow_id_idx").on(r.workflowId),Ps("job_batches_schedule_id_idx").on(r.scheduleId)])});import{index as Tr,integer as dp,sqliteTable as fp,text as D}from"drizzle-orm/sqlite-core";var L,tr=l(()=>{"use strict";Cr();L=fp("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(()=>ze.id),parentJobId:D("parent_job_id"),parentStepExecutionId:D("parent_step_execution_id"),fanOutIndex:dp("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 Es,sqliteTable as mp,text as rr}from"drizzle-orm/sqlite-core";var _e,Po=l(()=>{"use strict";tr();_e=mp("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=>[Es("job_subjects_job_id_idx").on(r.jobId),Es("job_subjects_subject_lookup_idx").on(r.subjectType,r.subjectId)])});import{index as Rs,integer as hp,sqliteTable as yp,text as me}from"drizzle-orm/sqlite-core";var dt,Eo=l(()=>{"use strict";tr();dt=yp("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(()=>dt.id),iterationIndex:hp("iteration_index")},r=>[Rs("job_step_executions_job_id_idx").on(r.jobId),Rs("job_step_executions_parent_idx").on(r.parentStepExecutionId)])});import{index as gp,integer as wp,sqliteTable as bp,text as Qe}from"drizzle-orm/sqlite-core";var Xe,Ro=l(()=>{"use strict";Xe=bp("schedules",{id:Qe("id").primaryKey(),viewId:Qe("view_id").notNull(),triggerType:Qe("trigger_type",{enum:["cron"]}).notNull(),cadence:Qe("cadence").notNull(),notificationOverride:Qe("notification_override",{mode:"json"}).$type(),missedFirePolicy:Qe("missed_fire_policy",{enum:["skip","catch_up"]}).notNull(),enabled:wp("enabled",{mode:"boolean"}).notNull(),lastFiredAt:Qe("last_fired_at"),createdAt:Qe("created_at").notNull()},r=>[gp("schedules_enabled_idx").on(r.enabled)])});import{integer as Sp,sqliteTable as xp,text as nr}from"drizzle-orm/sqlite-core";var Pe,ko=l(()=>{"use strict";Pe=xp("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:Sp("order").notNull().default(0)})});import{sqliteTable as vp,text as or}from"drizzle-orm/sqlite-core";var Ye,Ao=l(()=>{"use strict";Ye=vp("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 jp,text as Or}from"drizzle-orm/sqlite-core";var Ze,Co=l(()=>{"use strict";Ze=jp("local_repositories",{id:Or("id").primaryKey(),name:Or("name").notNull(),localPath:Or("local_path").notNull(),worktreeBasePath:Or("worktree_base_path")})});import{sqliteTable as Ip,text as ks}from"drizzle-orm/sqlite-core";var ir,kt,To=l(()=>{"use strict";ir="default",kt=Ip("settings",{id:ks("id").primaryKey(),data:ks("data",{mode:"json"}).$type().notNull()})});import{defineRelations as _p}from"drizzle-orm";var Pp,As,Cs=l(()=>{"use strict";Io();_o();tr();Po();Eo();Cr();Ro();ko();Ao();Co();To();Pp={workflowDefinitions:Ke,subjectViews:je,jobs:L,jobSubjects:_e,jobStepExecutions:dt,jobBatches:ze,schedules:Xe,workflowShortcuts:Pe,contextFiles:Ye,localRepositories:Ze,settings:kt},As=_p(Pp,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 Ep}from"drizzle-orm/node-sqlite";import{DatabaseSync as Xw}from"node:sqlite";function Ts(r){return r.exec("PRAGMA foreign_keys = ON;"),Ep({client:r,relations:As})}var Os=l(()=>{"use strict";Cs()});import{existsSync as $s,readdirSync as Rp}from"node:fs";import{dirname as kp,join as Oo}from"node:path";import{fileURLToPath as Ap}from"node:url";function qs(){let r=kp(Ap(import.meta.url)),e=[Oo(r,"persistence/migrations"),Oo(r,"migrations")];for(let t of e)if(Cp(t))return t;throw new Error(`Engine SQL migrations not found. Looked in: ${e.join(", ")}`)}function Cp(r){return $s(r)?Rp(r,{withFileTypes:!0}).some(e=>e.isDirectory()&&$s(Oo(r,e.name,"migration.sql"))):!1}var Bs=l(()=>{"use strict"});import{migrate as Ds}from"drizzle-orm/node-sqlite/migrator";import{readMigrationFiles as Tp}from"drizzle-orm/migrator";function qo(r,e,t={}){let n=t.log??(()=>{}),o=qs(),i=Tp({migrationsFolder:o});if(i.length===0)throw new he(`No SQL migrations in ${o}`);let s=$p(i),a=cr(r,ft),c=Op.filter(S=>cr(r,S));if(!a&&c.length===0){Ds(e,{migrationsFolder:o}),$o(r,s);return}if(!a){Fp(r,s,n),Jp(r,i),$o(r,s);return}Np(r,i);let u=Ns(r,s),d=Js(r);if(d.length===0&&c.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&&u.length>0)throw new he(`migrations journal is present but the schema is incomplete (${u.join("; ")}) \u2014 treating this as an interrupted update`);Ds(e,{migrationsFolder:o}),$o(r,s)}function $p(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=qp(s);if(a){e.push(a);continue}let c=Bp(s);if(c){n.push(c);continue}let u=Dp(s);u&&t.push(u)}return{tables:e,indexes:t,alterColumns:n}}function qp(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:ar(a[1]),type:a[2]})}return{name:ar(e[1]),createSql:`${r};`,columns:o}}function Bp(r){let e=r.match(/^ALTER TABLE\s+(`[^`]+`|"[^"]+"|\w+)\s+ADD(?:\s+COLUMN)?\s+(`[^`]+`|"[^"]+"|\w+)\s+(\w+)/i);return e?{table:ar(e[1]),name:ar(e[2]),type:e[3]}:null}function Dp(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:ar(e[1]),sql:`${t};`}}function ar(r){return r.replace(/^["`]|["`]$/g,"")}function sr(r){return`\`${r.replace(/`/g,"")}\``}function Fp(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(!cr(r,s.name)){r.exec(s.createSql),n.push(s.name);continue}let a=new Set($r(r,s.name));for(let c of s.columns)a.has(c.name)||(r.exec(`ALTER TABLE ${sr(s.name)} ADD COLUMN ${sr(c.name)} ${c.type}`),a.add(c.name),o.push(`${s.name}.${c.name}`))}for(let s of e.alterColumns)cr(r,s.table)&&($r(r,s.table).includes(s.name)||(r.exec(`ALTER TABLE ${sr(s.table)} ADD COLUMN ${sr(s.name)} ${s.type}`),o.push(`${s.table}.${s.name}`)));for(let s of e.indexes)Fs(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 cr(r,e){return r.prepare("SELECT 1 AS ok FROM sqlite_master WHERE type = 'table' AND name = ?").get(e)!=null}function Fs(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(${sr(e)})`).all().map(n=>n.name)}function Ns(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(!cr(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)Fs(r,o.name)||t.push(`missing index '${o.name}'`);return t}function $o(r,e){let t=Ns(r,e);if(t.length>0)throw new he(`schema is incomplete after migrate (${t.join("; ")})`)}function Js(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 Np(r,e){let t=new Map(e.map(n=>[n.name,n]));for(let n of Js(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 Jp(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,Op,Ls=l(()=>{"use strict";Bs();ft="__drizzle_migrations",he=class extends Error{constructor(e){super(`Engine database migration failed: ${e}`),this.name="DatabaseMigrationError"}},Op=["workflow_definitions","subject_views","job_batches","jobs","job_subjects","job_step_executions","schedules","workflow_shortcuts","context_files","local_repositories","settings"]});import{Injectable as Mp,Logger as Wp}from"@nestjs/common";import{mkdirSync as Hp}from"node:fs";import{dirname as Vp}from"node:path";import{DatabaseSync as Us}from"node:sqlite";var Lp,Up,Bo,X,Ms=l(()=>{"use strict";kr();Os();Ls();Lp=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},Up=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},X=Bo=class{logger=new Wp(Bo.name);sqlite;db;constructor(){let t=process.env.KNO_SQLITE_PATH??gs();t===":memory:"?this.sqlite=new Us(":memory:"):(Hp(Vp(t),{recursive:!0}),this.sqlite=new Us(t)),this.db=Ts(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=Lp([Mp(),Up("design:paramtypes",[])],X)});import{Injectable as zp}from"@nestjs/common";import{eq as Ws}from"drizzle-orm";var Kp,Gp,O,mt=l(()=>{"use strict";Io();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},Gp=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(Ke).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(Ke).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(Ws(Ke.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(Ke).where(Ws(Ke.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=Kp([zp(),Gp("design:paramtypes",[Object,Function])],O)});import{Injectable as Yp}from"@nestjs/common";import{eq as Do}from"drizzle-orm";var Qp,Xp,Hs,ie,qr=l(()=>{"use strict";_o();Qp=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},Xp=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},Hs=["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(je).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(je).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(je.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(je).set({order:o}).where(Do(je.id,e[o]));return this.list({subjectType:n})}async delete(e){return await this.get(e)?(await this.db.delete(je).where(Do(je.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=Hs.indexOf(t.subjectType)-Hs.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=Qp([Yp(),Xp("design:paramtypes",[Object])],ie)});import{Injectable as td}from"@nestjs/common";import{and as rd,desc as nd,eq as ur,inArray as od}from"drizzle-orm";import{randomUUID as id}from"node:crypto";function sd(r){return r?r.mode==="single"?[r.subject]:r.subjects:[]}function ad(r){if(r.length!==0)return r.length===1?{mode:"single",subject:r[0]}:{mode:"collection",subjects:r}}function Ks(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(...Ks(r,s.stepExecutions,i.id,s.index));return o}function cd(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 c=s.get(a.iterationIndex)??[];c.push(a),s.set(a.iterationIndex,c)}if(s.size!==0)return[...s.entries()].sort(([a],[c])=>a-c).map(([a,c])=>{let u=c.map(d=>Vs(d,t(d.id)));return{index:a,stepExecutions:u,startedAt:ud(u),...pd(u)?{completedAt:ld(u)}:{}}})};return(e.get(null)??[]).filter(o=>o.iterationIndex==null).map(o=>Vs(o,t(o.id)))}function Vs(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 ud(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 ld(r){return r.map(t=>t.completedAt).filter(t=>t!=null).reduce((t,n)=>t>n?t:n)}function pd(r){return r.length>0&&r.every(e=>e.completedAt!=null)}function dd(r){return r==="completed"||r==="failed"||r==="cancelled"}var Zp,ed,z,lr=l(()=>{"use strict";tr();Po();Eo();Zp=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},ed=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=>dd(s.status)===e.terminal)}async latestBySubject(e,t){let n={};for(let u of t)n[u]=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,ur(_e.jobId,L.id)).where(rd(ur(L.workflowId,e),od(_e.subjectId,t))).orderBy(nd(L.createdAt)),i=new Map;for(let u of o)i.has(u.subjectId)||i.set(u.subjectId,u.jobId);let s=[...new Set(i.values())],a=await Promise.all(s.map(u=>this.get(u))),c=new Map(a.filter(u=>u!=null).map(u=>[u.id,u]));for(let[u,d]of i)n[u]=c.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(_e).where(ur(_e.jobId,e));let n=sd(t);n.length!==0&&await this.db.insert(_e).values(n.map(o=>({id:id(),jobId:e,subjectType:o.subjectType,subjectId:o.id,snapshot:o})))}async replaceStepExecutions(e,t){await this.db.delete(dt).where(ur(dt.jobId,e));let n=Ks(e,t);n.length!==0&&await this.db.insert(dt).values(n)}toDomain(e,t,n){let o=ad(t.map(s=>s.snapshot)),i=cd(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=Zp([td(),ed("design:paramtypes",[Object,Function])],z)});import{Injectable as hd}from"@nestjs/common";import{eq as yd}from"drizzle-orm";var fd,md,se,Br=l(()=>{"use strict";Cr();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)},se=class{db;constructor(e){this.db=e}async create(e){return await this.db.insert(ze).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(ze).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(yd(ze.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=fd([hd(),md("design:paramtypes",[Object])],se)});import{Injectable as bd}from"@nestjs/common";import{eq as Gs}from"drizzle-orm";var gd,wd,$e,Fo=l(()=>{"use strict";Ro();gd=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)},$e=class{db;constructor(e){this.db=e}async create(e){return await this.db.insert(Xe).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(Xe).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(Gs(Xe.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(Xe).where(Gs(Xe.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=gd([bd(),wd("design:paramtypes",[Object])],$e)});import{Injectable as vd}from"@nestjs/common";import{eq as No}from"drizzle-orm";var Sd,xd,qe,Jo=l(()=>{"use strict";ko();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},xd=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(Pe).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(Pe).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(Pe.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(Pe).set({order:n}).where(No(Pe.id,e[n]));return this.list()}async delete(e){return await this.get(e)?(await this.db.delete(Pe).where(No(Pe.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=Sd([vd(),xd("design:paramtypes",[Object])],qe)});import{Injectable as _d}from"@nestjs/common";import{eq as zs}from"drizzle-orm";var jd,Id,ae,Dr=l(()=>{"use strict";Ao();jd=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},Id=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(Ye).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(Ye).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(zs(Ye.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(Ye).where(zs(Ye.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=jd([_d(),Id("design:paramtypes",[Object])],ae)});import{Injectable as Rd}from"@nestjs/common";import{eq as Qs}from"drizzle-orm";var Pd,Ed,ce,Fr=l(()=>{"use strict";Co();Pd=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},Ed=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(Ze).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(Ze).set({name:t.name??n.name,localPath:t.localPath??n.localPath,worktreeBasePath:t.worktreeBasePath!==void 0?t.worktreeBasePath??null:n.worktreeBasePath??null}).where(Qs(Ze.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(Ze).where(Qs(Ze.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=Pd([Rd(),Ed("design:paramtypes",[Object])],ce)});import{z as P}from"zod";var Xs,Ys,Zs,Lo,Nr,ea,Uo=l(()=>{"use strict";Xs=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()}),Ys=P.object({id:P.string().min(1),label:P.string().min(1),params:P.array(Xs)}),Zs=P.object({actionId:P.string().min(1),label:P.string().min(1),params:P.array(Xs)}),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())}),ea=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 ta=l(()=>{"use strict";Wr()});var ra=l(()=>{"use strict";Uo()});function kd(r){let e=r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"");return e.length>0?e:"step"}function na(r,e){let t=e instanceof Set?e:new Set(e),n=kd(r);if(!t.has(n))return n;let o=2;for(;t.has(`${n}-${o}`);)o+=1;return`${n}-${o}`}function oa(r,e){for(let t of r)t.id&&e.push(t.id),t.type==="loop"&&Array.isArray(t.steps)&&oa(t.steps,e)}function ia(r){let e=[];oa(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 sa(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 Ad,pr,Cd,et,aa,ca,ua,la,pa,da,fa,ma,Td,ha,ya,ht,Od,$d,qd,Bd,Dd,Fd,Nd,ga,tt,wa=l(()=>{"use strict";Wr();Mo();Ad=f.enum(["on_fail","on_complete","on_needs_input"]),pr=f.object({triggers:f.array(Ad),messageTemplate:f.string().optional()}),Cd=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()}),et=f.string().min(1),aa=f.object({type:f.literal("agent"),id:f.string().min(1),name:et,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()}),ca=f.object({type:f.literal("interaction"),id:f.string().min(1),name:et,interaction:f.union([f.literal("questionnaire"),f.literal("confirmation"),f.literal("conversation")]),notify:f.boolean().optional()}),ua=f.object({type:f.literal("shell"),id:f.string().min(1),name:et,command:f.string().min(1)}),la=f.object({type:f.literal("git"),id:f.string().min(1),name:et,operation:f.enum(["create_worktree","checkout","create_branch","commit","push"]),params:f.record(f.string(),f.unknown())}),pa=f.object({type:f.literal("provider_action"),id:f.string().min(1),name:et,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()}),da=f.object({type:f.literal("sub_workflow"),id:f.string().min(1),name:et,workflowId:f.string().min(1),forEach:f.literal("selection")}),fa=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()})]),ma=f.discriminatedUnion("action",[f.object({action:f.literal("fail")}),f.object({action:f.literal("continue")}),f.object({action:f.literal("ask_human")})]),Td=f.object({type:f.literal("loop"),id:f.string().min(1),name:et,steps:f.array(f.lazy(()=>ha)),until:fa,maxIterations:f.number().int().nonnegative(),onMaxIterations:ma}),ha=f.lazy(()=>f.discriminatedUnion("type",[la,pa,ua,aa,ca,da,Td])),ya=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(Cd),steps:f.array(ha),notificationPolicy:pr}),ht=ya.superRefine((r,e)=>{let t=ia(r.steps);t.length!==0&&e.addIssue({code:"custom",path:["steps"],message:`Duplicate step id(s): ${t.join(", ")}`})}),Od=aa.extend({id:f.string().min(1).optional()}),$d=ca.extend({id:f.string().min(1).optional()}),qd=ua.extend({id:f.string().min(1).optional()}),Bd=la.extend({id:f.string().min(1).optional()}),Dd=pa.extend({id:f.string().min(1).optional()}),Fd=da.extend({id:f.string().min(1).optional()}),Nd=f.object({type:f.literal("loop"),id:f.string().min(1).optional(),name:et,steps:f.array(f.lazy(()=>ga)),until:fa,maxIterations:f.number().int().nonnegative(),onMaxIterations:ma}),ga=f.lazy(()=>f.discriminatedUnion("type",[Bd,Dd,qd,Od,$d,Fd,Nd])),tt=ya.omit({id:!0,steps:!0}).extend({id:f.string().min(1).optional(),steps:f.array(ga)})});function ba(r){return r==="none"?[]:Array.isArray(r)?r:[r]}function Sa(r,e){return ba(r).includes(e)}var Wo=l(()=>{"use strict"});var xa=l(()=>{"use strict"});var va=l(()=>{"use strict";Wo()});var ja=l(()=>{"use strict";wa();Mo();Wo();xa();va()});import{z as yt}from"zod";var Jd,Hr,Vr,Kr,Ia=l(()=>{"use strict";Jd=yt.enum(["user","organization","project"]),Hr=yt.object({id:yt.string().min(1),name:yt.string().min(1),description:yt.string().optional(),tier:Jd,path:yt.string().min(1)}),Vr=Hr.omit({id:!0}).extend({id:yt.string().min(1).optional()}),Kr=Hr.partial().omit({id:!0})});var _a=l(()=>{"use strict";Ia()});import{z as At}from"zod";var Gr,zr,Qr,Pa=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 Ea=l(()=>{"use strict";Pa()});var Ra=l(()=>{"use strict"});var ka=l(()=>{"use strict";Ra()});var Aa=l(()=>{"use strict"});var Ca=l(()=>{"use strict";Aa()});import{z as Z}from"zod";var Ct,Ta=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 Oa=l(()=>{"use strict";Ta()});import{z as ue}from"zod";var Xr,Yr,Zr,en,$a=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 qa=l(()=>{"use strict";$a()});import{z as x}from"zod";function gt(r){return r.kind==="subject"}function Tt(r){return r.kind==="agent"}var Ld,Ba,Da,Fa,Na,tn,rn,nn,on,sn,an,Ja,La,Ua=l(()=>{"use strict";Wr();Ld=x.enum(["jira","bitbucket","github","confluence","manual"]),Ba=x.enum(["claude","cursor"]),Da={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()},Fa=x.object({...Da,kind:x.literal("subject"),type:Ld,subjectType:re}),Na=x.object({...Da,kind:x.literal("agent"),type:Ba}),tn=x.discriminatedUnion("kind",[Fa,Na]),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",[Fa.extend({defaultAgent:x.boolean().optional()}),Na.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:Ba,apiKey:x.string().min(1).optional(),instanceId:x.string().min(1).optional()}),Ja=x.object({id:x.string().min(1),displayName:x.string().min(1)}),La={providerInstances:[]}});var Ma=l(()=>{"use strict";Ua()});var Wa=l(()=>{"use strict"});var Ha=l(()=>{"use strict";Wa()});var C=l(()=>{"use strict";ta();ra();ja();_a();Ea();ka();Ca();Oa();qa();Ma();Ha()});import{Injectable as Wd}from"@nestjs/common";import{eq as Hd}from"drizzle-orm";function Vd(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??La.providerInstances,...r.defaultAgentInstanceId?{defaultAgentInstanceId:r.defaultAgentInstanceId}:{}}}function Va(r){return r.providerInstances!==void 0}var Ud,Md,E,Ee=l(()=>{"use strict";C();To();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},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 get(){let e=await this.db.query.settings.findFirst({where:{id:ir}});return Ho(e?e.data:{})}async update(e){let t=Vd(await this.get(),e);return await this.db.query.settings.findFirst({where:{id:ir}})?await this.db.update(kt).set({data:t}).where(Hd(kt.id,ir)):await this.db.insert(kt).values({id:ir,data:t}),t}async replaceProviderInstances(e){return this.update({providerInstances:e})}};E=Ud([Wd(),Md("design:paramtypes",[Object])],E)});import{Module as Gd}from"@nestjs/common";var Kd,zd,Re,dr=l(()=>{"use strict";Ms();mt();qr();lr();Br();Fo();Jo();Dr();Fr();Ee();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},zd=[O,ie,z,se,$e,qe,ae,ce,E],Re=class{};Re=Kd([Gd({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:$e,useFactory:r=>new $e(r.getDb()),inject:[X]},{provide:qe,useFactory:r=>new qe(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:E,useFactory:r=>new E(r.getDb()),inject:[X]}],exports:[X,...zd]})],Re)});import{Injectable as Yd,Logger as Zd,Inject as Ga}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 ef(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 Qd,Xd,Ka,Vo,rt,Ko=l(()=>{"use strict";Ee();Oe();Qd=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},Xd=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},Ka=function(r,e){return function(t,n){e(t,n,r)}};rt=Vo=class{secrets;settings;logger=new Zd(Vo.name);constructor(e,t){this.secrets=e,this.settings=t}async onModuleInit(){let e=await this.settings.get();await ef(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=Qd([Yd(),Ka(0,Ga(fe)),Ka(1,Ga(E)),Xd("design:paramtypes",[Function,E])],rt)});function cn(r,e=Et(r)){let t=of[r]??r;return new Error(`${t} API key not configured \u2014 set '${e}' via the setup script`)}function Qa(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 rf){let o=e.get(n);o?.length&&t.push(`## ${tf[n]}
12
12
  ${o.join(`
13
13
 
14
14
  `)}`)}return t.join(`
15
15
 
16
- `)}function fr(r){let e=[],t=Va(r.knowledge);return t&&e.push(t),e.push(`# Objective
16
+ `)}function fr(r){let e=[],t=Qa(r.knowledge);return t&&e.push(t),e.push(`# Objective
17
17
  ${r.objective}`),e.push(`# Output format
18
- ${Xd[r.outputFormat]}`),e.join(`
18
+ ${nf[r.outputFormat]}`),e.join(`
19
19
 
20
- `)}function mr(r,e){return e==="free_text"?r:Ka(r)}function Ka(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 zd,Qd,Xd,Yd,un=l(()=>{"use strict";Te();zd={user:"User preferences",organization:"Organization guidelines",project:"Project context"},Qd=["user","organization","project"],Xd={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."},Yd={anthropic:"Anthropic",cursor:"Cursor"}});async function*ef(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 Zd,ln,Ga=l(()=>{"use strict";un();Te();un();Zd=Rt("anthropic"),ln=class{secrets;options;constructor(e,t={}){this.secrets=e,this.options=t}async run(e){let t=await this.requireApiKey(),n=fr(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??ef,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:mr(a,e.outputFormat),sessionId:s}}async requireApiKey(){let e=this.options.secretKey?.trim()||Zd,t=await this.secrets.get(e);if(!t)throw cn("anthropic",e);return t}}});function rf(r,e,t){return{apiKey:r,...t?{model:{id:t}}:{},local:{...e?{cwd:e}:{},settingSources:[]}}}async function nf(){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 tf,pn,za=l(()=>{"use strict";un();Te();tf=Rt("cursor"),pn=class{secrets;options;constructor(e,t={}){this.secrets=e,this.options=t}async run(e){let t=await this.requireApiKey(),n=fr(e),o=this.options.sdk??await nf(),i=rf(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:mr(c,e.outputFormat),sessionId:s.agentId}}finally{await s[Symbol.asyncDispose]?.()}}async requireApiKey(){let e=this.options.secretKey?.trim()||tf,t=await this.secrets.get(e);if(!t)throw cn("cursor",e);return t}}});function Qa(r){return typeof r=="object"&&r!=null&&typeof r.listExtendedActions=="function"&&typeof r.executeExtendedAction=="function"}function dn(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 Ot(r){return r.length===0?"none":r.map(e=>e.actionId).join(", ")}var fn=l(()=>{"use strict"});function hr(r){return r==null?"":typeof r=="string"?r:Xa(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 Xa(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(Xa).join("");return e.type==="paragraph"||e.type==="heading"||e.type==="blockquote"||e.type==="listItem"?`${t}
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 mr(r,e){return e==="free_text"?r:Xa(r)}function Xa(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 tf,rf,nf,of,un=l(()=>{"use strict";Oe();tf={user:"User preferences",organization:"Organization guidelines",project:"Project context"},rf=["user","organization","project"],nf={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."},of={anthropic:"Anthropic",cursor:"Cursor"}});async function*af(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 sf,ln,Ya=l(()=>{"use strict";un();Oe();un();sf=Et("anthropic"),ln=class{secrets;options;constructor(e,t={}){this.secrets=e,this.options=t}async run(e){let t=await this.requireApiKey(),n=fr(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??af,s,a,c;for await(let u of i({prompt:n,options:o}))u.session_id&&(s=u.session_id),u.type==="result"&&(u.subtype==="success"&&typeof u.result=="string"?a=u.result:c=u.errors?.join("; ")||u.subtype||"Claude agent returned an error result");if(c)throw new Error(`Claude agent failed: ${c}`);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:mr(a,e.outputFormat),sessionId:s}}async requireApiKey(){let e=this.options.secretKey?.trim()||sf,t=await this.secrets.get(e);if(!t)throw cn("anthropic",e);return t}}});function uf(r,e,t){return{apiKey:r,...t?{model:{id:t}}:{},local:{...e?{cwd:e}:{},settingSources:[]}}}async function lf(){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 cf,pn,Za=l(()=>{"use strict";un();Oe();cf=Et("cursor"),pn=class{secrets;options;constructor(e,t={}){this.secrets=e,this.options=t}async run(e){let t=await this.requireApiKey(),n=fr(e),o=this.options.sdk??await lf(),i=uf(t,e.cwd,this.options.model),s=e.sessionId?await o.resume(e.sessionId,i):await o.create(i);try{let c=await(await s.send(n)).wait();if(c.status!=="finished")throw new Error(c.error?.message||`Cursor agent ended with status '${c.status}'`);let u=c.result??"";return{raw:u,parsed:mr(u,e.outputFormat),sessionId:s.agentId}}finally{await s[Symbol.asyncDispose]?.()}}async requireApiKey(){let e=this.options.secretKey?.trim()||cf,t=await this.secrets.get(e);if(!t)throw cn("cursor",e);return t}}});function ec(r){return typeof r=="object"&&r!=null&&typeof r.listExtendedActions=="function"&&typeof r.executeExtendedAction=="function"}function dn(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 Ot(r){return r.length===0?"none":r.map(e=>e.actionId).join(", ")}var fn=l(()=>{"use strict"});function hr(r){return r==null?"":typeof r=="string"?r:tc(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 tc(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(tc).join("");return e.type==="paragraph"||e.type==="heading"||e.type==="blockquote"||e.type==="listItem"?`${t}
23
+ `:t}var Go=l(()=>{"use strict"});function mf(r,e){return e.startsWith("http://")||e.startsWith("https://")?e:`${r.replace(/\/$/,"")}${e.startsWith("/")?e:`/${e}`}`}function nc(r){return{representation:"atlas_doc_format",value:JSON.stringify(mn(r))}}function ic(r){return hr(hf(r))}function hf(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 oc(r,e,t){return{id:String(r.id??""),source:t,title:String(r.title??""),url:yf(e,r),raw:r}}function yf(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 gf(r,e){return{id:String(r.id??""),subjectId:e,body:ic(r.body),createdAt:r.version?.createdAt??r.createdAt??"",raw:r}}var pf,df,ff,rc,hn,yn,zo=l(()=>{"use strict";fn();Go();pf="kno.confluence.apiToken",df=50,ff=10,rc=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()||pf}async get(e){let{baseUrl:t}=await this.requireConfig(),n=await this.request("GET",`/wiki/api/v2/pages/${encodeURIComponent(e)}`);return oc(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 ic(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=${df}`,o=new Set;for(let i=0;i<ff&&t.length<rc&&!(!n||o.has(n));i++){o.add(n);let s=await this.request("GET",n),a=Array.isArray(s.results)?s.results:[];for(let u of a){if(t.length>=rc)break;t.push(gf(u,e))}let c=typeof s._links?.next=="string"?s._links.next:void 0;if(!c||a.length===0)break;n=c}return t}async postComment(e,t){await this.requireConfig(),await this.request("POST","/wiki/api/v2/footer-comments",{body:{pageId:e,body:nc(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),c=await this.request("POST","/wiki/api/v2/pages",{body:{spaceId:a,status:"current",title:o,body:nc(i)}});return oc(c,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=mf(o,t),c={Authorization:`Basic ${Buffer.from(`${i}:${s}`).toString("base64")}`,Accept:"application/json"};n.body!==void 0&&(c["Content-Type"]="application/json");let u=await this.fetchFn(a,{method:e,headers:c,...n.body!==void 0?{body:JSON.stringify(n.body)}:{}});if(!u.ok){let m=await u.text().catch(()=>"");throw new Error(`Confluence ${e} ${t} failed (${u.status}): ${m||u.statusText}`)}if(u.status===204)return;let d=await u.text();if(d)return JSON.parse(d)}}});import{randomUUID as wf}from"node:crypto";var bf,gn,sc=l(()=>{"use strict";bf=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:wf(),subjectId:e,body:t,createdAt:new Date().toISOString()}),this.comments.set(e,o)}assertCommentsSupported(e){let t=this.type??e.source;if(bf.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 xf.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 vf(r,e){return`${r}#${e}`}function jf(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 If(r){if(typeof r.repoSlug=="string"&&r.repoSlug.trim().length>0||!uc(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 cc(r){if(!uc(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=cc(r.state);if(e)return`state="${e}"`}function Pf(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 Ef(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 uc(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:vf(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 Rf(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 Sf,xf,Xo,ac,Yo,ei,bn,ti=l(()=>{"use strict";fn();Sf="kno.bitbucket.apiToken",xf="https://api.bitbucket.org/2.0";Xo=50,ac=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()||Sf}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 wn(i,t,this.instanceId)}async query(e){let t=If(e);if(t)return this.queryWorkspacePullRequests(t,e);let n=jf(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=cc(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<ac&&n.length<Yo&&!(!i||o.has(i));s++){o.add(i);let a=await this.request("GET",i),c=Array.isArray(a.values)?a.values:[];for(let d of c){if(n.length>=Yo)break;n.push(wn(d,t??Pf(d),this.instanceId))}let u=typeof a.next=="string"&&a.next.length>0?a.next:void 0;if(!u||c.length===0)break;i=u}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=${Xo}`;for(let c=0;c<ac&&i.length<Yo&&!(!a||s.has(a));c++){s.add(a);let u=await this.request("GET",a),d=Array.isArray(u.values)?u.values:[];for(let b of d)i.push(Rf(b,e));let m=typeof u.next=="string"&&u.next.length>0?u.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=Ef(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: ${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)),c=await this.request("GET",`/users/${encodeURIComponent(n)}`),u=Zo(c.uuid),d=Zo(c.account_id);if(!u&&!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=>u!=null&&N.uuid===u||d!=null&&N.account_id===d))return wn(a,o,this.instanceId);let S=[...m.map(N=>N.uuid?{uuid:N.uuid}:{account_id:N.account_id}),u?{uuid:u}:{account_id:d}],I=await this.request("PUT",this.prPath(s,o,i),{body:{title:a.title??"",reviewers:S}});return wn(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:`${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 c=await this.fetchFn(s,{method:e,headers:a,...n.body!==void 0?{body:JSON.stringify(n.body)}:{}});if(!c.ok){let d=await c.text().catch(()=>"");throw new Error(`Bitbucket ${e} ${t} failed (${c.status}): ${d||c.statusText}`)}if(c.status===204)return;let u=await c.text();if(u)return JSON.parse(u)}}});import{randomUUID as kf}from"node:crypto";function Af(r,e){return Object.entries(e).every(([t,n])=>t==="status"?r.raw?.status===n:r[t]===n)}var Sn,lc=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=>Af(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:kf(),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}=pc(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 qf(r,e,t){return`${r}/${e}#${t}`}function pc(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 Bf(r){let e=r.role;if(e==="assignee"||e==="creator")return e}function Df(r,e){return r==="creator"?`author:${e}`:`assignee:${e}`}function Ff(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: ${$f.join(", ")}`)}function Nf(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:qf(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 Jf(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 Cf,Tf,Of,$f,jn,dc=l(()=>{"use strict";Cf="2026-03-10",Tf="https://api.github.com",Of="kno.github.apiToken",$f=["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()||Of}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=Bf(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=>Jf(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:Ff(t)})}async queryRepoIssues(e,t){let{owner:n,name:o}=pc(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 c=await this.request("GET",`/repos/${encodeURIComponent(n)}/${encodeURIComponent(o)}/issues?${s.toString()}`),u=Array.isArray(c)?c:[];if(u.length===0)break;for(let d of u)if(!ri(d)){if(i.length>=500)break;i.push(ni(d,this.instanceId,`${n}/${o}`))}if(u.length<100)break}return i}async querySearch(e,t){let n=this.requireUsername(),o=[Df(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 c=new URLSearchParams({q:i,per_page:String(100),page:String(a)}),u=await this.request("GET",`/search/issues?${c.toString()}`),d=Array.isArray(u.items)?u.items:[];if(d.length===0)break;for(let m of d)if(!ri(m)){if(s.length>=500)break;s.push(ni(m,this.instanceId,Nf(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=`${Tf}${t}`,s={Authorization:`Bearer ${o}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":Cf};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 u=await a.text().catch(()=>"");throw new Error(`GitHub ${e} ${t} failed (${a.status}): ${u||a.statusText}`)}if(a.status===204)return;let c=await a.text();if(c)return JSON.parse(c)}}});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 Wf(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 fc(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 Lf,Uf,Mf,In,En,mc=l(()=>{"use strict";R();Go();Lf="kno.jira.apiToken",Uf=50,Mf=10,In=500,En=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()||Lf}async get(e){let{baseUrl:t}=await this.requireConfig(),n=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}`);return fc(n,t,this.instanceId)}async query(e){let{baseUrl:t}=await this.requireConfig(),n=Wf(e),o=[],i,s=new Set;for(let a=0;a<Mf&&o.length<In;a++){let c={jql:n,maxResults:Math.min(Uf,In-o.length),fields:["summary","description","status","assignee"]};i&&(c.nextPageToken=i);let u=await this.request("POST","/rest/api/3/search/jql",{body:c}),d=Array.isArray(u.issues)?u.issues:[];for(let b of d){if(o.length>=In)break;o.push(fc(b,t,this.instanceId))}let m=typeof u.nextPageToken=="string"?u.nextPageToken:void 0;if(u.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 c of a)t.push({id:String(c.id??""),subjectId:e,body:hr(c.body),...c.author?.displayName?{author:c.author.displayName}:{},createdAt:c.created??"",raw:c});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(u=>u.to?.name).filter(u=>typeof u=="string"&&u.length>0),c=a.length>0?a.join(", "):"(none)";throw new Error(`No Jira transition to status '${t}' from the current state. Available: ${c}`)}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}`,c={Authorization:`Basic ${Buffer.from(`${i}:${s}`).toString("base64")}`,Accept:"application/json"};n.body!==void 0&&(c["Content-Type"]="application/json");let u=await this.fetchFn(a,{method:e,headers:c,...n.body!==void 0?{body:JSON.stringify(n.body)}:{}});if(!u.ok){let m=await u.text().catch(()=>"");throw new Error(`Jira ${e} ${t} failed (${u.status}): ${m||u.statusText}`)}if(u.status===204)return;let d=await u.text();if(d)return JSON.parse(d)}}});import{randomUUID as Hf}from"node:crypto";function Vf(r,e){return Object.entries(e).every(([t,n])=>r[t]===n)}var Rn,hc=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=>Vf(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:Hf(),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 Be(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 Kf(r){return r==="jira"||r==="github"?"ticket":r==="bitbucket"?"pull_request":r==="confluence"?"documentation":"any"}var wv,F,$t=l(()=>{"use strict";C();Ya();Za();zo();sc();ti();lc();dc();mc();hc();wv=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=Be(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(!gt(e))throw new Error(`Unknown provider instance kind on '${e.id}'`);let n=Kf(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 En(t,{instanceId:e.id,baseUrl:Be(e.config,"baseUrl"),email:Be(e.config,"email"),secretKey:e.secretKey}));return}if(e.type==="github"){this.tickets.set(e.id,new jn(t,{instanceId:e.id,username:Be(e.config,"username"),secretKey:e.secretKey}));return}if(e.type==="bitbucket"){this.repos.set(e.id,new bn(t,{instanceId:e.id,email:Be(e.config,"email"),workspace:Be(e.config,"workspace"),secretKey:e.secretKey}));return}if(e.type==="confluence"){this.documentation.set(e.id,new yn(t,{instanceId:e.id,baseUrl:Be(e.config,"baseUrl"),email:Be(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:Be(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 gc(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 yc,wc=l(()=>{"use strict";R();yc=[{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 Sc(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 bc,xc=l(()=>{"use strict";R();bc=[{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 Pc(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 = ${Ic(jc(r,e))} AND statusCategory != Done`};case"current-sprint-tickets":return{jql:`project = ${Ic(jc(r,e))} AND sprint in openSprints() AND statusCategory != Done`};default:throw new y(`Unknown Jira query template: ${r}`)}}function jc(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 Ic(r){return`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}var vc,_c,Ec=l(()=>{"use strict";R();vc={name:"project",label:"Project key",type:"string",required:!0},_c=[{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:[vc]},{id:"current-sprint-tickets",label:"Tickets in the current sprint",params:[vc]}]});import{Inject as kc,Injectable as Qf}from"@nestjs/common";var Gf,zf,Rc,Ac,nt,oi=l(()=>{"use strict";C();R();Ee();$t();wc();xc();Ec();Gf=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},zf=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)}},Ac={bitbucket:{list:()=>yc,resolve:gc},github:{list:()=>bc,resolve:Sc},jira:{list:()=>_c,resolve:Pc}},nt=class{settings;registry;constructor(e,t){this.settings=e,this.registry=t}async list(e){let t=await this.providerType(e);return t?Ac[t]?.list()??[]:[]}async resolve(e,t,n){let o=await this.providerType(e),i=o?Ac[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 c=n[a.name];if(c==null||typeof c=="string"&&c.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=Gf([Qf(),Rc(0,kc(E)),Rc(1,kc(F)),zf("design:paramtypes",[E,F])],nt)});import{Inject as Tc,Injectable as Zf}from"@nestjs/common";var Xf,Yf,Cc,em,ot,ii=l(()=>{"use strict";C();Ee();zo();ti();$t();Xf=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},Yf=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},Cc=function(r,e){return function(t,n){e(t,n,r)}},em={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)?[]:em[n.type]?.()??[]}};ot=Xf([Zf(),Cc(0,Tc(E)),Cc(1,Tc(F)),Yf("design:paramtypes",[E,F])],ot)});async function Oc(r){let e=r.fetchFn??fetch;return r.type==="claude"?om(r.apiKey,e):im(r.apiKey,e)}async function om(r,e){let t=await e(tm,{method:"GET",headers:{"x-api-key":r,"anthropic-version":nm}});if(!t.ok)throw $c("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 c=typeof s.display_name=="string"&&s.display_name.trim()?s.display_name:a;return[{id:a,displayName:c}]})}async function im(r,e){let t=await e(rm,{method:"GET",headers:{Authorization:`Basic ${Buffer.from(`${r}:`).toString("base64")}`}});if(!t.ok)throw $c("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 c=typeof s.displayName=="string"&&s.displayName.trim()?s.displayName:a;return[{id:a,displayName:c}]})}function $c(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 tm,rm,nm,qc=l(()=>{"use strict";tm="https://api.anthropic.com/v1/models",rm="https://api.cursor.com/v1/models",nm="2023-06-01"});import{Inject as ai,Injectable as cm}from"@nestjs/common";var sm,am,si,An,it,ci=l(()=>{"use strict";C();Ee();Oe();R();qc();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)},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(!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 Oc({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=sm([cm(),si(0,ai(E)),si(1,ai(fe)),si(2,ai(An)),am("design:paramtypes",[E,Function,Function])],it)});import{Module as lm}from"@nestjs/common";var um,st,Cn=l(()=>{"use strict";wo();hs();jo();Oe();dr();Ee();Ko();$t();oi();ii();ci();um=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=um([lm({imports:[Rt,Re],providers:[{provide:F,useFactory:async(r,e)=>{let t=await r.get();return F.fromSettings(t.providerInstances??[],e)},inject:[E,fe]},{provide:Yt,useClass:Rr},rt,nt,ot,{provide:An,useValue:(r,e)=>fetch(r,e)},it],exports:[F,Yt,rt,nt,ot,it,An]})],st)});import{Injectable as dm}from"@nestjs/common";var pm,ye,Tn=l(()=>{"use strict";pm=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=pm([dm()],ye)});import{Global as mm,Module as hm}from"@nestjs/common";var fm,at,On=l(()=>{"use strict";Tn();fm=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=fm([mm(),hm({providers:[ye],exports:[ye]})],at)});import{Injectable as wm}from"@nestjs/common";import{execFile as bm}from"node:child_process";import{mkdirSync as ui,rmSync as Sm}from"node:fs";import{dirname as xm,join as $n,resolve as Bc}from"node:path";import{promisify as vm}from"node:util";function Dc(r){return r==null?"":typeof r=="string"?r:r.toString("utf8")}function Fc(r){return $n(r,"worktrees")}function Im(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 ym,gm,jm,De,li=l(()=>{"use strict";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},gm=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},jm=vm(bm),De=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 Im(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=Bc(e);try{let{stdout:n}=await this.git(t,["rev-parse","--git-common-dir"]),o=Bc(t,n.trim()),i=o.endsWith(".git")?xm(o):o;await this.git(i,["worktree","remove","--force",t])}catch{Sm(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 jm("git",t,{cwd:e,encoding:"utf8",windowsHide:!0});return{stdout:n.stdout??"",stderr:n.stderr??""}}catch(n){let o=n,i=Dc(o.stderr),s=Dc(o.stdout),a=i||s||o.message||"unknown git error";throw new Error(`git ${t.join(" ")} failed (cwd=${e}, code=${String(o.code??"?")}): ${a}`)}}};De=ym([wm(),gm("design:paramtypes",[String])],De)});import{Module as Pm}from"@nestjs/common";import{mkdirSync as Em}from"node:fs";var _m,Nc,qn,Jc=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},Nc=er();Em(Nc,{recursive:!0});qn=class{};qn=_m([Pm({providers:[{provide:De,useFactory:()=>new De(Fc(Nc))}],exports:[De]})],qn)});function gr(r,e){return r.replace(/\{\{\s*([^}]+?)\s*\}\}/g,(t,n)=>{let o=Rm(e,n.trim());return o==null?"":typeof o=="string"?o:JSON.stringify(o)})}function Rm(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"?gr(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 Lc=l(()=>{"use strict"});function Uc(r,e){switch(r){case"questionnaire":return pi(e);case"confirmation":return km(e);case"conversation":return Am(e);default:return r}}function pi(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 km(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)?[]:pi(r)}function Am(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?pi(r):[]}var Mc=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 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 di(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]},c=i.findIndex(u=>u.index===n);i[c]=a}else{let a={index:n,stepExecutions:[e],startedAt:e.startedAt??new Date().toISOString()};i.push(a),i.sort((c,u)=>c.index-u.index)}return{...o,iterations:i}}return o.iterations?{...o,iterations:o.iterations.map(i=>({...i,stepExecutions:di(i.stepExecutions,e,t,n)}))}:o})}function wr(r,e){for(let t of r){if(t.id===e)return t;if(t.type==="loop"){let n=wr(t.steps,e);if(n)return n}}}function Wc(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,c)=>a>c?a:c):void 0;return{...i,...s?{completedAt:s}:{}}});return{...n,iterations:o}})}function fi(r){let e=[];for(let t of r){t.childJobIds&&e.push(...t.childJobIds);for(let n of t.iterations??[])e.push(...fi(n.stepExecutions))}return e}var Hc=l(()=>{"use strict"});import{z as le}from"zod";function Vc(r,e){let t=qm[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 Cm,Tm,Om,$m,qm,Kc=l(()=>{"use strict";Cm=le.object({questions:le.array(le.object({id:le.string(),prompt:le.string()}))}),Tm=le.object({approved:le.boolean()}),Om=le.object({suggestions:le.array(le.object({body:le.string()}))}),$m=le.string(),qm={questionnaire:Cm,confirmation:Tm,comment_suggestions:Om,free_text:$m}});function ge(r){return r==="completed"||r==="failed"||r==="cancelled"}function mi(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 Gc(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 hi=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 yi=l(()=>{"use strict";R()});import{Injectable as Dm}from"@nestjs/common";var Bm,bt,gi=l(()=>{"use strict";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},bt=class{requested=new Set;requestCancellation(e){this.requested.add(e)}isCancellationRequested(e){return this.requested.has(e)}clear(e){this.requested.delete(e)}};bt=Bm([Dm()],bt)});import{Logger as Fm}from"@nestjs/common";import{readFile as Nm}from"node:fs/promises";async function zc(r,e,t=new Fm("resolveContextFiles"),n=o=>Nm(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 c=a instanceof Error?a.message:String(a);throw new Error(`Cannot read context file '${s.name}' at ${s.path}: ${c}`)}}return o}var Qc=l(()=>{"use strict"});import{basename as Jm,dirname as Lm,join as Um,resolve as br,sep as Xc}from"node:path";function Mm(r){return r.replace(/-/g,"").slice(0,4)}function Yc(r,e){return`${r}-${Mm(e)}`}function wi(r){return r.replace(/[\\/:*?"<>|]/g,"-")}function Dn(r){let e=br(r);return Um(Lm(e),`${Jm(e)}-worktrees`)}function Fn(r,e){let t=br(r),n=br(e);if(ut(t,n))return!0;let o=t.endsWith(Xc)?t:t+Xc,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 bi=l(()=>{"use strict"});import{join as Zc}from"node:path";async function eu(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),c=o.find(m=>m.id===a),u=o.find(m=>ut(m.localPath,a)),d=c??u;if(!d)throw new h(`Unknown local repository: ${a}`);n[i.name]=d.localPath}return n}async function tu(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",c=(await i.list()).find(S=>ut(S.localPath,s)),u=c?.worktreeBasePath?.trim()?c.worktreeBasePath.trim():Dn(s);if(Fn(s,u)&&!ut(s,u))throw new Error(`Worktree base '${u}' must not be inside the repository at '${s}'`);if(a==="existing-branch")return Wm({job:e,repoPath:s,branch:Nn(t,"branch"),worktreeBase:u,explicitPath:typeof t.worktreePath=="string"?t.worktreePath:void 0,git:n,jobs:o});let d=Nn(t,"branchName"),m=Yc(d,e.id),b=typeof t.worktreePath=="string"&&t.worktreePath.trim()!==""?t.worktreePath:Zc(u,wi(m));return n.createWorktree(e.id,{repoPath:s,baseBranch:Nn(t,"baseBranch"),branchName:m,worktreePath:b})}async function Wm(r){let{job:e,repoPath:t,branch:n,worktreeBase:o,git:i,jobs:s}=r,a=await i.listWorktrees(t),c=a.filter(b=>b.branch===n&&!ut(b.path,t)),u=a.find(b=>b.branch===n&&ut(b.path,t));if(c.length===0){if(u)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=c[0].path,m=await Hm(s,d);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(d,n),{worktreePath:d,branch:n}}async function Hm(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 ru=l(()=>{"use strict";R();bi();hi()});import{Inject as de,Injectable as Gm,Logger as zm}from"@nestjs/common";import{randomUUID as Si}from"node:crypto";import{exec as Qm}from"node:child_process";import{promisify as Xm}from"node:util";async function xi(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 nu(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 eh(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(c=>c.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 St(r,e){let t=r[e];if(typeof t!="string"||t.length===0)throw new Error(`Missing required string param '${e}'`);return t}function th(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 ou(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 Vm,Km,pe,vi,Ym,Zm,we,Ln=l(()=>{"use strict";mt();lr();Br();qr();Tn();li();Ee();Dr();Fr();$t();wo();fn();R();Lc();Mc();Hc();Kc();hi();yi();gi();Qc();ru();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},Km=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)}},Ym=Xm(Qm),Zm=new Set(["agent","shell","git","provider_action"]),we=vi=class{workflows;jobs;batches;views;events;providers;notifications;contextFiles;localRepositories;git;settings;cancellation;logger=new zm(vi.name);childTerminalLocks=new Set;batchTerminalLocks=new Set;constructor(e,t,n,o,i,s,a,c,u,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=c,this.localRepositories=u,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)}`);ou(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:Si(),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 c=n[a],u=await this.createJob({workflowId:t.id,subjectContext:{mode:"single",subject:c},selection:e.selection,batchId:i.id,fanOutIndex:a,inputValues:e.inputValues});s.push(u)}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 eu(t.inputSchema,e.inputValues,this.localRepositories);ou(t.inputSchema,n);let o=e.subjectContext??await this.resolveSubjectContext(t,e.subjectId),i=new Date().toISOString();return this.jobs.create({id:Si(),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!=="interaction")throw new Error(`Paused execution ${i} has type '${s.type}'; expected interaction or loop`);let a=new Date().toISOString(),c=ee(n.stepHistory,i,I=>({...I,status:"completed",completedAt:a,output:t})),u=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:c,currentStepId:void 0,currentStepExecutionId:void 0,updatedAt:a}),this.emit({type:"human_answered",jobId:n.id,answers:u,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 c=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}),u=ee(a.stepHistory,t.parentStepExecutionId,d=>({...d,status:"waiting_for_children",error:void 0,completedAt:void 0,childJobIds:[...d.childJobIds??[],c.id]}));return a=await this.persistJob({...a,status:"waiting_for_children",stepHistory:u,completedAt:void 0,updatedAt:new Date().toISOString()}),this.emitRetryLaunch(c.id,t.id),this.runJob(c.id),c}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 c=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(c.id,t.id),this.runJob(c.id),c}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(!Zm.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),c=a[s.index];if(!c||c.id!==o.stepDefinitionId)throw new J(`Failed step '${o.stepDefinitionId}' does not match sequence position ${s.index}`);let u=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:u})),updatedAt:u}),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 fi(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 c=e;for(let u=s;u<n.length;u++){let d=await this.stopIfCancelled(c);if(d)return{outcome:"cancelled",job:d};let m=n[u],b=new Date().toISOString(),S=u===s?a:void 0,I,N=c.stepHistory;if(S){let A=ct(c.stepHistory,S);if(!A)throw new Error(`Reuse execution ${S} not found on job ${c.id}`);I=A}else I={id:Si(),stepDefinitionId:m.id,type:m.type,status:"running",startedAt:b},N=di(c.stepHistory,I,o,i);if(c=await this.persistJob({...c,status:c.status==="pending"?"planning":c.status,currentStepId:m.id,currentStepExecutionId:I.id,stepHistory:N,updatedAt:b}),c.status==="cancelled")return{outcome:"cancelled",job:c};this.emit({type:"step_started",jobId:c.id,stepDefinitionId:m.id,timestamp:b});try{let A=await this.dispatchStep(c,t,m,I.id,o,i);c=A.job;let Ve=await this.stopIfCancelled(c);if(Ve)return{outcome:"cancelled",job:Ve};if(A.outcome!=="completed")return A}catch(A){let Ve=await this.failJob(c,t,I.id,m.id,A);return Ve.status==="cancelled"?{outcome:"cancelled",job:Ve}:{outcome:"failed",job:Ve}}}return o!=null&&i!=null&&(c=await this.persistJob({...c,stepHistory:Wc(c.stepHistory,o,i),updatedAt:new Date().toISOString()})),{outcome:"completed",job:c}}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,c=n.maxIterations){let u=e,d=a;for(;;){if(d>=c)switch(n.onMaxIterations.action){case"fail":return u=await this.failExecution(u,t,o,n.id,`Loop '${n.id}' exceeded maxIterations (${c})`),{outcome:"failed",job:u};case"continue":return u=await this.finishExecution(u,o,n.id,{iterations:d,exitedOnMaxIterations:!0}),{outcome:"completed",job:u};case"ask_human":{let b={maxIterationsCheckpoint:!0,nextIteration:d,effectiveMaxIterations:c},S=new Date().toISOString(),I=ee(u.stepHistory,o,N=>({...N,status:"pending",output:b}));return u=await this.persistJob({...u,status:"waiting_for_human",currentStepId:n.id,currentStepExecutionId:o,stepHistory:I,updatedAt:S}),this.emit({type:"waiting_for_human",jobId:u.id,stepDefinitionId:n.id,interaction:"confirmation",data:b,questions:[`Loop '${n.id}' reached maxIterations (${c}). Extend, continue, or cancel?`],timestamp:S}),t.notificationPolicy.triggers.includes("on_needs_input")&&await this.notifications.send({title:`Input needed: ${t.name}`,body:`Job ${u.id} hit max iterations on loop '${n.id}'`,jobId:u.id}),{outcome:"paused",job:u}}default:{let b=n.onMaxIterations;throw new Error(`Unknown onMaxIterations action: ${JSON.stringify(b)}`)}}let m=await this.executeStepSequence(u,t,n.steps,o,d,0);if(u=m.job,m.outcome!=="completed")return m;if(nu(n.until,u.context))return u=await this.finishExecution(u,o,n.id,{iterations:d+1}),{outcome:"completed",job:u};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=wr(t.steps,n.stepDefinitionId);if(!a||a.type!=="loop")throw new Error(`Loop step definition '${n.stepDefinitionId}' not found`);let c=Bt(e.stepHistory,n.id),u=new Date().toISOString();if(i.action==="cancel")return await this.failExecution({...e,status:"planning",currentStepId:void 0,currentStepExecutionId:void 0,updatedAt:u},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:u,output:{iterations:s.nextIteration,exitedOnMaxIterations:!0,humanAction:"continue"}})),updatedAt:u});return this.emit({type:"human_answered",jobId:I.id,answers:i,timestamp:u}),this.emit({type:"step_completed",jobId:I.id,stepDefinitionId:a.id,timestamp:u}),c?.parentLoopExecutionId!=null&&c.iterationIndex!=null?this.continueLoopAfterBody(I,t,c.parentLoopExecutionId,c.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:u});this.emit({type:"human_answered",jobId:b.id,answers:i,timestamp:u});let S=await this.runLoopStep(b,t,a,n.id,c?.parentLoopExecutionId,c?.iterationIndex,s.nextIteration,m);return S.outcome!=="completed"?S.job:c?.parentLoopExecutionId!=null&&c.iterationIndex!=null?this.continueLoopAfterBody(S.job,t,c.parentLoopExecutionId,c.iterationIndex):this.continueTopLevelAfter(S.job,t,a.id)}async continueLoopAfterBody(e,t,n,o){let i=ct(e.stepHistory,n);if(!i)throw new Error(`Loop execution ${n} not found`);let s=wr(t.steps,i.stepDefinitionId);if(!s||s.type!=="loop")throw new Error(`Loop step '${i.stepDefinitionId}' not found`);let a=Bt(e.stepHistory,n),c=i.output?.effectiveMaxIterations??s.maxIterations,u=e;if(nu(s.until,u.context))u=await this.finishExecution(u,n,s.id,{iterations:o+1});else{let d=o+1,m=await this.runLoopStep(u,t,s,n,a?.parentLoopExecutionId,a?.iterationIndex,d,c);if(m.outcome!=="completed")return m.job;u=m.job}return a?.parentLoopExecutionId!=null&&a.iterationIndex!=null?this.continueLoopAfterBody(u,t,a.parentLoopExecutionId,a.iterationIndex):this.continueTopLevelAfter(u,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=wr(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(),c=ee(e.stepHistory,n,d=>({...d,status:"waiting_for_children",childJobIds:s})),u=await this.persistJob({...e,status:"waiting_for_children",currentStepId:t.id,currentStepExecutionId:n,stepHistory:c,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:u}}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=mi(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 c=await this.workflowForJob(a),u=t.parentStepExecutionId,d=ct(a.stepHistory,u);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,c,u,d.stepDefinitionId,"One or more child jobs failed");return}let S=s.slice().sort((A,Ve)=>(A.fanOutIndex??0)-(Ve.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,u,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,c,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=mi(i,m=>m.fanOutIndex);if(!s||s.groupCount!==o.resolvedSubjects.length||!s.allTerminal)return;let{activeJobs:a}=s,c=Gc(a),u=new Date().toISOString(),d=await this.batches.update(o.id,{status:c,completedAt:u});if(!d)return;if(this.emit({type:"batch_completed",batchId:d.id,summary:a.map(m=>({jobId:m.id,status:m.status})),timestamp:u}),!d.notificationSent){let m=await this.workflowForJob(t),b=d.notificationOverride??m.notificationPolicy,S=c==="completed"?"on_complete":"on_fail";b.triggers.includes(S)&&await this.notifications.send({title:`Batch ${c}: ${m.name}`,body:`JobBatch ${d.id} finished with status '${c}' (${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 zc(t.contextFileIds??[],this.contextFiles,this.logger),i=Dt(e),s=gr(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 c=await this.providers.getAgentProvider(a).run({objective:s,outputFormat:t.outputFormat,knowledge:o,context:{...i,stepId:t.id},...e.worktreePath?{cwd:e.worktreePath}:{}}),u=Vc(t.outputFormat,c.parsed);return this.finishExecution(e,n,t.id,u)}async executeGitStep(e,t,n){let o=qt(t.params,Dt(e));switch(t.operation){case"create_worktree":{let i=await tu({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=St(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=St(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:St(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=gr(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 c=this.providers.getDocumentationProvider(i);switch(t){case"get_subject":return c.get(s);case"get_content":return c.getContent(s);case"get_comments":return c.getComments(s);case"post_comment":return await c.postComment(s,St(n,"body")),{posted:!0};case"update_status":throw new Error(`Provider action '${t}' is not valid for subject type 'documentation'`);default:{let u=t;throw new Error(`Unknown provider action: ${u}`)}}}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,St(n,"body")),{posted:!0};case"update_status":return await a.updateStatus(s,St(n,"status")),{status:St(n,"status")};case"get_content":throw new Error(`Provider action 'get_content' is not valid for subject type '${o}'`);default:{let c=t;throw new Error(`Unknown provider action: ${c}`)}}}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(!ec(s))throw new Error(`Provider instance '${i.providerId}' does not support extended actions. Available: none`);let a=await s.listExtendedActions(),c=a.find(m=>m.actionId===i.actionId);if(!c)throw new Error(`Provider '${i.providerId}' has no extended action '${i.actionId}'. Available: ${Ot(a)}`);let u=qt(i.params??{},Dt(e))??{};dn(c,u);let d=await s.executeExtendedAction(i.actionId,{...u,subjectId:o.subjectId});return this.finishExecution(e,n,t.id,d)}async executeShellStep(e,t,n){let o=gr(t.command,Dt(e)),i=e.worktreePath??process.cwd();try{let s=await Ym(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,c=a.stderr??"",u=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}): ${c||u||a.message||o}`)}}async pauseForInteraction(e,t,n,o){let i=new Date().toISOString(),s=eh(t,n.id),a=s!=null?e.context[s]:void 0,c=ee(e.stepHistory,o,b=>({...b,status:"pending"})),u=await this.persistJob({...e,status:"waiting_for_human",currentStepId:n.id,currentStepExecutionId:o,stepHistory:c,updatedAt:i}),d=Uc(n.interaction,a);return this.emit({type:"waiting_for_human",jobId:u.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 ${u.id} is waiting for human input on step '${n.id}'`,jobId:u.id}),u}async finishExecution(e,t,n,o,i={}){let s=new Date().toISOString(),a=ee(e.stepHistory,t,u=>({...u,status:"completed",completedAt:s,output:o})),c=await this.persistJob({...e,...i,context:{...e.context,[n]:o},stepHistory:a,updatedAt:s});return this.emit({type:"step_completed",jobId:c.id,stepDefinitionId:n,timestamp:s}),c}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(),c=ee(e.stepHistory,n,d=>({...d,status:"failed",completedAt:a,error:s})),u=await this.persistJob({...e,status:"failed",currentStepId:o,currentStepExecutionId:n,stepHistory:c,completedAt:a,updatedAt:a});return this.emit({type:"step_failed",jobId:u.id,stepDefinitionId:o,error:s,timestamp:a}),u.status==="cancelled"?(await this.onBatchMemberTerminal(u.id),u):(this.emit({type:"job_failed",jobId:u.id,error:s,timestamp:a}),await this.onBatchMemberTerminal(u.id),!u.batchId&&t.notificationPolicy.triggers.includes("on_fail")&&await this.notifications.send({title:`Job failed: ${t.name}`,body:`Job ${u.id} failed on step '${o}': ${s}`,jobId:u.id}),u)}async resolveSubjectContext(e,t){if(e.appliesTo==="none")return;let n=th(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 xi(this.providers.ticketInstanceIds(),t=>this.providers.getTicketProvider(t).get(e),`Ticket not found: ${e}`)}async getPullRequestById(e){return xi(this.providers.repoInstanceIds(),t=>this.providers.getRepoProvider(t).get(e),`Pull request not found: ${e}`)}async getDocumentationById(e){return xi(this.providers.documentationInstanceIds(),t=>this.providers.getDocumentationProvider(t).get(e),`Documentation page not found: ${e}`)}};we=vi=Vm([Gm(),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(De)),pe(10,de(E)),pe(11,de(bt)),Km("design:paramtypes",[O,z,se,ie,ye,F,Object,ae,ce,De,Object,bt])],we)});import{Module as nh}from"@nestjs/common";var rh,Ft,ji=l(()=>{"use strict";dr();Cn();On();Jc();Ln();gi();rh=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=rh([nh({imports:[Re,st,at,qn],providers:[bt,we],exports:[we]})],Ft)});import{Catch as ih}from"@nestjs/common";var oh,Un,iu=l(()=>{"use strict";R();oh=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=oh([ih(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 sh}from"node:crypto";function ah(){return sh()}function Mn(r){let e=r.id??ah(),t=sa(r.steps),n=su(r.steps,t);return{...r,id:e,steps:n}}function su(r,e){return r.map(t=>{let n=t.id;return n||(n=na(t.name,e),e.add(n)),t.type==="loop"?{...t,id:n,steps:su(t.steps,e)}:{...t,id:n}})}var Ii=l(()=>{"use strict";C()});function au(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(!Sa(r.appliesTo,t))throw new h(`subjectType '${t}' is not included in workflow '${e}' appliesTo`);return r}function cu(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 uu(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: ${uu(t.error)}`);let n=Mn(t.data),o=ht.safeParse(n);if(!o.success)throw new h(`Validation failed: ${uu(o.error)}`);return Wn(o.data),r.create(o.data)}var _i=l(()=>{"use strict";C();R();Sr();Ii()});import{Body as lu,Controller as ch,Delete as uh,Get as pu,HttpCode as lh,Inject as ph,Param as Pi,Patch as dh,Post as fh,Query as mh}from"@nestjs/common";var Nt,U,xt,Fe,du=l(()=>{"use strict";C();mt();R();ne();Ii();_i();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)},xt=function(r,e){return function(t,n){e(t,n,r)}},Fe=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 c=o.error.issues.map(u=>`${u.path.join(".")||"(root)"}: ${u.message}`).join("; ");throw new h(`Validation failed: ${c}`)}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([pu(),xt(0,mh("subjectHandling")),U("design:type",Function),U("design:paramtypes",[String]),U("design:returntype",Promise)],Fe.prototype,"list",null);Nt([pu(":id"),xt(0,Pi("id")),U("design:type",Function),U("design:paramtypes",[String]),U("design:returntype",Promise)],Fe.prototype,"get",null);Nt([fh(),xt(0,lu()),U("design:type",Function),U("design:paramtypes",[Object]),U("design:returntype",Promise)],Fe.prototype,"create",null);Nt([dh(":id"),xt(0,Pi("id")),xt(1,lu(new v(tt))),U("design:type",Function),U("design:paramtypes",[String,Object]),U("design:returntype",Promise)],Fe.prototype,"update",null);Nt([uh(":id"),lh(204),xt(0,Pi("id")),U("design:type",Function),U("design:paramtypes",[String]),U("design:returntype",Promise)],Fe.prototype,"remove",null);Fe=Nt([ch("workflows"),xt(0,ph(O)),U("design:paramtypes",[O])],Fe)});function hh(r){return mu(r.workflowDefinition.steps,"steps")}function fu(r){let e=hh(r);if(e.length>0)throw new Error(`Workflow library entry '${r.id}' is not portable: ${e.join(", ")}`)}function mu(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(...mu(n.steps,`${i}.steps`))}),t}var hu=l(()=>{"use strict"});function yu(){return structuredClone(Ei)}function gu(r){let e=Ei.find(t=>t.id===r);return e?structuredClone(e):void 0}var yh,gh,Ei,wu=l(()=>{"use strict";hu();yh={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"]}}},gh={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(()=>($l(),Cw));
33
+ Testing: {{testing-review}}`,outputFormat:"free_text"}],notificationPolicy:{triggers:["on_fail","on_complete"]}}},Ei=[yh,gh];for(let r of Ei)fu(r)});import{Controller as wh,Get as bh,Inject as Sh,Param as xh,Post as vh}from"@nestjs/common";var Ri,vt,bu,Jt,Su=l(()=>{"use strict";mt();R();wu();_i();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},vt=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},bu=function(r,e){return function(t,n){e(t,n,r)}},Jt=class{workflows;constructor(e){this.workflows=e}list(){return yu()}async add(e){let t=gu(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([bh(),vt("design:type",Function),vt("design:paramtypes",[]),vt("design:returntype",Array)],Jt.prototype,"list",null);Ri([vh(":id/add"),bu(0,xh("id")),vt("design:type",Function),vt("design:paramtypes",[String]),vt("design:returntype",Promise)],Jt.prototype,"add",null);Jt=Ri([wh("workflow-library"),bu(0,Sh(O)),vt("design:paramtypes",[O])],Jt)});import{Body as Ai,Controller as jh,Delete as Ih,Get as Ci,HttpCode as _h,Inject as ki,Param as Vn,Patch as xu,Post as Ph,Query as Eh}from"@nestjs/common";var lt,T,be,Se,vu=l(()=>{"use strict";C();qr();mt();R();ne();Sr();$t();yi();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);au(n,e,t)}};lt([Ci(),be(0,Eh("subjectType")),T("design:type",Function),T("design:paramtypes",[String]),T("design:returntype",Promise)],Se.prototype,"list",null);lt([xu("reorder"),be(0,Ai(new v(Mr))),T("design:type",Function),T("design:paramtypes",[Object]),T("design:returntype",Promise)],Se.prototype,"reorder",null);lt([Ci(":id/subjects"),be(0,Vn("id")),T("design:type",Function),T("design:paramtypes",[String]),T("design:returntype",Promise)],Se.prototype,"listSubjects",null);lt([Ci(":id"),be(0,Vn("id")),T("design:type",Function),T("design:paramtypes",[String]),T("design:returntype",Promise)],Se.prototype,"get",null);lt([Ph(),be(0,Ai(new v(Lr))),T("design:type",Function),T("design:paramtypes",[Object]),T("design:returntype",Promise)],Se.prototype,"create",null);lt([xu(":id"),be(0,Vn("id")),be(1,Ai(new v(Ur))),T("design:type",Function),T("design:paramtypes",[String,Object]),T("design:returntype",Promise)],Se.prototype,"update",null);lt([Ih(":id"),_h(204),be(0,Vn("id")),T("design:type",Function),T("design:paramtypes",[String]),T("design:returntype",Promise)],Se.prototype,"remove",null);Se=lt([jh("views"),be(0,ki(ie)),be(1,ki(O)),be(2,ki(F)),T("design:paramtypes",[ie,O,F])],Se)});import{Body as Ti,Controller as Rh,Delete as kh,Get as Iu,HttpCode as Ah,Inject as ju,Param as Oi,Patch as _u,Post as Ch}from"@nestjs/common";var jt,q,pt,ke,Pu=l(()=>{"use strict";C();Jo();mt();R();ne();Sr();jt=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)},pt=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);cu(t,e)}};jt([Iu(),q("design:type",Function),q("design:paramtypes",[]),q("design:returntype",Promise)],ke.prototype,"list",null);jt([_u("reorder"),pt(0,Ti(new v(en))),q("design:type",Function),q("design:paramtypes",[Object]),q("design:returntype",Promise)],ke.prototype,"reorder",null);jt([Iu(":id"),pt(0,Oi("id")),q("design:type",Function),q("design:paramtypes",[String]),q("design:returntype",Promise)],ke.prototype,"get",null);jt([Ch(),pt(0,Ti(new v(Yr))),q("design:type",Function),q("design:paramtypes",[Object]),q("design:returntype",Promise)],ke.prototype,"create",null);jt([_u(":id"),pt(0,Oi("id")),pt(1,Ti(new v(Zr))),q("design:type",Function),q("design:paramtypes",[String,Object]),q("design:returntype",Promise)],ke.prototype,"update",null);jt([kh(":id"),Ah(204),pt(0,Oi("id")),q("design:type",Function),q("design:paramtypes",[String]),q("design:returntype",Promise)],ke.prototype,"remove",null);ke=jt([Rh("workflow-shortcuts"),pt(0,ju(qe)),pt(1,ju(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 $i=l(()=>{"use strict"});import{z as Q}from"zod";var zn,Qn,Xn,Yn,qi=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 Th,Get as Ru,HttpCode as ku,Inject as Eu,Param as xr,Post as It,Query as Ne}from"@nestjs/common";import"zod";function Bi(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,$,Oh,oe,Au=l(()=>{"use strict";Ln();lr();R();ne();$i();qi();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)}},Oh=["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,c,u){if(t!=null&&t!==""&&!Oh.includes(t))throw new h(`Invalid status filter: ${t}`);let d=Bi(i,"topLevelOnly"),m=Bi(s,"terminal"),b=Bi(a,"liveWorktree"),{limit:S,offset:I}=Kn(c,u),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)}};Ae([Ru(),$(0,Ne("workflowId")),$(1,Ne("status")),$(2,Ne("batchId")),$(3,Ne("parentJobId")),$(4,Ne("topLevelOnly")),$(5,Ne("terminal")),$(6,Ne("liveWorktree")),$(7,Ne("limit")),$(8,Ne("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([It("latest-by-subject"),ku(200),$(0,Zn(new v(Xn))),k("design:type",Function),k("design:paramtypes",[Object]),k("design:returntype",Promise)],oe.prototype,"latestBySubject",null);Ae([It("delete-worktrees"),ku(200),$(0,Zn(new v(Yn))),k("design:type",Function),k("design:paramtypes",[Object]),k("design:returntype",Promise)],oe.prototype,"deleteWorktrees",null);Ae([Ru(":id"),$(0,xr("id")),k("design:type",Function),k("design:paramtypes",[String]),k("design:returntype",Promise)],oe.prototype,"get",null);Ae([It(),$(0,Zn(new v(zn))),k("design:type",Function),k("design:paramtypes",[Object]),k("design:returntype",Promise)],oe.prototype,"create",null);Ae([It(":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([It(":id/retry"),$(0,xr("id")),k("design:type",Function),k("design:paramtypes",[String]),k("design:returntype",Promise)],oe.prototype,"retry",null);Ae([It(":id/retry-step"),$(0,xr("id")),k("design:type",Function),k("design:paramtypes",[String]),k("design:returntype",Promise)],oe.prototype,"retryStep",null);Ae([It(":id/cancel"),$(0,xr("id")),k("design:type",Function),k("design:paramtypes",[String]),k("design:returntype",Promise)],oe.prototype,"cancel",null);oe=Ae([Th("jobs"),$(0,Eu(z)),$(1,Eu(we)),k("design:paramtypes",[z,we])],oe)});import{z as te}from"zod";var eo,to,Di=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 $h,Controller as qh,Get as Ji,Inject as Fi,Param as Li,Post as Cu,Query as Ni}from"@nestjs/common";import"zod";var Lt,M,Ce,Je,Tu=l(()=>{"use strict";Ln();Br();lr();R();ne();$i();Di();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)},Ce=function(r,e){return function(t,n){e(t,n,r)}},Je=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([Ji(),Ce(0,Ni("workflowId")),Ce(1,Ni("limit")),Ce(2,Ni("offset")),M("design:type",Function),M("design:paramtypes",[String,String,String]),M("design:returntype",Promise)],Je.prototype,"list",null);Lt([Ji(":id"),Ce(0,Li("id")),M("design:type",Function),M("design:paramtypes",[String]),M("design:returntype",Promise)],Je.prototype,"get",null);Lt([Ji(":id/jobs"),Ce(0,Li("id")),M("design:type",Function),M("design:paramtypes",[String]),M("design:returntype",Promise)],Je.prototype,"listJobs",null);Lt([Cu(),Ce(0,$h(new v(to))),M("design:type",Function),M("design:paramtypes",[Object]),M("design:returntype",Promise)],Je.prototype,"launch",null);Lt([Cu(":id/cancel"),Ce(0,Li("id")),M("design:type",Function),M("design:paramtypes",[String]),M("design:returntype",Promise)],Je.prototype,"cancel",null);Je=Lt([qh("batches"),Ce(0,Fi(se)),Ce(1,Fi(z)),Ce(2,Fi(we)),M("design:paramtypes",[se,z,we])],Je)});import{Body as Ou,Controller as Bh,Delete as Dh,Get as $u,HttpCode as Fh,Inject as Nh,Param as Ui,Patch as Jh,Post as Lh,Query as Uh}from"@nestjs/common";var Ut,W,_t,Le,qu=l(()=>{"use strict";C();Fo();R();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)},_t=function(r,e){return function(t,n){e(t,n,r)}},Le=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([$u(),_t(0,Uh("enabled")),W("design:type",Function),W("design:paramtypes",[String]),W("design:returntype",Promise)],Le.prototype,"list",null);Ut([$u(":id"),_t(0,Ui("id")),W("design:type",Function),W("design:paramtypes",[String]),W("design:returntype",Promise)],Le.prototype,"get",null);Ut([Lh(),_t(0,Ou(new v(Ct))),W("design:type",Function),W("design:paramtypes",[Object]),W("design:returntype",Promise)],Le.prototype,"create",null);Ut([Jh(":id"),_t(0,Ui("id")),_t(1,Ou(new v(Ct.partial().omit({id:!0})))),W("design:type",Function),W("design:paramtypes",[String,Object]),W("design:returntype",Promise)],Le.prototype,"update",null);Ut([Dh(":id"),Fh(204),_t(0,Ui("id")),W("design:type",Function),W("design:paramtypes",[String]),W("design:returntype",Promise)],Le.prototype,"remove",null);Le=Ut([Bh("schedules"),_t(0,Nh($e)),W("design:paramtypes",[$e])],Le)});import{Controller as Mh,Inject as Wh,Query as Bu,Sse as Hh}from"@nestjs/common";import{Observable as Fu}from"rxjs";var Du,ro,Mi,vr,Nu=l(()=>{"use strict";Tn();Du=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)},Mi=function(r,e){return function(t,n){e(t,n,r)}},vr=class{events;constructor(e){this.events=e}stream(e,t){return new Fu(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()}})}};Du([Hh(),Mi(0,Bu("jobId")),Mi(1,Bu("batchId")),ro("design:type",Function),ro("design:paramtypes",[String,String]),ro("design:returntype",Fu)],vr.prototype,"stream",null);vr=Du([Mh("events"),Mi(0,Wh(ye)),ro("design:paramtypes",[ye])],vr)});import{extendZodWithOpenApi as Vh}from"@asteasolutions/zod-to-openapi";import{z as Kh}from"zod";var Ju=l(()=>{"use strict";Vh(Kh)});import{z as Lu}from"zod";var no,Wi=l(()=>{"use strict";no=Lu.object({value:Lu.string().min(1)})});import{z as xe}from"zod";var TP,Gh,Uu,Mu=l(()=>{"use strict";TP=xe.object({path:xe.string().optional(),mode:xe.enum(["directories","files"]).optional(),extensions:xe.string().optional()}),Gh=xe.object({name:xe.string().min(1),path:xe.string().min(1),isDirectory:xe.boolean()}),Uu=xe.object({path:xe.string().min(1),entries:xe.array(Gh)})});import{z as p}from"zod";function my(r){let e=p.toJSONSchema(r),{$schema:t,...n}=e;return n}function Hu(r){let e=(t,n)=>r.registerComponent("schemas",t,my(n)).ref;return{WorkflowDefinition:e("WorkflowDefinition",ht),WorkflowDefinitionInput:e("WorkflowDefinitionInput",tt),UpdateWorkflowBody:e("UpdateWorkflowBody",sy),SubjectView:e("SubjectView",Jr),CreateSubjectViewBody:e("CreateSubjectViewBody",Lr),ReorderViewsBody:e("ReorderViewsBody",Mr),UpdateViewBody:e("UpdateViewBody",cy),WorkflowShortcut:e("WorkflowShortcut",Xr),CreateWorkflowShortcutBody:e("CreateWorkflowShortcutBody",Yr),UpdateWorkflowShortcutBody:e("UpdateWorkflowShortcutBody",Zr),ReorderShortcutsBody:e("ReorderShortcutsBody",en),Schedule:e("Schedule",Ct),UpdateScheduleBody:e("UpdateScheduleBody",uy),EngineSettings:e("EngineSettings",rn),UpdateSettingsBody:e("UpdateSettingsBody",py),SettingsPatchResponse:e("SettingsPatchResponse",fy),ProviderInstanceConfig:e("ProviderInstanceConfig",tn),CreateProviderInstanceBody:e("CreateProviderInstanceBody",on),UpdateProviderInstanceBody:e("UpdateProviderInstanceBody",sn),ProviderInstanceMutationResponse:e("ProviderInstanceMutationResponse",dy),SetSecretBody:e("SetSecretBody",no),CreateJobBody:e("CreateJobBody",zn),ResumeJobBody:e("ResumeJobBody",Qn),LatestBySubjectBody:e("LatestBySubjectBody",Xn),LatestBySubjectResponse:e("LatestBySubjectResponse",ly),LaunchBody:e("LaunchBody",to),Job:e("Job",Hi),JobBatch:e("JobBatch",Wu),LaunchResponse:e("LaunchResponse",ty),HealthResponse:e("HealthResponse",ry),ProviderStatus:e("ProviderStatus",ny),QueryTemplate:e("QueryTemplate",Ys),ProviderActionDescriptor:e("ProviderActionDescriptor",Zs),PreviewModelsBody:e("PreviewModelsBody",an),PreviewModel:e("PreviewModel",Ja),ResolveQueryTemplateBody:e("ResolveQueryTemplateBody",Nr),ResolveQueryTemplateResponse:e("ResolveQueryTemplateResponse",ea),ErrorResponse:e("ErrorResponse",oy),EngineEvent:e("EngineEvent",iy),Subject:e("Subject",oo),WorkflowLibraryEntry:e("WorkflowLibraryEntry",ay),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",Uu)}}var zh,Qh,Xh,Yh,oo,Zh,ey,Hi,Wu,ty,ry,ny,oy,iy,sy,ay,cy,uy,ly,py,dy,fy,_,Vi,Ki=l(()=>{"use strict";Ju();C();qi();Di();Wi();Mu();zh=p.enum(["pending","planning","waiting_for_human","waiting_for_children","implementing","testing","completed","failed","cancelled"]),Qh=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()}),Xh=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()}),Yh=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",[Qh,Xh,Yh]),Zh=p.discriminatedUnion("mode",[p.object({mode:p.literal("single"),subject:oo}),p.object({mode:p.literal("collection"),subjects:p.array(oo)})]),ey=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()}),Hi=p.object({id:p.string(),workflowId:p.string(),status:zh,subjectContext:Zh.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:ht.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(ey),createdAt:p.string(),updatedAt:p.string(),completedAt:p.string().optional()}),Wu=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()}),ty=p.discriminatedUnion("kind",[p.object({kind:p.literal("job"),job:Hi}),p.object({kind:p.literal("batch"),batch:Wu})]),ry=p.object({ok:p.boolean(),service:p.string(),timestamp:p.string()}),ny=p.object({providerId:p.string(),secretKey:p.string(),configured:p.boolean()}),oy=p.object({error:p.string()}),iy=p.object({type:p.string(),timestamp:p.string()}).passthrough(),sy=tt,ay=p.object({id:p.string().min(1),source:p.enum(["example","community","official"]),name:p.string().min(1),description:p.string(),workflowDefinition:tt}),cy=Ur,uy=Ct.partial().omit({id:!0}),ly=p.record(p.string(),Hi.nullable()),py=nn,dy=p.object({settings:rn,restartRequired:p.literal(!0)}),fy=p.object({settings:rn,restartRequired:p.boolean()}),_=p.object({id:p.string().min(1)}),Vi=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 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 Vu(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:j.object({subjectHandling:j.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:j.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:Vi.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: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:Vi.extend({workflowId:j.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:j.object({path:j.string().optional(),mode:j.enum(["directories","files"]).optional(),extensions:j.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:j.object({enabled:j.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:j.object({providerId:j.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:j.object({providerId:j.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:j.object({providerId:j.string().min(1),templateId:j.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:j.object({id:j.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:j.object({id:j.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:j.object({id:j.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:j.object({key:j.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: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 Ku=l(()=>{"use strict";C();Ki()});import{OpenAPIRegistry as hy,OpenApiGeneratorV31 as yy}from"@asteasolutions/zod-to-openapi";function Gu(){if(io)return io;let r=new hy,e=Hu(r);return Vu(r,e),io=new yy(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,zu=l(()=>{"use strict";Ki();Ku()});import{Controller as gy,Get as wy,Header as by}from"@nestjs/common";var Qu,Gi,jr,Xu=l(()=>{"use strict";zu();Qu=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},Gi=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},jr=class{getOpenApiDocument(){return Gu()}};Qu([wy("openapi.json"),by("Content-Type","application/json"),Gi("design:type",Function),Gi("design:paramtypes",[]),Gi("design:returntype",void 0)],jr.prototype,"getOpenApiDocument",null);jr=Qu([gy()],jr)});import{Controller as Sy,Get as zi,Inject as so,Param as ao,Post as Yu,Body as Zu,HttpCode as el}from"@nestjs/common";var Mt,H,Te,Ue,tl=l(()=>{"use strict";Ko();oi();ii();ci();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)},Te=function(r,e){return function(t,n){e(t,n,r)}},Ue=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([zi("status"),H("design:type",Function),H("design:paramtypes",[]),H("design:returntype",Promise)],Ue.prototype,"status",null);Mt([Yu("preview-models"),el(200),Te(0,Zu(new v(an))),H("design:type",Function),H("design:paramtypes",[Object]),H("design:returntype",Promise)],Ue.prototype,"previewAvailableModels",null);Mt([zi(":providerId/query-templates"),Te(0,ao("providerId")),H("design:type",Function),H("design:paramtypes",[String]),H("design:returntype",Promise)],Ue.prototype,"listQueryTemplates",null);Mt([zi(":providerId/actions"),Te(0,ao("providerId")),H("design:type",Function),H("design:paramtypes",[String]),H("design:returntype",Promise)],Ue.prototype,"listExtendedActions",null);Mt([Yu(":providerId/query-templates/:templateId/resolve"),el(200),Te(0,ao("providerId")),Te(1,ao("templateId")),Te(2,Zu(new v(Nr))),H("design:type",Function),H("design:paramtypes",[String,String,Object]),H("design:returntype",Promise)],Ue.prototype,"resolveQueryTemplate",null);Ue=Mt([Sy("providers"),Te(0,so(rt)),Te(1,so(nt)),Te(2,so(ot)),Te(3,so(it)),H("design:paramtypes",[rt,nt,ot,it])],Ue)});import{Body as xy,Controller as vy,Get as jy,Inject as Iy,Patch as _y}from"@nestjs/common";var Qi,Pt,rl,Wt,nl=l(()=>{"use strict";C();Ee();ne();Qi=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)},rl=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:Va(e)}}};Qi([jy(),Pt("design:type",Function),Pt("design:paramtypes",[]),Pt("design:returntype",Promise)],Wt.prototype,"get",null);Qi([_y(),rl(0,xy(new v(nn))),Pt("design:type",Function),Pt("design:paramtypes",[Object]),Pt("design:returntype",Promise)],Wt.prototype,"update",null);Wt=Qi([vy("settings"),rl(0,Iy(E)),Pt("design:paramtypes",[E])],Wt)});function Xi(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 ol(r){let{defaultAgent:e,...t}=r;return t}var il=l(()=>{"use strict";C()});import{Body as sl,Controller as Py,Delete as Ey,Get as al,HttpCode as Ry,Inject as ky,Param as Yi,Patch as Ay,Post as Cy}from"@nestjs/common";var Vt,V,Ht,Me,cl=l(()=>{"use strict";C();Ee();R();ne();il();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)}},Me=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=ol(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:Xi({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(u=>u.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:Xi({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([al(),V("design:type",Function),V("design:paramtypes",[]),V("design:returntype",Promise)],Me.prototype,"list",null);Vt([al(":id"),Ht(0,Yi("id")),V("design:type",Function),V("design:paramtypes",[String]),V("design:returntype",Promise)],Me.prototype,"get",null);Vt([Cy(),Ht(0,sl(new v(on))),V("design:type",Function),V("design:paramtypes",[Object]),V("design:returntype",Promise)],Me.prototype,"create",null);Vt([Ay(":id"),Ht(0,Yi("id")),Ht(1,sl(new v(sn))),V("design:type",Function),V("design:paramtypes",[String,Object]),V("design:returntype",Promise)],Me.prototype,"update",null);Vt([Ey(":id"),Ry(200),Ht(0,Yi("id")),V("design:type",Function),V("design:paramtypes",[String]),V("design:returntype",Promise)],Me.prototype,"remove",null);Me=Vt([Py("provider-instances"),Ht(0,ky(E)),V("design:paramtypes",[E])],Me)});import{Body as Ty,Controller as Oy,HttpCode as $y,Inject as qy,Param as By,Post as Dy}from"@nestjs/common";var ul,co,Zi,Ir,ll=l(()=>{"use strict";Oe();R();ne();Wi();ul=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)},Zi=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)}};ul([Dy(":key"),$y(204),Zi(0,By("key")),Zi(1,Ty(new v(no))),co("design:type",Function),co("design:paramtypes",[String,Object]),co("design:returntype",Promise)],Ir.prototype,"set",null);Ir=ul([Oy("secrets"),Zi(0,qy(fe)),co("design:paramtypes",[Function])],Ir)});import{readFile as Fy}from"node:fs/promises";async function es(r){try{await Fy(r,"utf8")}catch(e){let t=e instanceof Error?e.message:String(e);throw new h(`Cannot read context file at '${r}': ${t}`)}}var pl=l(()=>{"use strict";R()});import{Body as dl,Controller as Ny,Delete as Jy,Get as fl,HttpCode as Ly,Inject as Uy,Param as ts,Patch as My,Post as Wy}from"@nestjs/common";import{randomUUID as Hy}from"node:crypto";var Gt,K,Kt,We,ml=l(()=>{"use strict";C();Dr();R();ne();pl();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)}},We=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 es(e.path),this.files.create({id:e.id??Hy(),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 es(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([fl(),K("design:type",Function),K("design:paramtypes",[]),K("design:returntype",Promise)],We.prototype,"list",null);Gt([fl(":id"),Kt(0,ts("id")),K("design:type",Function),K("design:paramtypes",[String]),K("design:returntype",Promise)],We.prototype,"get",null);Gt([Wy(),Kt(0,dl(new v(Vr))),K("design:type",Function),K("design:paramtypes",[Object]),K("design:returntype",Promise)],We.prototype,"create",null);Gt([My(":id"),Kt(0,ts("id")),Kt(1,dl(new v(Kr))),K("design:type",Function),K("design:paramtypes",[String,Object]),K("design:returntype",Promise)],We.prototype,"update",null);Gt([Jy(":id"),Ly(204),Kt(0,ts("id")),K("design:type",Function),K("design:paramtypes",[String]),K("design:returntype",Promise)],We.prototype,"remove",null);We=Gt([Ny("context-files"),Kt(0,Uy(ae)),K("design:paramtypes",[ae])],We)});import{execFile as Vy}from"node:child_process";import{stat as Ky}from"node:fs/promises";import{resolve as rs}from"node:path";import{promisify as Gy}from"node:util";async function ns(r){let e=rs(r);try{if((await zy("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 os(r,e){let t=rs(r),n=rs(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 Ky(n)).isDirectory())throw new h(`Worktree base '${n}' exists and is not a directory`)}catch(o){if(o instanceof h)throw o}}var zy,hl=l(()=>{"use strict";R();bi();zy=Gy(Vy)});import{Body as yl,Controller as Qy,Delete as Xy,Get as gl,HttpCode as Yy,Inject as Zy,Param as is,Patch as eg,Post as tg}from"@nestjs/common";import{randomUUID as rg}from"node:crypto";var Qt,G,zt,He,wl=l(()=>{"use strict";C();Fr();R();ne();hl();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)}},He=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 ns(e.localPath),await os(e.localPath,e.worktreeBasePath),this.repos.create({id:e.id??rg(),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 ns(o),await os(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([gl(),G("design:type",Function),G("design:paramtypes",[]),G("design:returntype",Promise)],He.prototype,"list",null);Qt([gl(":id"),zt(0,is("id")),G("design:type",Function),G("design:paramtypes",[String]),G("design:returntype",Promise)],He.prototype,"get",null);Qt([tg(),zt(0,yl(new v(zr))),G("design:type",Function),G("design:paramtypes",[Object]),G("design:returntype",Promise)],He.prototype,"create",null);Qt([eg(":id"),zt(0,is("id")),zt(1,yl(new v(Qr))),G("design:type",Function),G("design:paramtypes",[String,Object]),G("design:returntype",Promise)],He.prototype,"update",null);Qt([Xy(":id"),Yy(204),zt(0,is("id")),G("design:type",Function),G("design:paramtypes",[String]),G("design:returntype",Promise)],He.prototype,"remove",null);He=Qt([Qy("local-repositories"),zt(0,Zy(ce)),G("design:paramtypes",[ce])],He)});import{readdir as ng,stat as og}from"node:fs/promises";import{homedir as ig}from"node:os";import{join as sg,resolve as ag}from"node:path";async function bl(r,e={}){let t=r?.trim()?r.trim():ig(),n=ag(t),o;try{o=await og(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 ng(n,{encoding:"utf8",withFileTypes:!0})).filter(a=>a.name!=="."&&a.name!=="..").map(a=>({name:a.name,path:sg(n,a.name),isDirectory:a.isDirectory()})).filter(a=>cg(a,e)).sort((a,c)=>a.isDirectory!==c.isDirectory?a.isDirectory?-1:1:a.name.localeCompare(c.name))}catch(s){throw new h(`Cannot browse '${n}': ${s instanceof Error?s.message:String(s)}`)}return{path:n,entries:i}}function Sl(r){if(r==null||r.trim()==="")return;let e=r.split(",").map(t=>vl(t)).filter(t=>t!=null);return e.length>0?e:void 0}function xl(r){if(!(r==null||r.trim()==="")){if(r==="directories"||r==="files")return r;throw new h(`Invalid browse mode '${r}'`)}}function cg(r,e){if(e.mode==="directories")return r.isDirectory;if(r.isDirectory)return!0;let t=e.extensions?.map(o=>vl(o)).filter(Boolean);if(!t?.length)return!0;let n=r.name.toLowerCase();return t.some(o=>n.endsWith(o))}function vl(r){let e=r.trim().toLowerCase();if(e.length!==0)return e.startsWith(".")?e:`.${e}`}var jl=l(()=>{"use strict";R()});import{Controller as ug,Get as lg,Query as cs}from"@nestjs/common";var Il,ss,as,_r,_l=l(()=>{"use strict";jl();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},ss=function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},as=function(r,e){return function(t,n){e(t,n,r)}},_r=class{async browse(e,t,n){return bl(e,{mode:xl(t),extensions:Sl(n)})}};Il([lg("browse"),as(0,cs("path")),as(1,cs("mode")),as(2,cs("extensions")),ss("design:type",Function),ss("design:paramtypes",[String,String,String]),ss("design:returntype",Promise)],_r.prototype,"browse",null);_r=Il([ug("filesystem")],_r)});import{Module as dg}from"@nestjs/common";import{APP_FILTER as fg}from"@nestjs/core";var pg,uo,Pl=l(()=>{"use strict";dr();ji();On();iu();du();Su();vu();Pu();Au();Tu();qu();Nu();Xu();tl();nl();cl();ll();ml();wl();_l();Cn();jo();pg=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=pg([dg({imports:[Re,Ft,at,st,Rt],controllers:[Fe,Jt,Se,ke,oe,Je,Le,vr,jr,Ue,Wt,Me,Ir,We,He,_r],providers:[{provide:fg,useClass:Un}]})],uo)});import{Module as hg}from"@nestjs/common";var mg,lo,El=l(()=>{"use strict";ds();fs();ms();Cn();On();dr();ji();Pl();mg=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=mg([hg({imports:[Pr,Er,st,at,Re,Ft,uo],controllers:[Xt]})],lo)});import{apiReference as yg}from"@scalar/nestjs-api-reference";function Rl(r){r.use("/api/docs",yg({url:"/api/openapi.json",pageTitle:"Knoflows Engine API"}))}var kl=l(()=>{"use strict"});import{createServer as gg}from"node:net";function Al(r){return typeof r=="object"&&r!==null&&"code"in r&&r.code==="EADDRINUSE"}async function us(r,e=20){for(let t=0;t<e;t+=1){let n=r+t;if(await wg(n))return n}throw new Error(`No free port found in ${r}\u2013${r+e-1}`)}function wg(r){return new Promise(e=>{let t=gg();t.once("error",()=>{e(!1)}),t.once("listening",()=>{t.close(()=>e(!0))}),t.listen(r)})}var Cl=l(()=>{"use strict"});import{Catch as xg,HttpStatus as po,NotFoundException as vg}from"@nestjs/common";import{existsSync as Tl,statSync as jg}from"node:fs";import{extname as Ol,join as ls,normalize as Ig,relative as _g,sep as Pg}from"node:path";function $l(r){return(e,t,n)=>{if(e.method!=="GET"&&e.method!=="HEAD"){n();return}if((e.path??"").startsWith("/api")){n();return}let o=Eg(e.path??"/");if(o){let i=ls(r,o);if(Rg(r,i)){t.sendFile(o,{root:r},s=>{s&&n()});return}}if(ql(e)){Bl(t,r,i=>{i&&!t.headersSent&&t.status(po.NOT_FOUND).end()});return}t.status(po.NOT_FOUND).end()}}function ql(r){if(r.method!=="GET"&&r.method!=="HEAD")return!1;let e=r.path??"";if(e.startsWith("/api"))return!1;let t=Ol(e);return!(t&&t!==".html")}function Bl(r,e,t){r.sendFile("index.html",{root:e},t)}function Eg(r){if(r==="/"||r==="")return"index.html";let e=Ig(r.replace(/^\/+/,""));return!e||e==="."||e.startsWith("..")||!Ol(e)?null:e}function Rg(r,e){if(!Tl(e))return!1;try{if(!jg(e).isFile())return!1}catch{return!1}let t=_g(r,e);return t!==""&&!t.startsWith(`..${Pg}`)&&!t.startsWith("..")}function Dl(r){return ls(r,"index.html")}var bg,Sg,fo,Fl=l(()=>{"use strict";bg=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},Sg=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(ql(o)&&Tl(ls(this.staticRoot,"index.html"))){Bl(i,this.staticRoot,c=>{c&&!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=bg([xg(vg),Sg("design:paramtypes",[String])],fo)});import{existsSync as kg}from"node:fs";import{dirname as Ag,join as mo}from"node:path";import{fileURLToPath as Cg}from"node:url";function Nl(){let r=Ag(Cg(import.meta.url)),e=[mo(r,"../static"),mo(r,"../../static"),mo(r,"static")];for(let t of e)if(kg(mo(t,"index.html")))return t;return null}var Jl=l(()=>{"use strict"});var Bg={};import"reflect-metadata";import{existsSync as Tg}from"node:fs";import{Logger as Og}from"@nestjs/common";import{NestFactory as $g}from"@nestjs/core";async function qg(){let r=await $g.create(lo);r.enableCors(),r.setGlobalPrefix("api"),Rl(r);let e=Nl(),t=e?Dl(e):null;e&&t&&Tg(t)?(ho.log(`Serving UI from ${e}`),r.use($l(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 us(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(!Al(s))throw s;o=await us(o+1)}throw new Error(`Could not bind a free port starting at ${n}`)}var ho,Ll=l(()=>{"use strict";El();kl();Cl();Fl();Jl();ho=new Og("Bootstrap");qg()});import{readFileSync as Dg}from"node:fs";function Fg(){let r=Dg(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(Fg()):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(()=>(Ll(),Bg));