@agimon-ai/workflow-mcp 0.2.9 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -0
- package/dist/cli.cjs +4 -4
- package/dist/cli.mjs +4 -4
- package/dist/index.cjs +1 -1
- package/dist/index.mjs +1 -1
- package/dist/stdio-CMbfCrs1.cjs +55 -0
- package/dist/stdio-k5DKbtyw.mjs +55 -0
- package/package.json +5 -5
- package/dist/stdio-BPkG6mPS.cjs +0 -55
- package/dist/stdio-CAi-NNxh.mjs +0 -55
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import{Server as e}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as t,ListToolsRequestSchema as n}from"@modelcontextprotocol/sdk/types.js";import{z as r}from"zod";import{execFile as i,execFileSync as a,execSync as o,spawn as s}from"node:child_process";import{promisify as c}from"node:util";import{access as l,mkdir as u,readFile as d,readdir as f,rename as p,rm as m,unlink as h,writeFile as g}from"node:fs/promises";import{homedir as _,tmpdir as ee}from"node:os";import v,{basename as te,dirname as y,join as b,resolve as x}from"node:path";import{existsSync as S,mkdirSync as ne,readFileSync as C,rmSync as w,unlinkSync as T,watch as E,writeFileSync as D}from"node:fs";import{fileURLToPath as re}from"node:url";import{PortRegistryService as ie}from"@agimon-ai/foundation-port-registry";import{ProcessRegistryService as ae}from"@agimon-ai/foundation-process-registry";import{randomUUID as oe}from"node:crypto";import{createInterface as se}from"node:readline";import{load as ce}from"js-yaml";import{StdioServerTransport as le}from"@modelcontextprotocol/sdk/server/stdio.js";var O=class extends Error{code=`WORKFLOW_TOOL_NOT_FOUND`;constructor(e,t){super(`Unknown tool "${e}". Available tools: ${t.join(`, `)}`),this.toolName=e,this.availableTools=t,this.name=`WorkflowToolNotFoundError`}},ue=class extends Error{constructor(e,t,n={},r){super(e,r),this.code=t,this.context=n,this.name=`WorkflowToolError`}},k=class extends Error{constructor(e,t,n={},r){super(e,r),this.code=t,this.context=n,this.name=`CronError`}};const A=`# workflow-mcp:cron:`,j=`crontab`,de=`claude`,fe=`codex`,pe=de,me=`--cwd`,he=`CRON_WRITE_FAILED`,ge=r.enum([de,fe]),_e=r.object({name:r.string().min(1),cwd:r.string().min(1),cli:ge,schedule:r.string().min(1),prompt:r.string().optional(),promptFile:r.string().optional(),createdAt:r.string().min(1)}),ve=r.object({name:r.string().min(1),cwd:r.string().min(1),cli:ge.optional(),prompt:r.string().optional(),promptFile:r.string().optional(),schedule:r.string().optional(),intervalMinutes:r.number().positive().optional()});function ye(e){return`'${e.replace(/'/g,`'\\''`)}'`}function be(e,t,n,r){let i=n?ye(n):r?`"$(cat ${ye(r)})"`:void 0;if(e===`codex`){let e=[fe,`--approval-mode`,`full-auto`];return i&&e.push(`-q`,i),e.push(me,ye(t)),e.join(` `)}let a=[de,`--dangerously-skip-permissions`];return i&&a.push(`-p`,i),a.push(me,ye(t)),a.join(` `)}function xe(e){if(e<=0)throw Error(`Interval must be a positive number of minutes`);if(e<60)return`*/${e} * * * *`;let t=Math.floor(e/60);return t<24?`0 */${t} * * *`:`0 0 */${Math.floor(t/24)} * *`}const Se=c(i);var Ce=class{logger;constructor(e){this.logger=e??{info:e=>process.stdout.write(`${e}\n`),error:e=>console.error(e),warn:e=>console.error(e)}}async readCrontab(){try{let{stdout:e}=await Se(j,[`-l`]);return e}catch(e){let t=e.code;if(t===`ENOENT`||(e.stderr??``).includes(`no crontab for`))return``;throw this.logger.error(`[CronService.readCrontab] failed exitCode=${t}`),new k(`Failed to read current crontab.`,`CRON_READ_FAILED`,{exitCode:t},{cause:e})}}async writeCrontab(e){let t=``,n=i(j,[`-`]);n.stderr?.on(`data`,e=>{t+=e}),n.stdin?.write(e),n.stdin?.end(),await new Promise((r,i)=>{n.on(`close`,n=>{n===0?r():(this.logger.error(`[CronService.writeCrontab] failed exitCode=${n} stderr=${t}`),i(new k(`crontab rejected input (exit ${n}).`,he,{exitCode:n,stderr:t,contentLength:e.length})))}),n.on(`error`,e=>{this.logger.error(`[CronService.writeCrontab] spawn failed: ${e.message}`),i(new k(`Failed to spawn crontab process.`,he,{},{cause:e}))})})}async schedule(e){let t=e.cli??`claude`;if(!e.schedule&&!e.intervalMinutes)throw new k(`Either schedule (cron expression) or intervalMinutes must be provided.`,`CRON_INVALID_INPUT`,{name:e.name});let n=e.schedule??xe(e.intervalMinutes),r=be(t,e.cwd,e.prompt,e.promptFile),i=new Date().toISOString(),a=_e.parse({name:e.name,cwd:e.cwd,cli:t,schedule:n,prompt:e.prompt,promptFile:e.promptFile,createdAt:i}),o=await this.readCrontab(),s=this.removeCronBlock(o,e.name),c=`${`${A}${e.name}`}\n${`# workflow-mcp:meta:${JSON.stringify(a)}`}\n${`${n} ${r}`}`,l=s.trimEnd()?`${s.trimEnd()}\n${c}\n`:`${c}\n`;return await this.writeCrontab(l),this.logger.info(`Scheduled cron "${e.name}" [${n}]`),a}async list(){let e=await this.readCrontab(),t=[],n=e.split(`
|
|
2
|
+
`);for(let e=0;e<n.length;e++){let r=n[e];if(r.startsWith(`# workflow-mcp:meta:`))try{let e=r.slice(20),n=_e.parse(JSON.parse(e));t.push(n)}catch(t){this.logger.warn(`[CronService.list] skipping malformed metadata at line ${e+1}: ${t.message}`)}}return t}async remove(e){let t=await this.readCrontab(),n=this.removeCronBlock(t,e);return n===t?!1:(await this.writeCrontab(n),this.logger.info(`Removed cron "${e}"`),!0)}removeCronBlock(e,t){let n=e.split(`
|
|
3
|
+
`),r=[],i=`${A}${t}`,a=!1;for(let e of n){if(e===i){a=!0;continue}if(a){if(e.startsWith(`# workflow-mcp:meta:`))continue;a=!1;continue}r.push(e)}return r.join(`
|
|
4
|
+
`)}},we=class e{static TOOL_NAME=`list-crons`;constructor(e=new Ce){this.service=e}getInputSchema(){return r.object({})}getDefinition(){return{name:e.TOOL_NAME,description:`List all cron jobs scheduled via workflow-mcp, showing name, schedule, CLI, cwd, and prompt.`,inputSchema:r.toJSONSchema(r.object({}))}}async execute(){try{let e=await this.service.list();return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}catch(t){let n=new ue(`Failed to list cron jobs.`,`LIST_CRONS_TOOL_FAILED`,{tool:e.TOOL_NAME},{cause:t});return console.error(`[${e.TOOL_NAME}] ${n.message}`,n.context),{content:[{type:`text`,text:JSON.stringify({code:n.code,context:n.context,message:n.message},null,2)}],isError:!0}}}},Te=class extends Error{code=`INVALID_WORKFLOW_RUN_RECORD`;constructor(e,t,n){super(`Invalid workflow run record at "${e}": ${t}`,n),this.recordPath=e,this.name=`InvalidWorkflowRunRecordError`}},Ee=class extends Error{code=`WORKFLOW_RUN_CONFLICT`;constructor(e,t){super(`Workflow "${t}" is already running in workspace "${e}"`),this.workspace=e,this.runKey=t,this.name=`WorkflowRunConflictError`}};const De=r.record(r.string(),r.coerce.string()),Oe=r.object({description:r.string().optional(),required:r.boolean().optional(),default:r.string().optional(),type:r.string().optional(),options:r.array(r.string()).optional()}),ke=r.record(r.string(),r.string()),Ae=r.record(r.string(),r.string()),je=r.union([r.string(),Ae]),Me=r.object({"fail-fast":r.boolean().optional(),matrix:r.looseObject({include:r.array(ke).optional()}).optional()}),Ne=r.object({name:r.string().optional(),uses:r.string().optional(),run:je.optional(),interactiveRun:je.optional(),"timeout-minutes":r.number().optional(),env:De.optional(),with:r.record(r.string(),r.string()).optional(),"working-directory":r.string().optional(),if:r.string().optional(),"continue-on-error":r.boolean().optional(),"timeout-retries":r.number().optional(),id:r.string().optional()}),Pe=r.object({name:r.string(),run:r.string(),env:De.optional(),"working-directory":r.string().optional(),"ready-check":r.union([r.string(),r.boolean()]).optional(),"ready-timeout":r.number().optional(),host:r.string().optional(),port:r.number().int().min(1).max(65535).optional(),"port-range":r.object({min:r.number().int().min(1).max(65535),max:r.number().int().min(1).max(65535)}).optional(),"service-type":r.enum([`tool`,`service`]).optional()}),Fe=r.object({services:r.array(Pe).optional(),steps:r.array(Ne).optional()}),Ie=r.object({steps:r.array(Ne).optional()}),Le=r.object({"runs-on":r.string().optional(),needs:r.union([r.string(),r.array(r.string())]).optional(),extends:r.union([r.string(),r.array(r.string())]).optional(),description:r.string().optional(),strategy:Me.optional(),steps:r.array(Ne),preJob:Ie.optional(),postJob:Ie.optional(),env:De.optional(),if:r.string().optional(),"system-prompt":r.string().optional(),context:r.string().optional()}),Re=r.object({steps:r.array(Ne)}),ze=r.object({steps:r.array(Ne)}),Be=r.object({beforeCreate:ze.optional(),afterCreate:ze.optional(),beforeCompleted:ze.optional(),afterCompleted:ze.optional()}),Ve=r.object({STOP:r.string().optional()}),He=r.object({name:r.string().optional(),workspace:r.string().optional(),imports:r.array(r.string()).optional(),"system-prompt":r.string().optional(),"max-workflows":r.number().int().positive().optional(),"launch-command":r.string().optional(),keybindings:Ve.optional(),on:r.looseObject({workflow_dispatch:r.object({inputs:r.record(r.string(),Oe).optional()}).nullable().optional(),agent_decision:Re.optional()}).optional(),env:De.optional(),pre:Fe.optional(),post:Fe.optional(),worktree:Be.optional(),jobs:r.record(r.string(),Le)}),Ue=r.enum([`running`,`completed`,`error`]),We=r.enum([`success`,`skipped`,`failed`,`interrupted`]),Ge=r.object({cliAgent:r.string().optional(),continueOnError:r.boolean().optional(),displayName:r.string(),dryRun:r.boolean(),env:r.record(r.string(),r.string()).optional(),errorMessage:r.string().optional(),exitCode:r.number().optional(),failedJob:r.string().optional(),finishedAt:r.string().optional(),fixLoopCycle:r.number().int().positive().optional(),inputs:r.record(r.string(),r.string()).optional(),job:r.string().optional(),keepWorktree:r.boolean().optional(),originalRepoPath:r.string().optional(),outcome:We.optional(),pid:r.number().int().positive().optional(),prompt:r.string().optional(),runner:r.string().optional(),runKey:r.string(),secretFile:r.string().optional(),skipLaunch:r.boolean().optional(),stale:r.boolean().optional(),staleReason:r.string().optional(),stage:Ue,startedAt:r.string(),failureReason:r.string().optional(),worktreeBranch:r.string().optional(),worktreePath:r.string().optional(),workflowPath:r.string(),workspace:r.string()});r.object({changelogPath:r.string(),contextPath:r.string(),displayName:r.string(),recordPath:r.string(),runDir:r.string(),runKey:r.string(),stopRequestPath:r.string(),workspace:r.string()});const Ke=`default`,M=`running`,qe=`completed`,Je=`error`,Ye=`workspaces`,N=`run.json`,Xe=`stop-request.json`,Ze=`workflow-run`,Qe=`Workflow process is no longer running`;var $e=class{constructor(e=x(_(),`.workflow-mcp`)){this.homeDir=e}resolveWorkspace(e,t){return this.slugifySegment(e||t||Ke,Ke)}async createRun(e){let t=this.resolveWorkspace(e.workspace,e.workflowWorkspace),n=this.slugifySegment(e.displayName,Ze);await this.ensureWorkspaceStructure(t);let r=await this.findReusableRunStage(t,n);if(r===M)throw new Ee(t,n);let i=this.getRunDirectory(t,M,n);r?(await m(i,{recursive:!0,force:!0}),await p(this.getRunDirectory(t,r,n),i),await this.removeFileIfExists(x(i,`fix.md`)),await this.removeFileIfExists(x(i,Xe))):await u(i,{recursive:!0});let a={cliAgent:e.cliAgent,continueOnError:e.continueOnError,displayName:e.displayName,dryRun:e.dryRun,env:e.env,inputs:e.inputs,job:e.job,keepWorktree:e.keepWorktree,runKey:n,prompt:e.prompt,runner:e.runner,secretFile:e.secretFile,skipLaunch:e.skipLaunch,stage:M,startedAt:new Date().toISOString(),pid:e.pid??process.pid,workflowPath:e.workflowPath,workspace:t},o=x(i,N);return await this.writeRunRecord(o,a),{changelogPath:x(i,`changelog.md`),contextPath:x(i,`context.md`),displayName:e.displayName,recordPath:o,runDir:i,runKey:n,stopRequestPath:x(i,Xe),workspace:t}}async finalizeRun(e,t){await this.ensureWorkspaceStructure(e.workspace);let n=this.getRunDirectory(e.workspace,t.stage,e.runKey),r=await this.readRunRecord(e.recordPath),i={...r,errorMessage:t.errorMessage,exitCode:t.exitCode,failedJob:t.failedJob,failureReason:t.failureReason,finishedAt:new Date().toISOString(),fixLoopCycle:t.fixLoopCycle,originalRepoPath:t.originalRepoPath,outcome:t.outcome,pid:r.pid,stage:t.stage,worktreeBranch:t.worktreeBranch,worktreePath:t.worktreePath};e.runDir!==n&&(await m(n,{recursive:!0,force:!0}),await p(e.runDir,n));let a=x(n,N);return await this.writeRunRecord(a,i),{...e,recordPath:a,runDir:n,stopRequestPath:x(n,Xe)}}async requestStop(e,t,n){let r=this.resolveWorkspace(e),i=this.slugifySegment(t,Ze),a=this.getRunDirectory(r,M,i),o=x(a,N);if(!await this.pathExists(o))throw Error(`Running workflow not found: ${r}/${t}`);let s=await this.inspectRunningRecord(r,i);if(s.stale)throw Error(s.staleReason??`Running workflow is stale: ${r}/${t}`);let c={reason:n?.trim()?n.trim():void 0,requestedAt:new Date().toISOString()};return await g(x(a,Xe),`${JSON.stringify(c,null,2)}\n`,`utf-8`),c}async hasStopRequest(e){return await this.pathExists(e.stopRequestPath)}async readRunRecord(e){try{return this.validateRunRecord(JSON.parse(await d(e,`utf-8`)),e)}catch(t){throw t instanceof Te?t:new Te(e,t instanceof Error?t.message:`Unknown parse failure`,{cause:t})}}async readRunByKey(e,t,n){let r=this.resolveWorkspace(e),i=this.slugifySegment(n,Ze),a=x(this.getRunDirectory(r,t,i),N);if(!await this.pathExists(a))throw Error(`Workflow run not found: ${r}/${t}/${n}`);return await this.readRunRecord(a)}async listRuns(e){let t=e?[this.resolveWorkspace(e)]:await this.listWorkspaceNames();return(await Promise.all(t.map(async e=>this.listWorkspaceRuns(e)))).flat().sort((e,t)=>this.compareRunRecordsByLatest(e,t))}async listRunsPage(e={}){let t=e.page??1,n=e.pageSize??20,r=await this.listRuns(e.workspace),i=r.length,a=Math.ceil(i/n),o=(t-1)*n,s=r.slice(o,o+n);return{hasNextPage:t<a,hasPreviousPage:t>1&&i>0,items:s,page:t,pageSize:n,total:i,totalPages:a}}async countRunningWorkflows(e){let t=this.getRunStageDirectory(e,M);if(!await this.pathExists(t))return 0;let n=await f(t,{withFileTypes:!0}),r=0;for(let e of n){if(!e.isDirectory())continue;let n=x(t,e.name,N);if(await this.pathExists(n))try{let e=await this.readRunRecord(n);e.pid&&this.isProcessAlive(e.pid)&&r++}catch{}}return r}async ensureWorkspaceStructure(e){await u(this.getRunStageDirectory(e,M),{recursive:!0}),await u(this.getRunStageDirectory(e,qe),{recursive:!0}),await u(this.getRunStageDirectory(e,Je),{recursive:!0})}async findRunStage(e,t){for(let n of[M,qe,Je])if(await this.pathExists(this.getRunDirectory(e,n,t)))return n;return null}async listWorkspaceRuns(e){let t=new Map;for(let n of[M,qe,Je]){let r=this.getRunStageDirectory(e,n);if(!await this.pathExists(r))continue;let i=await f(r,{withFileTypes:!0});for(let a of i){if(!a.isDirectory())continue;let i=x(r,a.name,N);if(!await this.pathExists(i))continue;let o=await this.readListableRunRecord(e,n,a.name,i);o&&t.set(o.runKey,o)}}return[...t.values()]}async findReusableRunStage(e,t){let n=await this.findRunStage(e,t);return n===M?(await this.reconcileStaleRunningRecord(e,t),this.findRunStage(e,t)):n}async inspectRunningRecord(e,t){let n=x(this.getRunDirectory(e,M,t),N),r=await this.readRunRecord(n);return!r.pid||this.isProcessAlive(r.pid)?r:{...r,stale:!0,staleReason:`${Qe}: pid ${r.pid}`}}async readListableRunRecord(e,t,n,r){try{return t===M?await this.inspectRunningRecord(e,n):await this.readRunRecord(r)}catch(e){if(e instanceof Te)return null;throw e}}async reconcileStaleRunningRecord(e,t){let n=this.getRunDirectory(e,M,t),r=x(n,N),i=await this.readRunRecord(r);if(!i.pid||this.isProcessAlive(i.pid))return i;let a=this.getRunDirectory(e,Je,t),o={...i,errorMessage:`${Qe}: pid ${i.pid}`,exitCode:130,finishedAt:new Date().toISOString(),outcome:`interrupted`,stage:Je};return await m(a,{recursive:!0,force:!0}),await p(n,a),await this.writeRunRecord(x(a,N),o),o}async listWorkspaceNames(){let e=x(this.homeDir,Ye);return await this.pathExists(e)?(await f(e,{withFileTypes:!0})).filter(e=>e.isDirectory()).map(e=>e.name).sort((e,t)=>e.localeCompare(t)):[]}compareRunRecordsByLatest(e,t){let n=e.finishedAt??e.startedAt,r=(t.finishedAt??t.startedAt).localeCompare(n);if(r!==0)return r;let i=e.workspace.localeCompare(t.workspace);return i===0?e.runKey.localeCompare(t.runKey):i}async writeRunRecord(e,t){await g(e,`${JSON.stringify(t,null,2)}\n`,`utf-8`)}validateRunRecord(e,t){let n=Ge.safeParse(e);if(!n.success)throw new Te(t,n.error.message);return n.data}getRunStageDirectory(e,t){return x(this.homeDir,Ye,e,t)}getRunDirectory(e,t,n){return x(this.getRunStageDirectory(e,t),n)}async pathExists(e){try{return await l(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async removeFileIfExists(e){try{await h(e)}catch(e){if(e.code!==`ENOENT`)throw e}}slugifySegment(e,t){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)||t}isProcessAlive(e){try{return process.kill(e,0),!0}catch(e){let t=e.code;if(t===`ESRCH`)return!1;if(t===`EPERM`)return!0;throw e}}};const et=r.object({page:r.number().int().min(1).optional().describe(`Page number to return. Defaults to 1.`),pageSize:r.number().int().min(1).max(100).optional().describe(`Number of workflow runs per page. Defaults to 20 and is capped at 100.`),workspace:r.string().optional().describe(`Optional workspace filter. When omitted, runs from all workspaces are returned.`)});var tt=class e{static TOOL_NAME=`list_workflow_statuses`;constructor(e=new $e){this.registry=e}getInputSchema(){return et}getDefinition(){return{name:e.TOOL_NAME,description:`List tracked workflow runs from the local workflow registry, including their workspace, stage, outcome, and timestamps.`,inputSchema:r.toJSONSchema(et)}}async execute(e={}){try{let t=et.parse(e),n=await this.registry.listRunsPage({page:t.page??1,pageSize:t.pageSize??20,workspace:t.workspace});return{content:[{type:`text`,text:JSON.stringify(n,null,2)}]}}catch(t){let n=new ue(`Failed to list workflow statuses.`,`LIST_WORKFLOW_STATUSES_TOOL_FAILED`,{workspace:e.workspace??`all`},{cause:t});return{content:[{type:`text`,text:JSON.stringify({code:n.code,context:n.context,message:n.message},null,2)}],isError:!0}}}};const nt=v.dirname(re(import.meta.url));var rt=class extends Error{code=`WORKFLOW_CAPACITY_EXCEEDED`;constructor(e,t,n){super(`Workspace "${e}" is at capacity: ${t}/${n} workflows running.\n → Check running workflows: list-workflow-statuses --workspace ${e}\n → Wait for a running workflow to complete, or cancel one before dispatching again.`),this.workspace=e,this.running=t,this.max=n,this.name=`WorkflowCapacityError`}},P=class extends Error{code=`WORKFLOW_INTERRUPTED`;context;constructor(e,t={}){let n=t.context?` during ${t.context.phase}`:``;super(`Workflow interrupted by ${e}${n}`,{cause:t.cause??t.context}),this.signal=e,this.name=`WorkflowInterruptedError`,this.context=t.context}};const F=`\x1B[0m`,it=`\x1B[1m`,at=`\x1B[2m`,ot=`\x1B[31m`,st=`\x1B[34m`,ct=[`pnpm-workspace.yaml`,`nx.json`,`.git`];function lt(e){let t=x(e);for(;;){for(let e of ct)if(S(b(t,e)))return t;let n=y(t);if(n===t)return e;t=n}}var ut=class{runningServices=[];processRegistry=new ae(process.env.PROCESS_REGISTRY_PATH);portRegistry=new ie(process.env.PORT_REGISTRY_PATH);constructor(e){this.logger=e}resolveWorkingDirectory(e,t){return e[`working-directory`]?x(t,e[`working-directory`]):t}getRunningServices(){return this.runningServices}async startService(e,t,n,r){let i=e.run;if(r)return this.logger.info(` ${st}dry ${F} ${e.name}`),this.logger.info(` ${at}$ ${i}${F}`),null;this.logger.info(` ${st}start${F} ${e.name}`),this.logger.info(` ${at}$ ${i}${F}`);let a={...process.env,...t};if(e.env)for(let[t,n]of Object.entries(e.env))a[t]=String(n);let o=this.resolveWorkingDirectory(e,n),c=lt(o),l=a.NODE_ENV??process.env.NODE_ENV??`development`,u=e.host??`127.0.0.1`,d;if(e.port!==void 0||e[`port-range`]){let t=await this.portRegistry.reservePort({repositoryPath:c,serviceName:e.name,serviceType:e[`service-type`]??`tool`,environment:l,preferredPort:e.port,portRange:e[`port-range`],host:u,force:!0});if(!t.success||t.port===void 0)throw Error(t.error??`Failed to reserve port for background service ${e.name}`);d=t.port,a.PORT??=String(d),a.SERVICE_PORT??=String(d),a.HOST??=u,a.SERVICE_HOST??=u}let f=s(i,[],{stdio:[`ignore`,`pipe`,`pipe`],cwd:o,env:{...a,FORCE_COLOR:`1`},shell:`/bin/zsh`,detached:!0});if(f.pid===void 0)throw d!==void 0&&await this.portRegistry.releasePort({repositoryPath:c,serviceName:e.name,serviceType:e[`service-type`]??`tool`,environment:l,force:!0}),Error(`Failed to spawn background service ${e.name}`);let p=`${st}[${e.name}]${F}`;f.stdout?.on(`data`,e=>{for(let t of e.toString().split(`
|
|
5
|
+
`))t.trim()&&process.stdout.write(`${p} ${t}\n`)}),f.stderr?.on(`data`,e=>{for(let t of e.toString().split(`
|
|
6
|
+
`))t.trim()&&process.stderr.write(`${p} ${t}\n`)}),f.on(`error`,e=>{this.logger.error(`${p} Process error: ${e.message}`)});let m=async()=>{d!==void 0&&await this.portRegistry.releasePort({repositoryPath:c,serviceName:e.name,serviceType:e[`service-type`]??`tool`,environment:l,force:!0})};if(f.pid!==void 0){let t=await this.processRegistry.registerProcess({repositoryPath:c,serviceName:e.name,serviceType:e[`service-type`]??`tool`,environment:l,pid:f.pid,port:d,host:d===void 0?void 0:u,command:i,args:[],metadata:{workingDirectory:o,readyCheck:e[`ready-check`]},force:!0});if(!t.success){try{process.kill(-f.pid,`SIGTERM`)}catch{f.kill(`SIGTERM`)}throw d!==void 0&&await this.portRegistry.releasePort({repositoryPath:c,serviceName:e.name,serviceType:e[`service-type`]??`tool`,environment:l,force:!0}),Error(t.error??`Failed to register process for background service ${e.name}`)}m=async()=>{let t=await this.processRegistry.releaseProcess({repositoryPath:c,serviceName:e.name,serviceType:e[`service-type`]??`tool`,environment:l,pid:f.pid,kill:!0,releasePort:!0,force:!0});if(!t.success&&!t.error?.includes(`No matching process entry`))throw Error(t.error??`Failed to release ${e.name}`)}}let h={name:e.name,process:f,env:a,release:m};return this.runningServices.push(h),h}async waitForServiceReady(e,t,n,r){if(!e[`ready-check`]||typeof e[`ready-check`]!=`string`)return!0;let i=(e[`ready-timeout`]||30)*1e3,a=Date.now(),s=e[`ready-check`],c=this.resolveWorkingDirectory(e,t),l=this.runningServices.find(t=>t.name===e.name)?.env??{...process.env,...n};for(this.logger.info(` ${at}wait${F} Waiting for ${e.name} to be ready...`);Date.now()-a<i;){if(r?.())return!1;try{return o(s,{stdio:`ignore`,cwd:c,env:l,shell:`/bin/zsh`,timeout:5e3}),this.logger.info(` [32mready${F} ${e.name}`),!0}catch{if(r?.())return!1}await new Promise(e=>{setTimeout(e,1e3)})}return r?.()||this.logger.error(` ${ot}timeout${F} ${e.name} not ready after ${e[`ready-timeout`]||30}s`),!1}async stopAll(){if(this.runningServices.length!==0){this.logger.info(`\n ${st}${it}pre${F} ${it}Stopping services${F}`),this.logger.info(` ${`─`.repeat(50)}`);for(let e of this.runningServices){if(!e.process.killed&&e.process.pid&&this.logger.info(` ${at}stop${F} ${e.name} (pid ${e.process.pid})`),e.release)try{await e.release();continue}catch(t){this.logger.warn(` ${ot}warn${F} Failed registry cleanup for ${e.name}: ${t instanceof Error?t.message:String(t)}`)}if(!e.process.killed&&e.process.pid)try{process.kill(-e.process.pid,`SIGTERM`)}catch{e.process.kill(`SIGTERM`)}}this.runningServices=[]}}};const I=`\x1B[0m`,dt=`\x1B[1m`,ft=`\x1B[2m`,pt=`\x1B[33m`,mt=`WORKFLOW_JOB_ID`,ht=`WORKFLOW_JOB_NAME`,gt=`PROCESS_REGISTRY_TAG`;var _t=class{constructor(e,t,n){this.parser=e,this.stepRunner=t,this.logger=n}async runJob(e,t,n,r){let i=this.parser.expandMatrix(t),a=r.maxRetries;for(let o of i){let i=oe(),s=Object.keys(o).length>0?` ${ft}(${Object.entries(o).map(([e,t])=>`${e}=${t}`).join(`, `)})${I}`:``;this.logger.info(`\n [35m${dt}job${I} ${dt}${e}${I}${s}`),this.logger.info(` ${`─`.repeat(50)}`);let c={...n.workflowEnv,[mt]:i,[ht]:e,[gt]:i};if(t.env)for(let[e,r]of Object.entries(t.env))c[e]=this.parser.interpolate(String(r),{inputs:n.inputs,matrix:o,secrets:n.secrets,env:c});c[mt]=i,c[ht]=e,c[gt]=i,this.logger.info(` ${ft}jobid${I} ${i}`);let l=[];if(c.WORKFLOW_RUN_DIR){let t=n.jobOrder.indexOf(e),r=n.jobOrder.slice(0,t+1).map(e=>{let t=n.allJobs[e]?.description;return t?` - ${e}: ${t}`:` - ${e}`}).join(`
|
|
7
|
+
`);l.push(`You are currently running job "${e}" in the following workflow:\n${r}\n\nWhen you have completed your task, you MUST either:\n1. If you find bugs, missing features, or issues that need fixes from a previous job, write to ${c.WORKFLOW_RUN_DIR}/fix.md with a YAML frontmatter restart-from field specifying which job should handle the fix, followed by a detailed description. Example:\n---\nrestart-from: development\n---\nDescription of what needs to be fixed...\n\nThe workflow runner will restart from the specified job. Only create fix.md for issues that require code changes — fix minor issues yourself.\n2. Otherwise, stop. Do not continue with unrelated work.`)}if(n.workflowSystemPrompt&&l.push(this.parser.interpolate(n.workflowSystemPrompt,{inputs:n.inputs,matrix:o,secrets:n.secrets,env:c})),t[`system-prompt`]&&l.push(this.parser.interpolate(t[`system-prompt`],{inputs:n.inputs,matrix:o,secrets:n.secrets,env:c})),l.length>0){let e=l.join(`
|
|
8
|
+
|
|
9
|
+
`);c.JOB_SYSTEM_PROMPT=e,this.logger.info(` ${ft}prompt${I} ${e.split(`
|
|
10
|
+
`)[0].slice(0,80)}${e.includes(`
|
|
11
|
+
`)?`...`:``}`)}let u=t.context?this.parser.interpolate(t.context,{inputs:n.inputs,matrix:o,secrets:n.secrets,env:c}):c.CONTEXT_FILE;if(u){let e=x(r.workflowDir,u);S(e)?(c.WORKFLOW_CONTEXT=e,c.WORKFLOW_CONTEXT_FILE=e,this.logger.info(` ${ft}ctx ${I} ${u}`)):r.dryRun||this.logger.warn(` ${pt}warn${I} context file not found: ${u}`)}if(c.CHANGELOG_FILE){let e=x(r.workflowDir,c.CHANGELOG_FILE),t=y(e);S(t)||ne(t,{recursive:!0}),S(e)||D(e,`# Changelog
|
|
12
|
+
`,`utf-8`),c.WORKFLOW_CHANGELOG=e,this.logger.info(` ${ft}log ${I} changelog at ${c.CHANGELOG_FILE}`)}let d={inputs:n.inputs,matrix:o,secrets:n.secrets,env:c},f=!1,p=t.preJob?.steps??[],m=t.steps??[],h=t.postJob?.steps??[];for(let t=1;t<=a;t++){t>1&&(this.logger.info(`\n ${pt}retry${I} ${dt}${e}${I}${s} (attempt ${t}/${a})`),this.logger.info(` ${`─`.repeat(50)}`));let n=!0;if(p.length>0&&(n=await this.runStepSequence(p,d,r)),n&&=await this.runStepSequence(m,d,r),h.length>0){let e=await this.runStepSequence(h,d,r);n&&=e}if(n){f=!0;break}t<a&&this.logger.warn(` ${pt}Job "${e}" failed, retrying...${I}`)}if(f)this.logger.info(` [32mJob "${e}" completed${I}${s}`);else if(this.logger.error(`\n [31mJob "${e}" failed after ${a} attempts${I}`),t.strategy?.[`fail-fast`]!==!1)return!1}return!0}async runStepSequence(e,t,n){for(let r of e)if(!await this.stepRunner.runStep(r,t,n))return!1;return!0}},vt=class extends Error{code=`WORKFLOW_STEP_SPAWN_FAILED`;constructor(e,t={}){super(`Failed to start workflow step "${e.stepName}"`,{cause:t.cause??e}),this.context=e,this.name=`WorkflowStepSpawnError`}},yt=class extends Error{code=`WORKFLOW_STEP_TIMEOUT_CONFIG_INVALID`;constructor(e,t={}){super(`Invalid ${e.configKey} for workflow step "${e.stepName}"`,{cause:t.cause??e}),this.context=e,this.name=`WorkflowStepTimeoutConfigError`}};const bt=`/backend-api`;var xt=class{codexHome;fetchFn;now;readTextFile;constructor(e={}){this.codexHome=e.codexHome??b(_(),`.codex`),this.fetchFn=e.fetchFn??fetch,this.now=e.now??(()=>Date.now()),this.readTextFile=e.readTextFile??(e=>d(e,`utf8`))}isCodexCommand(e,t){let n=e.trim();return n===`codex`||n.startsWith(`codex `)}async getQuotaStatus(){let e=await this.readAuthFile(),t=e?.tokens?.access_token?.trim(),n=e?.tokens?.account_id?.trim();if(!t||!n)return null;let r=await this.readChatgptBaseUrl(),i=await this.fetchFn(this.buildUsageUrl(r),{headers:{Authorization:`Bearer ${t}`,"ChatGPT-Account-Id":n,"User-Agent":`codex-cli`}});if(!i.ok)throw Error(`codex quota request failed with HTTP ${i.status}`);let a=await i.json();return{blockingLimit:this.findBlockingLimit(a),planType:a.plan_type??null}}async readAuthFile(){let e=await this.readOptionalTextFile(b(this.codexHome,`auth.json`));return e?JSON.parse(e):null}async readChatgptBaseUrl(){let e=(await this.readOptionalTextFile(b(this.codexHome,`config.toml`)))?.match(/^\s*chatgpt_base_url\s*=\s*"([^"]+)"/m);return this.normalizeBaseUrl(e?.[1]??`https://chatgpt.com/backend-api/`)}buildUsageUrl(e){return e.includes(bt)?`${e}/wham/usage`:`${e}/api/codex/usage`}normalizeBaseUrl(e){let t=e.trim().replace(/\/+$/,``);return(t.startsWith(`https://chatgpt.com`)||t.startsWith(`https://chat.openai.com`))&&!t.includes(bt)&&(t=`${t}${bt}`),t}async readOptionalTextFile(e){try{return await this.readTextFile(e)}catch(e){if(e.code===`ENOENT`)return null;throw e}}findBlockingLimit(e){let t=[];this.collectBlockingLimit(t,`codex`,`codex`,e.rate_limit);for(let n of e.additional_rate_limits??[])this.collectBlockingLimit(t,n.metered_feature??n.limit_name??`codex`,n.limit_name??n.metered_feature??`codex`,n.rate_limit);return t.sort((e,t)=>e.resetAt-t.resetAt||t.usedPercent-e.usedPercent),t[0]??null}collectBlockingLimit(e,t,n,r){if(!r)return;let i=[{payload:r.primary_window,window:`primary`},{payload:r.secondary_window,window:`secondary`}];for(let{payload:a,window:o}of i){let i=a?.reset_at,s=a?.used_percent??0;typeof i==`number`&&(s>=100||r.limit_reached===!0&&i*1e3>this.now()||r.allowed===!1&&i*1e3>this.now())&&e.push({limitId:t,limitName:n,resetAfterSeconds:a?.reset_after_seconds??null,resetAt:i,usedPercent:s,window:o,windowSeconds:a?.limit_window_seconds??null})}}};const L=`\x1B[0m`,R=`\x1B[2m`,St=`\x1B[36m`,Ct=`\x1B[32m`,z=`\x1B[33m`,B=`\x1B[31m`,wt=`SIGINT`,V=`SIGTERM`,Tt=`unnamed`,Et=`/bin/zsh`,Dt=`FORCE_COLOR`,H=`inherit`,Ot=`pipe`,kt=` `,At=`
|
|
13
|
+
${kt}\$ `,jt=`skip`,U=`warn`,W=`error`,G=`fail`,K=`interrupted`,Mt=`already stopping`,Nt=`failed to signal`,q=`(continue-on-error)`,Pt=`ESRCH`,Ft=process.platform!==`win32`,It=`interactiveRun`,Lt=`timeout-minutes`,Rt=`timeout-retries`,zt=`retry`,J=`SIGKILL`,Bt=1e3,Vt=1e3,Ht=6e4,Ut=Math.floor(2147483647/Ht),Wt=`WORKFLOW_STEP_DISPLAY`,Gt=`workflow-mcp`,Kt={status:`status_completed`},qt=new Set([`ENOENT`,`EBUSY`,`EAGAIN`,`EPERM`]),Jt=1e3,Yt=`done`,Xt=`stop`,Zt=1e3,Qt=`stop_requested`,$t=r.number().positive().finite().max(Ut),en=r.number().int().min(0).max(10).default(2);var tn=class{activeStep=null;activeQuotaWait=null;constructor(e,t,n=new xt,r=E){this.parser=e,this.logger=t,this.quotaService=n,this.watchStatusFile=r}stopActiveStep(e){if(this.activeQuotaWait){if(this.activeQuotaWait.controller.signal.aborted){this.logger.info(` ${R}${jt}${L} ${this.activeQuotaWait.stepName} ${Mt}`);return}this.activeQuotaWait.signal=e,this.activeQuotaWait.controller.abort(),this.logger.info(` ${z}${K}${L} cancelling quota wait for ${this.activeQuotaWait.stepName}`);return}if(!this.activeStep){this.logger.info(` ${R}${jt}${L} no active step to stop`);return}if(this.activeStep.process.killed){this.logger.info(` ${R}${jt}${L} ${this.activeStep.stepName} ${Mt}`);return}this.logger.info(` ${z}${K}${L} sending ${e} to ${this.activeStep.stepName}`),this.killActiveStep(e)||this.logger.warn(` ${z}${U}${L} ${Nt} ${this.activeStep.stepName}`)}async runStep(e,t,n){let r=this.resolveRunner(n),i=this.resolveStepCommand(e,t,r),a=e.name?this.parser.interpolate(e.name,t):i?.command.slice(0,60)||e.uses||Tt;if(e.uses){let n=this.parser.interpolate(e.uses,t);return this.parser.isActionSkipped(n)?(this.logger.info(` ${R}${jt}${L} ${n}`),!0):(this.logger.warn(` ${z}${U}${L} Unsupported action: ${n} (skipped)`),!0)}if(!i)return!0;if(i.missingRunner)return this.logger.error(` ${B}${W}${L} runner "${i.missingRunner.runner}" not found for step "${a}" (available runner keys: ${i.missingRunner.availableKeys.join(`, `)})`),e[`continue-on-error`]||n.continueOnError?(this.logger.warn(` ${z}${G}${L} ${a} ${q}\n`),!0):(this.logger.error(` ${B}${G}${L} ${a}\n`),!1);let{command:o,interactive:s}=i,c=this.quotaService.isCodexCommand(o,i.agentKey),l=e[`continue-on-error`]||n.continueOnError,u;try{u=this.resolveTimeoutMs(e,a)}catch(e){if(!(e instanceof yt))throw e;return this.logger.error(` ${B}${W}${L} invalid ${e.context.configKey} for "${a}": ${String(e.context.timeoutValue)}`),l?(this.logger.warn(` ${z}${G}${L} ${a} ${q}\n`),!0):(this.logger.error(` ${B}${G}${L} ${a}\n`),!1)}let d={...process.env,...t.env};if(e.env)for(let[n,r]of Object.entries(e.env))d[n]=this.parser.interpolate(String(r),t);d.WORKFLOW_STEP_NAME=a,d[Wt]=this.formatStepDisplay(d.WORKFLOW_JOB_NAME,a);let f;s&&(f=this.createStatusFile(),d.WORKFLOW_STATUS_FILE=f,this.logger.info(` ${R}status-file${L} ${f}`));let p=e[`working-directory`]?x(n.workflowDir,this.parser.interpolate(e[`working-directory`],t)):n.workflowDir;if(n.dryRun)return this.logger.info(` ${St}dry ${L} ${a}`),this.logger.info(`${kt}${R}\$ ${o.split(`
|
|
14
|
+
`).join(At)}${L}`),!0;let m;try{m=this.resolveTimeoutRetries(e,a)}catch(e){if(!(e instanceof yt))throw e;return this.logger.error(` ${B}${W}${L} invalid ${e.context.configKey} for "${a}": ${String(e.context.timeoutValue)}`),l?(this.logger.warn(` ${z}${G}${L} ${a} ${q}\n`),!0):(this.logger.error(` ${B}${G}${L} ${a}\n`),!1)}let h=!1;for(let e=0;e<=m;e++){if(await this.waitForCodexQuotaAvailability(a,o,c),e>0?this.logger.warn(` ${z}${zt}${L} retrying step after timeout "${a}" (attempt ${e+1}/${m+1})`):this.logger.info(` ${St}run ${L} ${a}`),this.logger.info(`${kt}${R}\$ ${o.split(`
|
|
15
|
+
`)[0]}${o.includes(`
|
|
16
|
+
`)?` ...`:``}${L}`),n.stopRequestPath&&S(n.stopRequestPath))throw this.logger.info(`\n ${z}${K}${L} ${a} (${Xt})`),new P(V,{cause:Error(`Workflow stop requested before "${a}"`),context:this.createInterruptContext(a,o)});let t=s?this.withInteractiveTerminalTitle(o,d):o,r=this.executeCommand(t,p,d,a,s,u),i=s&&f?await this.raceInteractiveCompletion(r,f,a,n.stopRequestPath):n.stopRequestPath?await this.raceStopRequest(r,a,n.stopRequestPath):await r;if(i.status===`stop_requested`)throw this.logger.info(`\n ${z}${K}${L} ${a} (${Xt})`),new P(V,{cause:Error(`Workflow stop requested during "${a}"`),context:this.createInterruptContext(a,o)});if(i.status===`signaled`)throw this.logger.info(`\n ${z}${K}${L} ${a}`),new P(i.signal,{cause:Error(`Step process ended with ${i.signal}`),context:this.createInterruptContext(a,o)});if(i.status===`completed`&&(i.exitCode===130||i.exitCode===143)){let e=i.exitCode===130?wt:V;throw this.logger.info(`\n ${z}${K}${L} ${a}`),new P(e,{cause:Error(`Step process exited with ${i.exitCode}`),context:this.createInterruptContext(a,o)})}if(i.status===`spawn_error`)return this.logger.error(` ${B}${W}${L} unable to start step "${a}" in ${i.error.context.workDir} (${this.formatSpawnError(i.error)})`),l?(this.logger.warn(` ${z}${G}${L} ${a} ${q}\n`),!0):(this.logger.error(` ${B}${G}${L} ${a}\n`),!1);if(i.status===`timed_out`){if(this.logger.error(` ${B}${W}${L} step timed out after ${this.formatTimeoutMs(i.timeoutMs)} "${a}" (${o.split(`
|
|
17
|
+
`)[0]})`),e<m){if(f)try{D(f,``,`utf-8`)}catch(e){this.logger.warn(` ${z}${U}${L} status-file reset failed for ${a}: ${e instanceof Error?e.message:String(e)}`)}continue}return f&&this.cleanupStatusFile(f),l?(this.logger.warn(` ${z}${G}${L} ${a} ${q}\n`),!0):(this.logger.error(` ${B}${G}${L} ${a}\n`),!1)}if(f&&this.cleanupStatusFile(f),i.status===`status_completed`)return this.logger.info(`\n ${Ct}${Yt}${L} ${a} (status-file signaled completion)\n`),!0;if(i.status===`completed`&&i.exitCode===0)return this.logger.info(`\n ${Ct}pass${L} ${a}\n`),!0;if(i.status===`completed`&&this.logger.error(` ${B}${W}${L} step "${a}" exited with code ${i.exitCode} (${o.split(`
|
|
18
|
+
`)[0]})`),!h&&await this.shouldRetryForCodexQuota(a,c)){h=!0,this.logger.warn(` ${z}${zt}${L} codex quota reached after failed step, retrying after reset`),--e;continue}return l?(this.logger.warn(` ${z}${G}${L} ${a} ${q}\n`),!0):(this.logger.error(` ${B}${G}${L} ${a}\n`),!1)}return!1}async executeCommand(e,t,n,r,i,a){return i&&this.logger.info(` ${R}(interactive: output renders directly to terminal)${L}`),await new Promise(o=>{let c=i?this.captureTerminalState():null,l=i?s(e,[],{stdio:[H,H,H],cwd:t,detached:!1,env:{...n,[Dt]:`1`},shell:Et}):s(e,[],{stdio:[H,Ot,Ot],cwd:t,detached:Ft,env:{...n,[Dt]:`1`},shell:Et});this.activeStep={command:e,interactive:i,lastSignaledProcessIds:[],process:l,processGroupId:Ft&&!i&&typeof l.pid==`number`?l.pid:null,rootProcessId:typeof l.pid==`number`?l.pid:null,stepName:r};let u=null,d=!1,f=!1,p=async e=>{f||(f=!0,m&&clearTimeout(m),u&&clearTimeout(u),i&&(await this.cleanupInteractiveProcessTree(V),this.restoreTerminalState(c)),this.activeStep=null,o(e))},m=a===null?null:setTimeout(()=>{if(d=!0,this.killActiveStep(V)){u=setTimeout(()=>{f||(this.logger.warn(` ${z}${U}${L} ${r} forcing SIGKILL`),this.killActiveStep(J))},Bt);return}p({status:`timed_out`,timeoutMs:a})},a);l.stdout?.on(`data`,e=>{for(let t of e.toString().split(`
|
|
19
|
+
`))t&&this.logger.info(t)}),l.stderr?.on(`data`,e=>{for(let t of e.toString().split(`
|
|
20
|
+
`))t&&this.logger.error(t)}),l.on(`error`,n=>{p({status:`spawn_error`,error:new vt({commandPreview:e.split(`
|
|
21
|
+
`)[0],source:`StepRunnerService.executeCommand`,stepName:r,workDir:t},{cause:n})})}),l.on(`exit`,(e,t)=>{if(i||this.cleanupProcessGroup(),d&&a!==null){p({status:`timed_out`,timeoutMs:a});return}if(t===wt){p({status:`signaled`,signal:wt});return}if(t===V){p({status:`signaled`,signal:V});return}p({status:`completed`,exitCode:e??1})})})}createInterruptContext(e,t){return{phase:`step_execution`,stepName:e,commandPreview:t.split(`
|
|
22
|
+
`)[0],source:`StepRunnerService.runStep`}}formatSpawnError(e){let t=e.cause;return t instanceof Error?`${`code`in t&&typeof t.code==`string`?t.code:`unknown-spawn-error`}${`path`in t&&typeof t.path==`string`?` at ${t.path}`:``}; verify command, shell, and permissions`:`check shell availability, PATH, and permissions`}resolveStepCommand(e,t,n){let r=e[It]!=null,i=r?{command:e[It],interactive:!0}:{command:e.run,interactive:!1},a=r?{command:e.run,interactive:!1}:{command:e[It],interactive:!0},o=this.resolveExactAgentCommand(i.command,t,n);if(o)return{...o,interactive:i.interactive};let s=this.resolveExactAgentCommand(a.command,t,n);if(s)return{...s,interactive:a.interactive};let c=this.resolveMissingExplicitRunner(e,n);if(c)return{command:``,interactive:!1,missingRunner:c};let l=this.resolveStringCommand(i.command,t);if(l)return{command:l,interactive:i.interactive};let u=this.resolveStringCommand(a.command,t);if(u)return{command:u,interactive:a.interactive};let d=this.resolveFirstMappedCommand(i.command,t);if(d)return{command:d,interactive:i.interactive};let f=this.resolveFirstMappedCommand(a.command,t);return f?{command:f,interactive:a.interactive}:null}resolveExactAgentCommand(e,t,n){if(!n||!e||typeof e==`string`)return null;let r=e[n];return r?{agentKey:n,command:this.parser.interpolate(r,t),interactive:!1}:null}resolveStringCommand(e,t){return!e||typeof e!=`string`?null:this.parser.interpolate(e,t)}resolveFirstMappedCommand(e,t){if(!e||typeof e==`string`)return null;let[n]=Object.values(e);return n?this.parser.interpolate(n,t):null}resolveMissingExplicitRunner(e,t){if(!t)return null;let n=this.collectMappedRunnerKeys(e);return n.length===0||n.includes(t)?null:{availableKeys:n,runner:t}}collectMappedRunnerKeys(e){let t=new Set;for(let n of[e[It],e.run])if(n&&typeof n!=`string`)for(let e of Object.keys(n))t.add(e);return[...t]}resolveRunner(e){return e.runner??e.cliAgent}formatStepDisplay(e,t){return e?`${e} > ${t}`:t}withInteractiveTerminalTitle(e,t){let n=`${Gt}: ${t[Wt]??e.split(`
|
|
23
|
+
`)[0]??Tt}`,r=`[ -t 1 ] && printf '\\033]0;%s\\007' ${this.escapeShellArg(n)}`,i=`[ -t 1 ] && printf '\\033]0;%s\\007' ${this.escapeShellArg(Gt)}`;return`trap ${this.escapeShellArg(i)} EXIT
|
|
24
|
+
${r}
|
|
25
|
+
${e}`}escapeShellArg(e){return`'${e.replace(/'/g,`'\\''`)}'`}async shouldRetryForCodexQuota(e,t){return t?(await this.readCodexQuotaStatus(e))?.blockingLimit!=null:!1}async waitForCodexQuotaAvailability(e,t,n){if(n)for(;;){let n=await this.readCodexQuotaStatus(e),r=n?.blockingLimit;if(!r)return;let i=r.resetAt*1e3+Zt,a=Math.max(i-Date.now(),Zt),o=new Date(i).toLocaleString(),s=n?.planType?` (${n.planType})`:``;this.logger.warn(` ${z}wait ${L} codex quota ${r.limitName}/${r.window} is at ${r.usedPercent}%${s}; waiting until ${o}`),await this.waitForQuotaDelay(e,t,a)}}async readCodexQuotaStatus(e){try{return await this.quotaService.getQuotaStatus()}catch(t){return this.logger.warn(` ${z}${U}${L} unable to read codex quota for "${e}" (${this.formatQuotaError(t)})`),null}}async waitForQuotaDelay(e,t,n){let r=new AbortController;this.activeQuotaWait={controller:r,signal:null,stepName:e};try{let e=n;for(;e>0;){let t=Math.min(e,3e4);await this.waitForDelay(t,r.signal),e-=t}}catch(n){throw r.signal.aborted?new P(this.activeQuotaWait?.signal??V,{cause:Error(`Interrupted while waiting for Codex quota reset`),context:{...this.createInterruptContext(e,t),phase:`StepRunnerService.waitForCodexQuota`}}):n}finally{this.activeQuotaWait=null}}async waitForDelay(e,t){await new Promise((n,r)=>{let i=setTimeout(()=>{t.removeEventListener(`abort`,a),n()},e),a=()=>{clearTimeout(i),t.removeEventListener(`abort`,a),r(Error(`aborted`))};t.addEventListener(`abort`,a,{once:!0})})}formatQuotaError(e){return e instanceof Error&&e.message.trim().length>0?e.message:`unknown quota error`}resolveTimeoutMs(e,t){let n=e[Lt];if(n===void 0)return null;try{let e=$t.parse(n);return Math.ceil(e*Ht)}catch(e){throw new yt({stepName:t,configKey:Lt,timeoutValue:n},{cause:e})}}resolveTimeoutRetries(e,t){let n=e[Rt];try{return en.parse(n)}catch(e){throw new yt({stepName:t,configKey:Rt,timeoutValue:n},{cause:e})}}formatTimeoutMs(e){return e%Ht===0?`${e/Ht} minute(s)`:`${e}ms`}cleanupProcessGroup(){if(!this.activeStep)return;let{processGroupId:e,stepName:t}=this.activeStep;if(e!==null)try{process.kill(-e,V)}catch(n){let r=n.code;r===Pt?this.logger.info(` ${R}cleanup${L} process group ${e} already exited (ESRCH)`):this.logger.warn(` ${z}${U}${L} failed to clean up process group for ${t} (pgid=${e}, error=${r})`)}}async cleanupInteractiveProcessTree(e){if(!this.activeStep||!this.activeStep.interactive)return!1;let t=this.collectInteractiveProcessIds();if(t.length===0)return!1;this.activeStep.lastSignaledProcessIds=t;let n=this.signalProcessIds(t,e);if(await this.waitForProcessIdsToExit(t,Vt),e!==J){let e=this.uniqueLiveProcessIds(t);e.length>0&&(this.signalProcessIds(e,J),await this.waitForProcessIdsToExit(e,Vt))}return n}collectInteractiveProcessIds(){if(!this.activeStep?.interactive||this.activeStep.rootProcessId===null)return[];let e=this.activeStep.rootProcessId,t=[...this.snapshotProcessTree(e).map(e=>e.pid),...this.activeStep.lastSignaledProcessIds,e];return this.uniqueLiveProcessIds(t)}snapshotProcessTree(e){let t;try{t=a(`ps`,[`-axo`,`pid=,ppid=`],{encoding:`utf-8`,stdio:[`ignore`,Ot,`ignore`]})}catch(t){return this.logger.warn(` ${z}${U}${L} unable to inspect process tree for ${e} (${t instanceof Error?t.message:String(t)})`),this.isProcessAlive(e)?[{depth:0,pid:e}]:[]}let n=new Map;for(let e of t.split(`
|
|
26
|
+
`)){let t=e.trim();if(!t)continue;let[r,i]=t.split(/\s+/),a=Number(r),o=Number(i);if(!Number.isInteger(a)||!Number.isInteger(o))continue;let s=n.get(o)??[];s.push(a),n.set(o,s)}let r=[],i=new Set,o=(e,t)=>{if(!i.has(e)){i.add(e),e!==process.pid&&r.push({depth:t,pid:e});for(let r of n.get(e)??[])o(r,t+1)}};return o(e,0),r.sort((e,t)=>t.depth-e.depth)}signalProcessIds(e,t){let n=!1;for(let r of e)if(r!==process.pid)try{process.kill(r,t),n=!0}catch(e){let t=e.code;t!==Pt&&this.logger.warn(` ${z}${U}${L} ${Nt} pid ${r} (${t??e.message})`)}return n}uniqueLiveProcessIds(e){let t=new Set,n=[];for(let r of e)!Number.isInteger(r)||r<=0||r===process.pid||t.has(r)||(t.add(r),this.isProcessAlive(r)&&n.push(r));return n}isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}async waitForProcessIdsToExit(e,t){let n=Date.now()+t;for(;Date.now()<n;){if(e.every(e=>!this.isProcessAlive(e)))return;await new Promise(e=>setTimeout(e,50))}}killActiveStep(e){if(!this.activeStep)return!1;if(this.activeStep.interactive){let t=this.collectInteractiveProcessIds();if(t.length>0)return this.activeStep.lastSignaledProcessIds=t,this.signalProcessIds(t,e)}let{process:t,processGroupId:n}=this.activeStep;if(n!==null)try{return process.kill(-n,e),!0}catch(e){e.code===Pt?this.logger.info(` ${R}signal${L} process group for ${this.activeStep.stepName} already exited (ESRCH)`):this.logger.warn(` ${z}${U}${L} ${Nt} process group for ${this.activeStep.stepName}`)}try{return t.kill(e)}catch(e){return this.logger.warn(` ${z}${U}${L} ${Nt} ${this.activeStep.stepName} (${e.message})`),!1}}createStatusFile(){let e=b(ee(),`workflow-step-${oe()}.status`);return D(e,``,`utf-8`),e}async raceInteractiveCompletion(e,t,n,r){return new Promise(i=>{let a=!1,o=!1,s=!1,c=null,l=null,u=null,d=null,f=null,p=e=>{a||(a=!0,l&&=(l.close(),null),u&&=(u.close(),null),d&&=(clearInterval(d),null),f&&=(clearInterval(f),null),c&&=(clearTimeout(c),null),i(e))},m=!1,h=!1,g=()=>{try{return S(t)&&C(t,`utf-8`).trim()===`YES`}catch(e){let t=e.code;return!t||!qt.has(t)?this.logger.warn(` ${z}${U}${L} status-file read failed for ${n}: ${e instanceof Error?e.message:String(e)}`):this.logger.info(` ${R}status-file${L} transient FS error (${t}) polling ${n}`),!1}},_=()=>{if(!(o||!g())){if(o=!0,m=this.killActiveStep(V),!m){this.logger.warn(` ${z}${U}${L} ${n} status-file: SIGTERM could not be delivered, process may have already exited`);return}c=setTimeout(()=>{a||(h=!0,this.logger.warn(` ${z}${U}${L} ${n} did not exit after status-file SIGTERM, forcing SIGKILL`),this.killActiveStep(J))},Bt)}},ee=()=>!!(r&&S(r)),v=()=>{if(!(s||!ee())){if(s=!0,m=this.killActiveStep(V),!m){this.logger.warn(` ${z}${U}${L} ${n} stop request: SIGTERM could not be delivered, process may have already exited`);return}c=setTimeout(()=>{a||(h=!0,this.logger.warn(` ${z}${U}${L} ${n} did not exit after stop-request SIGTERM, forcing SIGKILL`),this.killActiveStep(J))},Bt)}};try{l=this.watchStatusFile(t,()=>_())}catch(e){this.logger.warn(` ${z}${U}${L} status-file watcher setup failed for ${n}: ${e instanceof Error?e.message:String(e)}`)}if(d=setInterval(_,1e3),r){try{u=this.watchStatusFile(r,()=>v())}catch(e){e.code!==`ENOENT`&&this.logger.warn(` ${z}${U}${L} stop-request watcher setup failed for ${n}: ${e instanceof Error?e.message:String(e)}`)}f=setInterval(v,Jt)}_(),v(),e.then(e=>{if(s){h&&this.logger.warn(` ${z}${U}${L} ${n} required SIGKILL escalation after stop request`),p({status:Qt});return}if(!(o||g())){p(e);return}switch(o||(o=!0,this.logger.info(` ${Ct}${Yt}${L} ${n} status-file observed during process exit handling`)),e.status){case`spawn_error`:case`timed_out`:p(e);return;case`signaled`:h&&this.logger.warn(` ${z}${U}${L} ${n} required SIGKILL escalation (work completed via status-file)`),p(Kt);return;case`completed`:e.exitCode===0||e.exitCode>128||h||!m?(h&&this.logger.warn(` ${z}${U}${L} ${n} required SIGKILL escalation (work completed via status-file, exit code ${e.exitCode})`),p(Kt)):p(e);return;case`status_completed`:p(e);return;case Qt:p(e);return;default:p(e)}})})}async raceStopRequest(e,t,n){return new Promise(r=>{let i=!1,a=!1,o=null,s=null,c=null,l=e=>{i||(i=!0,c&&=(c.close(),null),s&&=(clearInterval(s),null),o&&=(clearTimeout(o),null),r(e))},u=()=>{if(!(a||!S(n))){if(a=!0,!this.killActiveStep(V)){this.logger.warn(` ${z}${U}${L} ${t} stop request: SIGTERM could not be delivered, process may have already exited`);return}o=setTimeout(()=>{i||(this.logger.warn(` ${z}${U}${L} ${t} did not exit after stop-request SIGTERM, forcing SIGKILL`),this.killActiveStep(J))},Bt)}};try{c=this.watchStatusFile(n,()=>u())}catch(e){e.code!==`ENOENT`&&this.logger.warn(` ${z}${U}${L} stop-request watcher setup failed for ${t}: ${e instanceof Error?e.message:String(e)}`)}s=setInterval(u,Jt),u(),e.then(e=>{l(a?{status:Qt}:e)})})}captureTerminalState(){if(!process.stdin.isTTY)return null;try{return a(`stty`,[`-g`],{encoding:`utf-8`,stdio:[H,Ot,`ignore`]}).trim()}catch{return null}}restoreTerminalState(e){if(e&&process.stdin.isTTY)try{a(`stty`,[e],{stdio:[H,`ignore`,`ignore`]})}catch{}process.stdout.isTTY&&process.stdout.write(`\x1B[0m\x1B[?25h\x1B[?1049l`)}cleanupStatusFile(e){try{S(e)&&T(e)}catch(e){this.logger.warn(` ${z}${U}${L} status-file cleanup failed: ${e instanceof Error?e.message:String(e)}`)}}};const Y=`\x1B[0m`,nn=`\x1B[1m`,rn=`\x1B[2m`,an=`\x1B[36m`,on=`\x1B[32m`,sn=`\x1B[31m`,cn=`\x1B[34m`;var ln=class{activePrompt=null;activePromptSignal=null;constructor(e,t){this.stepRunner=e,this.logger=t}async pathExists(e){try{return await l(e),!0}catch{return!1}}abortActivePrompt(e){this.activePromptSignal=e,this.activePrompt?.close()}async handleUserPrompt(e,t,n,r,i){if(!e.on||!(`user_prompt`in e.on))return!0;this.logger.info(`\n ${cn}${nn}trigger${Y} ${nn}user_prompt${Y}`),this.logger.info(` ${`─`.repeat(50)}`);let a=t,o=n.CONTEXT_FILE;if(!a&&o){let e=x(r,o);await this.pathExists(e)&&(a=(await d(e,`utf-8`)).trim(),a&&this.logger.info(` ${on}found${Y} Existing context.md -> ${o}`))}if(!a)if(i)this.logger.info(` ${an}dry ${Y} Would prompt user for input`),a=`(dry-run: no prompt collected)`;else{this.logger.info(` ${an}input${Y} Enter your prompt (press Enter twice to finish):\n`);let e=[],t=se({input:process.stdin,output:process.stdout});this.activePrompt=t,this.activePromptSignal=null,a=await new Promise((n,r)=>{let i=!1,a=e=>{i||(i=!0,this.activePrompt=null,e())};t.on(`line`,n=>{n===``&&e.length>0&&e[e.length-1]===``?t.close():e.push(n)}),t.on(`SIGINT`,()=>{this.activePromptSignal=`SIGINT`,t.close()}),t.on(`close`,()=>a(()=>{let t=this.activePromptSignal;if(this.activePromptSignal=null,t){r(new P(t));return}e.length>0&&e[e.length-1]===``&&e.pop(),n(e.join(`
|
|
27
|
+
`))}))})}if(!a)return this.logger.error(` ${sn}fail${Y} No prompt provided. Aborting.`),!1;if(o){let e=x(r,o);await u(y(e),{recursive:!0}),await g(e,a,`utf-8`),this.logger.info(` ${on}saved${Y} ${a.split(`
|
|
28
|
+
`).length} line(s) -> ${o}`)}return n.USER_PROMPT=a,this.logger.info(` ${rn}prompt${Y} ${a.split(`
|
|
29
|
+
`)[0].slice(0,80)}${a.includes(`
|
|
30
|
+
`)?`...`:``}`),!0}async handleAgentDecision(e,t,n,r,i,a){let o=e.on?.agent_decision;if(!o?.steps)return!0;this.logger.info(`\n ${cn}${nn}trigger${Y} ${nn}agent_decision${Y}`),this.logger.info(` ${`─`.repeat(50)}`),a&&(t.HEARTBEAT_PROMPT=a,this.logger.info(` ${rn}prompt${Y} ${a.split(`
|
|
31
|
+
`)[0].slice(0,80)}${a.includes(`
|
|
32
|
+
`)?`...`:``}`));let s=t.CONTEXT_FILE;s&&await u(y(x(i.workflowDir,s)),{recursive:!0});let c={inputs:n,matrix:{},secrets:r,env:t};for(let e of o.steps)if(!await this.stepRunner.runStep(e,c,i))return this.logger.error(`\n ${sn}Agent decision aborted workflow${Y}`),!1;if(s&&!i.dryRun){let e=x(i.workflowDir,s);if(!await this.pathExists(e))return this.logger.error(` ${sn}fail${Y} Context file not created: ${s}`),!1;let t=(await d(e,`utf-8`)).trim();if(!t)return this.logger.error(` ${sn}fail${Y} Context file is empty: ${s}`),!1;this.logger.info(` ${on}ready${Y} context has ${t.split(`
|
|
33
|
+
`).length} line(s)`)}return!0}};const un=[`actions/checkout`,`actions/setup-node`,`actions/cache`,`actions/upload-artifact`,`actions/download-artifact`,`pnpm/action-setup`],dn=`bold.calm.cool.dark.deep.fair.fast.free.gold.keen.kind.loud.neat.pure.rare.safe.slim.soft.tall.warm.wild.wise.blue.gray.jade.iron.zinc.ruby.opal.onyx`.split(`.`),fn=`arch.beam.bird.bolt.cape.cove.dawn.dove.echo.fern.flux.gale.hawk.haze.iris.jade.kite.lake.lynx.mesa.moth.node.palm.peak.pine.raft.reef.sage.tide.vale`.split(`.`);var pn=class{generateHumanReadableId(){return`${dn[Math.floor(Math.random()*dn.length)]}-${fn[Math.floor(Math.random()*fn.length)]}`}parseWorkflowFile(e){let t=x(e);if(!S(t))throw Error(`Workflow file not found: ${t}`);let n=C(t,`utf-8`),r=He.parse(ce(n));if(r.imports&&this.resolveImports(r,t),!r.jobs||Object.keys(r.jobs).length===0)throw Error(`No jobs found in workflow file`);return this.resolveExtends(r),r}resolveImports(e,t,n=new Set){let r=x(t);if(n.has(r))throw Error(`Circular import detected: ${r}`);n.add(r);let i=r.replace(/\/[^/]+$/,``);for(let t of e.imports??[]){let a=x(i,t);if(!S(a))throw Error(`Imported workflow file not found: ${a} (from ${r})`);let o=ce(C(a,`utf-8`));if(o.imports&&this.resolveImports(o,a,n),o.env&&(e.env={...o.env,...e.env}),o.pre&&(e.pre||={},o.pre.services&&(e.pre.services=[...o.pre.services,...e.pre.services??[]]),o.pre.steps&&(e.pre.steps=[...o.pre.steps,...e.pre.steps??[]])),o.post&&(e.post||={},o.post.services&&(e.post.services=[...o.post.services,...e.post.services??[]]),o.post.steps&&(e.post.steps=[...o.post.steps,...e.post.steps??[]])),o.worktree){e.worktree||={};for(let t of[`beforeCreate`,`afterCreate`,`beforeCompleted`,`afterCompleted`])o.worktree[t]&&!e.worktree[t]&&(e.worktree[t]=o.worktree[t])}if(o[`max-workflows`]&&!e[`max-workflows`]&&(e[`max-workflows`]=o[`max-workflows`]),o[`launch-command`]&&!e[`launch-command`]&&(e[`launch-command`]=o[`launch-command`]),o.keybindings&&(e.keybindings={...o.keybindings,...e.keybindings}),o[`system-prompt`]&&(e[`system-prompt`]?e[`system-prompt`]=`${o[`system-prompt`]}\n\n${e[`system-prompt`]}`:e[`system-prompt`]=o[`system-prompt`]),o.jobs)for(let[t,n]of Object.entries(o.jobs))t in(e.jobs??{})||(e.jobs||={},e.jobs[t]=n)}delete e.imports}resolveExtends(e){let{jobs:t}=e,n=new Map;for(let[e,r]of Object.entries(t))e.startsWith(`.`)&&n.set(e,r);for(let[e,r]of Object.entries(t)){if(e.startsWith(`.`)||!r.extends)continue;let t=Array.isArray(r.extends)?r.extends:[r.extends],i=[...r.steps??[]],a=[...r.preJob?.steps??[]],o=[...r.postJob?.steps??[]],s=[],c=[],l=[];for(let i of t){let t=n.get(i);if(!t)throw Error(`Job "${e}" extends "${i}" but template not found`);s.push(...t.steps??[]),c.push(...t.preJob?.steps??[]),l.push(...t.postJob?.steps??[]),this.applyTemplate(r,t)}r.steps=[...s,...i],this.assignJobHookSteps(r,`preJob`,[...c,...a]),this.assignJobHookSteps(r,`postJob`,[...l,...o]),delete r.extends}for(let e of n.keys())delete t[e]}applyTemplate(e,t){e.steps=[...t.steps??[],...e.steps??[]],this.mergeJobHookSteps(e,t,`preJob`),this.mergeJobHookSteps(e,t,`postJob`),(t.env||e.env)&&(e.env={...t.env,...e.env}),t[`system-prompt`]&&e[`system-prompt`]?e[`system-prompt`]=`${t[`system-prompt`]}\n\n${e[`system-prompt`]}`:t[`system-prompt`]&&(e[`system-prompt`]=t[`system-prompt`]),t[`runs-on`]&&!e[`runs-on`]&&(e[`runs-on`]=t[`runs-on`]),t.strategy&&!e.strategy&&(e.strategy=t.strategy),t.context&&!e.context&&(e.context=t.context)}mergeJobHookSteps(e,t,n){let r=t[n]?.steps??[],i=e[n]?.steps??[];this.assignJobHookSteps(e,n,[...r,...i])}assignJobHookSteps(e,t,n){if(n.length>0){e[t]={steps:n};return}delete e[t]}loadSecrets(e){let t=new Map;if(!S(e))return t;let n=C(e,`utf-8`);for(let e of n.split(`
|
|
34
|
+
`)){let n=e.trim();if(!n||n.startsWith(`#`))continue;let r=n.indexOf(`=`);r!==-1&&t.set(n.slice(0,r),n.slice(r+1))}return t}interpolate(e,t){return e.replace(/\$\{\{\s*(.+?)\s*\}\}/g,(e,n)=>{let r=n.trim().split(`.`);if(r[0]===`inputs`&&r[1])return t.inputs.get(r[1])||``;if(r[0]===`matrix`&&r[1])return t.matrix[r[1]]||``;if(r[0]===`secrets`&&r[1])return t.secrets.get(r[1])||process.env[r[1]]||``;if(r[0]===`env`&&r[1])return t.env[r[1]]||process.env[r[1]]||``;if(r[0]===`runner`&&r[1]===`os`)return`macOS`;if(r[0]===`github`&&r[1]===`sha`)try{return o(`git rev-parse HEAD`,{encoding:`utf-8`,stdio:[`ignore`,`pipe`,`ignore`]}).trim()}catch{return`local`}return n.includes(`hashFiles`)?`local`:`\${{ ${n} }}`})}isActionSkipped(e){return un.some(t=>e.startsWith(t))}resolveJobOrder(e,t){let n=new Set,r=[],i=t=>{if(n.has(t))return;n.add(t);let a=e[t];if(!a)throw Error(`Job not found: ${t}`);let o=a.needs?Array.isArray(a.needs)?a.needs:[a.needs]:[];for(let e of o)i(e);r.push(t)};if(t)i(t);else for(let t of Object.keys(e))i(t);return r}expandMatrix(e){if(!e.strategy?.matrix)return[{}];let{include:t,...n}=e.strategy.matrix;if(t&&t.length>0)return t;let r=Object.keys(n).filter(e=>Array.isArray(n[e]));if(r.length===0)return[{}];let i=[{}];for(let e of r){let t=n[e],r=[];for(let n of i)for(let i of t)r.push({...n,[e]:String(i)});i=r}return i}};const mn=`\x1B[0m`,hn=`\x1B[2m`;var gn=class{constructor(e,t){this.stepRunner=e,this.logger=t}getWorktreeBranchName(e){return`worktree/${e.toLowerCase().replace(/[^a-z0-9-]+/g,`-`).replace(/^-|-$/g,``)}`}createWorktree(e,t){let n=this.getWorktreeBranchName(t),r=n.slice(9),i=x(y(e),`${te(e)}-worktree`),a=x(i,r);S(i)||ne(i,{recursive:!0}),S(a)&&(this.logger.info(` ${hn}clean${mn} Removing stale worktree at ${a}`),this.cleanupWorktreePath(e,a));try{o(`git branch -D "${n}"`,{cwd:e,stdio:[`ignore`,`pipe`,`ignore`]})}catch{}return this.logger.info(` [36mcreate${mn} Worktree at ${a} (branch: ${n})`),o(`git worktree add -b "${n}" "${a}" HEAD`,{cwd:e,stdio:[`ignore`,`pipe`,`ignore`]}),a}removeWorktree(e,t){if(S(t)){this.logger.info(` ${hn}remove${mn} Worktree at ${t}`);try{this.cleanupWorktreePath(e,t)}catch{this.logger.warn(` [33mwarn${mn} Failed to remove worktree (may need manual cleanup)`)}}}cleanupWorktreePath(e,t){if(this.isRegisteredWorktree(e,t)){o(`git worktree remove --force "${t}"`,{cwd:e,stdio:[`ignore`,`pipe`,`ignore`]});return}w(t,{recursive:!0,force:!0})}isRegisteredWorktree(e,t){try{return o(`git worktree list --porcelain`,{cwd:e,encoding:`utf-8`,stdio:[`ignore`,`pipe`,`ignore`]}).split(`
|
|
35
|
+
`).some(e=>e.startsWith(`worktree `)&&x(e.slice(9))===t)}catch{return!1}}async runHook(e,t,n,r,i,a){let o={inputs:r,matrix:{},secrets:i,env:n};for(let n of e.steps)if(!await this.stepRunner.runStep(n,o,{...a,workflowDir:t}))return!1;return!0}};const X=`\x1B[0m`,Z=`\x1B[1m`,_n=`\x1B[2m`,vn=`\x1B[32m`,yn=`\x1B[33m`,Q=`\x1B[31m`,$=`\x1B[34m`,bn=`SIGINT`,xn=`SIGTERM`,Sn=`workflow_execution`,Cn=`restart-from`,wn=`user_prompt`,Tn=`agent_decision`,En=`workflow_dispatch`,Dn=`Workflow post-cleanup failed`,On=`Workflow failed at job`;function kn(e,t){let n=Number(e);return Number.isInteger(n)&&n>0?n:t}var An=class{logger;parser;serviceManager;stepRunner;jobRunner;triggerService;worktreeService;registry;outputLines=[];interruptedSignal=null;constructor(e,t={}){let n=e||{info:e=>process.stdout.write(`${e}\n`),error:e=>console.error(e),warn:e=>console.error(e)},r=e=>{this.outputLines.push(e),this.outputLines.length>5e3&&this.outputLines.shift()};this.logger={info:e=>{r(e),n.info(e)},error:e=>{r(e),n.error(e)},warn:e=>{r(e),n.warn(e)}},this.parser=t.parser??new pn,this.serviceManager=t.serviceManager??new ut(this.logger),this.stepRunner=t.stepRunner??new tn(this.parser,this.logger),this.jobRunner=t.jobRunner??new _t(this.parser,this.stepRunner,this.logger),this.triggerService=t.triggerService??new ln(this.stepRunner,this.logger),this.worktreeService=t.worktreeService??new gn(this.stepRunner,this.logger),this.registry=t.registry??new $e}async run(e){this.outputLines=[],this.interruptedSignal=null;let t=e.dryRun??!1,n=e.continueOnError??!1,r=!1,i=e=>{r||(r=!0,this.interrupt(e))},a=()=>i(bn),o=()=>i(xn);process.on(bn,a),process.on(xn,o);try{return await this.executeWorkflow(e,t,n,e.keepWorktree??!1)}catch(e){if(e instanceof P||this.isInterrupted())return await this.serviceManager.stopAll(),this.createInterruptedResult();throw e}finally{process.off(bn,a),process.off(xn,o),await this.serviceManager.stopAll()}}interrupt(e,t={phase:Sn}){if(this.interruptedSignal)return;this.interruptedSignal=e;let n=t.phase===Sn?``:` (${t.phase})`;this.logger.info(`\n\n${yn}${Z}Interrupted — shutting down...${X}${n}`),this.triggerService.abortActivePrompt(e),this.stepRunner.stopActiveStep(e),this.serviceManager.stopAll()}isInterrupted(){return this.interruptedSignal===bn||this.interruptedSignal===xn}createInterruptedResult(){return{exitCode:130,output:this.outputLines.join(`
|
|
36
|
+
`)}}parseFixRestartFrom(e,t){if(!e.startsWith(`---`))return{};let n=e.indexOf(`---`,3);if(n<0)return{};let r=e.slice(3,n);for(let e of r.split(`
|
|
37
|
+
`)){let n=e.trim();if(n.startsWith(`${Cn}:`)){let e=n.slice(`${Cn}:`.length).trim();return t.includes(e)?{restartFrom:e}:{invalidTarget:e}}}return{}}async pathExists(e){try{return await l(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async waitForServiceStartup(){await new Promise(e=>{setTimeout(e,2e3)})}resolveRunner(e){if(e.runner&&e.cliAgent&&e.runner!==e.cliAgent)throw Error(`Conflicting runner selectors: runner="${e.runner}" cliAgent="${e.cliAgent}"`);return e.runner??e.cliAgent}async executeWorkflow(e,t,n,r=!1){let i=x(e.workflowPath),a=this.parser.parseWorkflowFile(i),s=this.resolveRunner(e),c=null,l=null,u=null,f=y(i),p=f,m=null,g=null,_=!1,ee=!1,v,b,ne,C=!!a.worktree,w=new Map,T=e.secretFile?this.parser.loadSecrets(e.secretFile):new Map,E={};try{let u=a.on?.[En]?.inputs||{};for(let[e,t]of Object.entries(u))t.default&&w.set(e,t.default);if(e.inputs)for(let[t,n]of Object.entries(e.inputs))w.set(t,n);if(a.env)for(let[e,t]of Object.entries(a.env))E[e]=String(t);if(e.env)for(let[t,n]of Object.entries(e.env))E[t]=n;s&&(E.WORKFLOW_RUNNER=s,E.WORKFLOW_CLI_AGENT=s);let D=f;for(;D!==`/`;){if(await this.pathExists(x(D,`.git`))){f=D;break}D=y(D)}let re=a[`max-workflows`];if(re){let t=this.registry.resolveWorkspace(e.workspace,a.workspace),n=await this.registry.countRunningWorkflows(t);if(n>=re)throw new rt(t,n,re)}let ie=a[`launch-command`];if(ie&&!e.skipLaunch){let t=this.buildLaunchCliCommand(e,i),n=e.name||a.name||te(i),r=e.name?n:`${n}-${this.parser.generateHumanReadableId()}`,s=ie.replace(`{name}`,r).replace(`{command}`,t);this.logger.info(`${_n}Delegating via launch-command: ${s}${X}`);try{return o(s,{stdio:`inherit`,cwd:f,env:this.buildLaunchEnvironment()}),{exitCode:0,output:this.outputLines.join(`
|
|
38
|
+
`)}}catch(e){return{exitCode:e.status??1,output:this.outputLines.join(`
|
|
39
|
+
`)}}}let ae=e.name||a.name||te(i),oe=e.name?ae:`${ae}-${this.parser.generateHumanReadableId()}`;if(c=await this.registry.createRun({cliAgent:e.cliAgent,continueOnError:e.continueOnError,displayName:oe,dryRun:t,env:e.env,inputs:e.inputs,job:e.job,keepWorktree:e.keepWorktree,prompt:e.prompt,runner:s,secretFile:e.secretFile,skipLaunch:e.skipLaunch,workflowPath:i,workflowWorkspace:a.workspace,workspace:e.workspace}),E.WORKFLOW_RUN_DIR=c.runDir,E.WORKFLOW_WORKSPACE=c.workspace,E.CONTEXT_FILE&&(E.CONTEXT_FILE=c.contextPath,E.CHANGELOG_FILE=c.changelogPath),this.logger.info(`${Z}${`═`.repeat(60)}${X}`),this.logger.info(` ${Z}run-workflow${X} - ${c.displayName}`),this.logger.info(`${Z}${`═`.repeat(60)}${X}`),this.logger.info(` File: ${i}`),this.logger.info(` Workspace: ${c.workspace||`default`}`),this.logger.info(` Run Dir: ${c.runDir}`),this.logger.info(` CWD: ${f}`),w.size>0&&this.logger.info(` Inputs: ${[...w.entries()].map(([e,t])=>`${e}=${t}`).join(`, `)}`),T.size>0&&this.logger.info(` Secrets: ${[...T.keys()].join(`, `)}`),e.job&&this.logger.info(` Target: ${e.job}`),s&&this.logger.info(` Runner: ${s}`),a.pre){let e=a.pre.services?.length||0,t=a.pre.steps?.length||0;this.logger.info(` Pre: ${e} service(s), ${t} setup step(s)`)}if(a.post){let e=a.post.services?.length||0,t=a.post.steps?.length||0;this.logger.info(` Post: ${e} service(s), ${t} cleanup step(s)`)}C&&this.logger.info(` Worktree: enabled${r?` (keep on completion)`:``}`);let se=a.on&&wn in a.on?wn:a.on?.[Tn]?Tn:En;if(this.logger.info(` Trigger: ${se}`),this.logger.info(` Mode: ${t?`dry-run`:`execute`}`),this.logger.info(`${Z}${`═`.repeat(60)}${X}`),!await this.triggerService.handleUserPrompt(a,e.prompt||null,E,f,t))return this.isInterrupted()?(l=this.createInterruptedResult(),l):(this.logger.error(`\n${Q}${Z}Workflow aborted: no prompt provided${X}`),l={exitCode:1,output:this.outputLines.join(`
|
|
40
|
+
`)},l);if(!await this.triggerService.handleAgentDecision(a,E,w,T,{runner:s,cliAgent:e.cliAgent,dryRun:t,continueOnError:n,stopRequestPath:c.stopRequestPath,workflowDir:f},e.prompt||null))return this.isInterrupted()?(l=this.createInterruptedResult(),l):(this.logger.info(`\n${yn}${Z}Workflow skipped: agent decided nothing to do${X}`),l={exitCode:2,output:this.outputLines.join(`
|
|
41
|
+
`)},l);if(p=f,C&&e.recovery){if(!e.recovery.worktreePath||!S(e.recovery.worktreePath))throw Error(`Recoverable worktree not found: ${e.recovery.worktreePath??`(missing)`}`);p=e.recovery.originalRepoPath??p,m=e.recovery.worktreePath,g=e.recovery.worktreeBranch??this.worktreeService.getWorktreeBranchName(c.displayName),f=m,E.WORKTREE_PATH=m,E.WORKTREE_BRANCH=g,E.WORKFLOW_NAME=c.displayName,E.ORIGINAL_REPO_PATH=p,this.logger.info(`\n ${$}${Z}worktree${X} ${Z}Reusing worktree${X}`),this.logger.info(` ${`─`.repeat(50)}`),this.logger.info(` ${_n}path ${X} ${m}`)}else if(C&&!t)a.worktree?.beforeCreate&&(this.logger.info(`\n ${$}${Z}worktree${X} ${Z}beforeCreate${X}`),this.logger.info(` ${`─`.repeat(50)}`),await this.worktreeService.runHook(a.worktree.beforeCreate,f,E,w,T,{runner:s,cliAgent:e.cliAgent,dryRun:t,continueOnError:n,stopRequestPath:c.stopRequestPath})||(this.isInterrupted()?l=this.createInterruptedResult():(this.logger.error(`\n${Q}${Z}Workflow aborted: worktree beforeCreate hook failed${X}`),l={exitCode:1,output:this.outputLines.join(`
|
|
42
|
+
`)}))),l||(this.logger.info(`\n ${$}${Z}worktree${X} ${Z}Creating worktree${X}`),this.logger.info(` ${`─`.repeat(50)}`),g=this.worktreeService.getWorktreeBranchName(c.displayName),m=this.worktreeService.createWorktree(f,c.displayName),f=m,E.WORKTREE_PATH=m,E.WORKTREE_BRANCH=g,E.WORKFLOW_NAME=c.displayName,E.ORIGINAL_REPO_PATH=p,a.worktree?.afterCreate&&(this.logger.info(`\n ${$}${Z}worktree${X} ${Z}afterCreate${X}`),this.logger.info(` ${`─`.repeat(50)}`),await this.worktreeService.runHook(a.worktree.afterCreate,m,E,w,T,{runner:s,cliAgent:e.cliAgent,dryRun:t,continueOnError:n,stopRequestPath:c.stopRequestPath})||(this.isInterrupted()?l=this.createInterruptedResult():(this.logger.error(`\n${Q}${Z}Workflow aborted: worktree afterCreate hook failed${X}`),l={exitCode:1,output:this.outputLines.join(`
|
|
43
|
+
`)}),ee=!r)));else if(C&&t){let e=y(f),t=te(f),n=c.displayName.toLowerCase().replace(/[^a-z0-9-]+/g,`-`).replace(/^-|-$/g,``),r=x(e,`${t}-worktree`,n);this.logger.info(`\n ${$}${Z}worktree${X} ${Z}(dry-run)${X} Would create at ${r}`)}!l&&a.pre&&(await this.runPreBlock(a.pre,E,w,T,{runner:s,cliAgent:e.cliAgent,dryRun:t,continueOnError:n,stopRequestPath:c.stopRequestPath,workflowDir:f})||(this.isInterrupted()?l=this.createInterruptedResult():(this.logger.error(`\n${Q}${Z}Workflow aborted: pre-conditions failed${X}`),l={exitCode:1,output:this.outputLines.join(`
|
|
44
|
+
`)}),ee=!!(m&&!r)));let ce=kn(E.MAX_RETRIES,3),le=kn(E.FIX_LOOP_MAX_CYCLES,3),O=this.parser.resolveJobOrder(a.jobs,e.recovery?e.recovery.originalJob||null:e.job||null);this.logger.info(`\n ${_n}Job order: ${O.join(` -> `)} (max retries: ${ce})${X}`);let ue=new Set,k=E.WORKFLOW_RUN_DIR?x(E.WORKFLOW_RUN_DIR,`fix.md`):null,A=0,j=0;if(e.recovery?.startJob&&(j=O.indexOf(e.recovery.startJob),j<0))throw Error(`Recovery job not found in workflow order: ${e.recovery.startJob}`);for(;!l&&j<O.length;){let r=O[j],i=a.jobs[r],o=await this.jobRunner.runJob(r,i,{inputs:w,secrets:T,workflowEnv:E,workflowSystemPrompt:a[`system-prompt`],jobOrder:O,allJobs:a.jobs},{runner:s,cliAgent:e.cliAgent,dryRun:t,continueOnError:n,stopRequestPath:c.stopRequestPath,workflowDir:f,maxRetries:ce});if(this.isInterrupted()&&(l=this.createInterruptedResult()),!l&&!o&&(v=r,b=`${On} "${r}"`,this.logger.error(`\n${Q}${Z}${On} "${r}"${X}`),await this.serviceManager.stopAll(),l={exitCode:1,output:this.outputLines.join(`
|
|
45
|
+
`)}),!l){if(ue.add(r),k&&await this.pathExists(k)&&!t){A++;let e=(await d(k,`utf-8`)).trim();if(await h(k),E.CONTEXT_FILE&&await this.pathExists(E.CONTEXT_FILE)&&await this.appendFixRequestToContext(E.CONTEXT_FILE,A,e),A>le){v=r,b=`Fix loop limit reached (${le} cycles).`,ne=A,this.logger.error(`\n${Q}${Z}Fix loop limit reached (${le} cycles). Aborting.${X}`),l={exitCode:1,output:this.outputLines.join(`
|
|
46
|
+
`)};continue}let{restartFrom:t,invalidTarget:n}=this.parseFixRestartFrom(e,O);this.logger.info(`\n${yn}${Z}fix.md detected after "${r}" (cycle ${A}/${le})${X}`),this.logger.info(`${_n}${e.split(`
|
|
47
|
+
`)[0].slice(0,100)}${e.includes(`
|
|
48
|
+
`)?`...`:``}${X}`),n&&this.logger.warn(`${yn}fix.md restart-from "${n}" is not a valid job (available: ${O.join(`, `)}), falling back to default${X}`);let i=t?O.indexOf(t):-1,a=O.indexOf(`development`);j=i>=0?i:a>=0?a:1,this.logger.info(`${yn}Restarting from job "${O[j]}"${X}\n`);continue}j++}}!l&&this.isInterrupted()&&(l=this.createInterruptedResult()),l||=(_=!0,this.logger.info(`\n${Z}${`═`.repeat(60)}${X}`),this.logger.info(` ${vn}${Z}Workflow completed successfully${X}`),this.logger.info(` Jobs run: ${[...ue].join(`, `)}`),m&&this.logger.info(` Worktree: ${m}`),this.logger.info(`${Z}${`═`.repeat(60)}${X}\n`),{exitCode:0,output:this.outputLines.join(`
|
|
49
|
+
`)})}catch(e){if(u=e,e instanceof P||this.isInterrupted())l=this.createInterruptedResult();else throw e}finally{if(_&&l?.exitCode===0&&C&&a.worktree?.beforeCompleted&&!t&&m&&(this.logger.info(`\n ${$}${Z}worktree${X} ${Z}beforeCompleted${X}`),this.logger.info(` ${`─`.repeat(50)}`),await this.worktreeService.runHook(a.worktree.beforeCompleted,m,E,w,T,{runner:s,cliAgent:e.cliAgent,dryRun:t,continueOnError:n})||(this.isInterrupted()?l=this.createInterruptedResult():(this.logger.error(`\n${Q}${Z}worktree beforeCompleted hook failed${X}`),l={exitCode:1,output:this.outputLines.join(`
|
|
50
|
+
`)}))),a.post)try{await this.runPostBlock(a.post,E,w,T,{runner:s,cliAgent:e.cliAgent,dryRun:t,continueOnError:n,workflowDir:f})||(this.logger.error(`\n${Q}${Z}${Dn}${X}`),(!l||l.exitCode===0||l.exitCode===2)&&(l={exitCode:1,output:this.outputLines.join(`
|
|
51
|
+
`)}))}catch(e){u??=e,this.logger.error(`\n${Q}${Z}${Dn}${X}`),(!l||l.exitCode===0||l.exitCode===2)&&(l={exitCode:1,output:this.outputLines.join(`
|
|
52
|
+
`)})}_&&l?.exitCode===0&&C&&a.worktree?.afterCompleted&&!t&&!r&&(this.logger.info(`\n ${$}${Z}worktree${X} ${Z}afterCompleted${X}`),this.logger.info(` ${`─`.repeat(50)}`),await this.worktreeService.runHook(a.worktree.afterCompleted,p,E,w,T,{runner:s,cliAgent:e.cliAgent,dryRun:t,continueOnError:n})||(this.isInterrupted()?l=this.createInterruptedResult():(this.logger.error(`\n${Q}${Z}worktree afterCompleted hook failed${X}`),l={exitCode:1,output:this.outputLines.join(`
|
|
53
|
+
`)}))),ee&&m&&this.worktreeService.removeWorktree(p,m),l&&={...l,output:this.outputLines.join(`
|
|
54
|
+
`)},c&&await this.finalizeRegistryRun(c,l,u,{failedJob:v,failureReason:b,fixLoopCycle:ne,originalRepoPath:m?p:void 0,worktreeBranch:g??void 0,worktreePath:m??void 0})}return l??{exitCode:1,output:this.outputLines.join(`
|
|
55
|
+
`)}}async finalizeRegistryRun(e,t,n,r={}){let i=t?.exitCode===130||n instanceof P,a=t?.exitCode??(i?130:1),o=a===0||a===2?`completed`:`error`,s=a===0?`success`:a===2?`skipped`:i||this.isInterrupted()?`interrupted`:`failed`,c=n instanceof Error?n.message:a===1?this.lastMeaningfulOutputLine():void 0;await this.registry.finalizeRun(e,{errorMessage:c,exitCode:a,...r,outcome:s,stage:o})}async appendFixRequestToContext(e,t,n){await g(e,`${await d(e,`utf-8`)}\n\n---\n## Fix Request (cycle ${t})\n${n}`,`utf-8`)}resolveCliPath(){let e=nt,t=x(`/`);for(;e!==t;){let t=x(e,`cli.cjs`);if(S(t))return t;let n=x(e,`dist`,`cli.cjs`);if(S(n))return n;e=y(e)}throw Error(`Unable to locate workflow-mcp cli.cjs from `+nt)}buildLaunchEnvironment(){let e={...process.env};return delete e.CMUX_WORKSPACE_ID,e}buildLaunchCliCommand(e,t){let n=[`node`,this.resolveCliPath(),`run-workflow`,t,`--skip-launch`],r=this.resolveRunner(e);if(e.job&&n.push(`--job`,e.job),r&&n.push(`--runner`,r),e.dryRun&&n.push(`--dry-run`),e.continueOnError&&n.push(`--continue-on-error`),e.keepWorktree&&n.push(`--keep-worktree`),e.prompt&&n.push(`--prompt`,`'${e.prompt.replace(/'/g,`'\\''`)}'`),e.name&&n.push(`--name`,`'${e.name}'`),e.workspace&&n.push(`--workspace`,`'${e.workspace}'`),e.secretFile&&n.push(`--secret-file`,e.secretFile),e.inputs)for(let[t,r]of Object.entries(e.inputs))n.push(`--input`,`${t}=${r}`);if(e.env)for(let[t,r]of Object.entries(e.env))n.push(`--env`,`${t}=${r}`);return n.join(` `)}lastMeaningfulOutputLine(){return[...this.outputLines].reverse().find(e=>e.trim().length>0)}async runPreBlock(e,t,n,r,i){if(this.logger.info(`\n ${$}${Z}pre${X} ${Z}Pre-conditions${X}`),this.logger.info(` ${`─`.repeat(50)}`),t.CONTEXT_FILE&&await u(y(x(i.workflowDir,t.CONTEXT_FILE)),{recursive:!0}),e.services&&e.services.length>0){this.logger.info(`\n ${$}${Z}services${X}`);for(let n of e.services)if(await this.serviceManager.startService(n,t,i.workflowDir,i.dryRun)&&n[`ready-check`]&&!i.dryRun){let e=await this.serviceManager.waitForServiceReady(n,i.workflowDir,t,()=>this.interruptedSignal!==null);if(this.isInterrupted())return!1;if(!e&&!i.continueOnError)return await this.serviceManager.stopAll(),!1}!i.dryRun&&this.serviceManager.getRunningServices().length>0&&await this.waitForServiceStartup()}if(e.steps&&e.steps.length>0){this.logger.info(`\n ${$}${Z}setup${X}`);let a={inputs:n,matrix:{},secrets:r,env:t};for(let t of e.steps)if(!await this.stepRunner.runStep(t,a,i))return this.logger.error(`\n ${Q}Pre-condition step failed${X}`),await this.serviceManager.stopAll(),!1}return this.logger.info(`\n ${vn}Pre-conditions ready${X}`),!0}async runPostBlock(e,t,n,r,i){this.logger.info(`\n ${$}${Z}post${X} ${Z}Cleanup${X}`),this.logger.info(` ${`─`.repeat(50)}`),await this.serviceManager.stopAll();try{if(e.services&&e.services.length>0){this.logger.info(`\n ${$}${Z}services${X}`);for(let n of e.services)if(await this.serviceManager.startService(n,t,i.workflowDir,i.dryRun)&&n[`ready-check`]&&!i.dryRun&&!await this.serviceManager.waitForServiceReady(n,i.workflowDir,t,()=>!1)&&!i.continueOnError)return!1;!i.dryRun&&this.serviceManager.getRunningServices().length>0&&await this.waitForServiceStartup()}if(e.steps&&e.steps.length>0){this.logger.info(`\n ${$}${Z}cleanup${X}`);let a={inputs:n,matrix:{},secrets:r,env:t};for(let t of e.steps)if(!await this.stepRunner.runStep(t,a,i))return this.logger.error(`\n ${Q}Post-cleanup step failed${X}`),!1}return this.logger.info(`\n ${vn}Cleanup complete${X}`),!0}finally{await this.serviceManager.stopAll()}}},jn=class{constructor(e=new $e,t=new An(void 0,{registry:e})){this.registry=e,this.runner=t}async recover(e){let t=await this.registry.readRunByKey(e.workspace,`error`,e.runKey),n=e.job??t.failedJob;if(!n)throw Error(`Workflow run "${t.workspace}/${t.runKey}" does not include a recoverable failed job`);if(t.worktreePath&&!S(t.worktreePath))throw Error(`Recoverable worktree not found: ${t.worktreePath}`);let r=e.runner??t.runner??t.cliAgent;return await this.runner.run({cliAgent:t.cliAgent,runner:r,workflowPath:t.workflowPath,job:n,inputs:t.inputs,env:t.env,secretFile:t.secretFile,dryRun:e.dryRun??t.dryRun,continueOnError:t.continueOnError,keepWorktree:t.keepWorktree,prompt:t.prompt,name:t.displayName,workspace:t.workspace,skipLaunch:!0,recovery:{originalJob:e.job?void 0:t.job,originalRepoPath:t.originalRepoPath,runKey:t.runKey,startJob:n,worktreeBranch:t.worktreeBranch,worktreePath:t.worktreePath}})}};const Mn=r.object({dryRun:r.boolean().optional().describe(`Print recovery steps without executing.`),job:r.string().optional().describe(`Optional job override. Defaults to the failed job recorded on the run.`),runKey:r.string().min(1).describe(`Run key of the failed workflow to recover.`),runner:r.string().optional().describe(`Optional runner key override for step command maps.`),workspace:r.string().optional().describe(`Workspace containing the failed workflow. Defaults to default.`)});var Nn=class e{static TOOL_NAME=`recover_workflow`;constructor(e=new jn){this.service=e}getInputSchema(){return Mn}getDefinition(){return{name:e.TOOL_NAME,description:`Recover a failed workflow run from the local workflow registry.`,inputSchema:r.toJSONSchema(Mn)}}async execute(e){try{let t=Mn.parse(e),n=await this.service.recover(t);return{content:[{type:`text`,text:n.output||`Workflow recovery finished with exit code ${n.exitCode}.`}],isError:n.exitCode===0?void 0:!0}}catch(e){return{content:[{type:`text`,text:`Failed to recover workflow. ${e instanceof Error?e.message:`Unknown error`}`}],isError:!0}}}};const Pn=r.object({workflowPath:r.string().describe(`Path to the workflow YAML file (e.g., .github/workflows/deploy.yml)`),runner:r.string().optional().describe(`Preferred runner key for step command maps (e.g. ollama, claude, codex)`),cliAgent:r.string().optional().describe(`Deprecated alias for runner. Preferred runner command key for step command maps.`),job:r.string().optional().describe(`Run only this job (and its dependencies)`),inputs:r.record(r.string(),r.string()).optional().describe(`Workflow dispatch inputs as key-value pairs`),env:r.record(r.string(),r.string()).optional().describe(`Extra environment variables as key-value pairs`),secretFile:r.string().optional().describe(`Path to a dotenv-style secrets file`),dryRun:r.boolean().optional().describe(`Print steps without executing`),continueOnError:r.boolean().optional().describe(`Continue past step failures`),keepWorktree:r.boolean().optional().describe(`Keep worktree on completion (skip merge and cleanup for retry)`),prompt:r.string().optional().describe(`User prompt for user_prompt trigger workflows`),name:r.string().optional().describe(`Name for the workflow run context directory`),workspace:r.string().optional().describe(`Workspace for workflow registry storage`)});var Fn=class e{static TOOL_NAME=`run_workflow`;constructor(e=new An){this.service=e}getInputSchema(){return Pn}getDefinition(){return{name:e.TOOL_NAME,description:`Run a GitHub Actions workflow file locally. Parses the workflow YAML and executes run steps on the host machine, respecting job dependencies, matrix strategies, environment variables, and workflow_dispatch inputs.`,inputSchema:r.toJSONSchema(Pn)}}async execute(e){try{let t=Pn.parse(e);if(t.runner&&t.cliAgent&&t.runner!==t.cliAgent)throw Error(`Conflicting runner selectors: runner="${t.runner}" cliAgent="${t.cliAgent}"`);let n={cliAgent:t.cliAgent,runner:t.runner??t.cliAgent,workflowPath:t.workflowPath,job:t.job,inputs:t.inputs,env:t.env,secretFile:t.secretFile,dryRun:t.dryRun,continueOnError:t.continueOnError,keepWorktree:t.keepWorktree,prompt:t.prompt,name:t.name,workspace:t.workspace},r=await this.service.run(n);return r.exitCode!==0&&r.exitCode!==2?{content:[{type:`text`,text:`Workflow failed (exit code ${r.exitCode}):\n\n${r.output}`}],isError:!0}:{content:[{type:`text`,text:r.output||`Workflow completed successfully.`}]}}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:`Unknown error`}`}],isError:!0}}}},In=class e{static TOOL_NAME=`schedule-cron`;constructor(e=new Ce){this.service=e}getInputSchema(){return ve}getDefinition(){return{name:e.TOOL_NAME,description:`Schedule a headless Claude Code or Codex CLI run as a system cron job. Specify either a cron expression or an interval in minutes.`,inputSchema:r.toJSONSchema(ve)}}async execute(t){try{let e=ve.parse(t),n=await this.service.schedule(e);return{content:[{type:`text`,text:JSON.stringify(n,null,2)}]}}catch(n){let r=new ue(`Failed to schedule cron job.`,`SCHEDULE_CRON_TOOL_FAILED`,{tool:e.TOOL_NAME,name:t.name,cwd:t.cwd},{cause:n});return console.error(`[${e.TOOL_NAME}] ${r.message}`,r.context),{content:[{type:`text`,text:JSON.stringify({code:r.code,context:r.context,message:r.message},null,2)}],isError:!0}}}};const Ln=r.object({reason:r.string().optional().describe(`Optional stop reason to record.`),runKey:r.string().min(1).describe(`Run key of the running workflow to stop.`),workspace:r.string().optional().describe(`Workspace containing the running workflow. Defaults to default.`)});var Rn=class e{static TOOL_NAME=`stop_workflow`;constructor(e=new $e){this.registry=e}getInputSchema(){return Ln}getDefinition(){return{name:e.TOOL_NAME,description:`Request a running workflow to stop gracefully without taking over terminal stdin.`,inputSchema:r.toJSONSchema(Ln)}}async execute(e){try{let t=Ln.parse(e),n=await this.registry.requestStop(t.workspace,t.runKey,t.reason);return{content:[{type:`text`,text:JSON.stringify({reason:n.reason,requestedAt:n.requestedAt,runKey:t.runKey,workspace:this.registry.resolveWorkspace(t.workspace)},null,2)}]}}catch(e){return{content:[{type:`text`,text:`Failed to request workflow stop. ${e instanceof Error?e.message:`Unknown error`}`}],isError:!0}}}};const zn=[Fn.TOOL_NAME,tt.TOOL_NAME,Nn.TOOL_NAME,In.TOOL_NAME,we.TOOL_NAME,Rn.TOOL_NAME];function Bn(){let r=new e({name:`workflow-mcp`,version:`0.1.0`},{capabilities:{tools:{}}}),i=new Fn,a=new tt,o=new Nn,s=new In,c=new we,l=new Rn;return r.setRequestHandler(n,async()=>({tools:[i.getDefinition(),a.getDefinition(),o.getDefinition(),s.getDefinition(),c.getDefinition(),l.getDefinition()]})),r.setRequestHandler(t,async e=>{let{name:t,arguments:n}=e.params;if(t===Fn.TOOL_NAME)return await i.execute(n);if(t===tt.TOOL_NAME)return await a.execute(n);if(t===Nn.TOOL_NAME)return await o.execute(n);if(t===In.TOOL_NAME)return await s.execute(n);if(t===we.TOOL_NAME)return await c.execute();if(t===Rn.TOOL_NAME)return await l.execute(n);throw new O(t,zn)}),r}var Vn=class{server;transport=null;constructor(e){this.server=e}async start(){this.transport=new le,await this.server.connect(this.transport),console.error(`workflow-mcp MCP server started on stdio`)}async stop(){this.transport&&=(await this.transport.close(),null)}};export{xt as a,pe as c,An as i,ve as l,Bn as n,$e as o,jn as r,Ce as s,Vn as t};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agimon-ai/workflow-mcp",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.1",
|
|
4
4
|
"description": "MCP server for running GitHub Actions workflows locally",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"mcp",
|
|
@@ -36,10 +36,10 @@
|
|
|
36
36
|
"commander": "14.0.3",
|
|
37
37
|
"js-yaml": "4.1.1",
|
|
38
38
|
"zod": "4.4.1",
|
|
39
|
-
"@agimon-ai/foundation-
|
|
40
|
-
"@agimon-ai/foundation-
|
|
41
|
-
"@agimon-ai/
|
|
42
|
-
"@agimon-ai/
|
|
39
|
+
"@agimon-ai/foundation-port-registry": "0.10.1",
|
|
40
|
+
"@agimon-ai/foundation-process-registry": "0.10.1",
|
|
41
|
+
"@agimon-ai/foundation-validator": "0.7.1",
|
|
42
|
+
"@agimon-ai/log-sink-mcp": "0.10.1"
|
|
43
43
|
},
|
|
44
44
|
"devDependencies": {
|
|
45
45
|
"@types/js-yaml": "4.0.9",
|
package/dist/stdio-BPkG6mPS.cjs
DELETED
|
@@ -1,55 +0,0 @@
|
|
|
1
|
-
let e=require(`@modelcontextprotocol/sdk/server/index.js`),t=require(`@modelcontextprotocol/sdk/types.js`),n=require(`zod`),r=require(`node:child_process`),i=require(`node:util`),a=require(`node:fs/promises`),o=require(`node:os`),s=require(`node:path`),c=require(`node:fs`),l=require(`@agimon-ai/foundation-port-registry`),u=require(`@agimon-ai/foundation-process-registry`),d=require(`node:crypto`),f=require(`node:readline`),p=require(`js-yaml`),m=require(`@modelcontextprotocol/sdk/server/stdio.js`);var h=class extends Error{code=`WORKFLOW_TOOL_NOT_FOUND`;constructor(e,t){super(`Unknown tool "${e}". Available tools: ${t.join(`, `)}`),this.toolName=e,this.availableTools=t,this.name=`WorkflowToolNotFoundError`}},g=class extends Error{constructor(e,t,n={},r){super(e,r),this.code=t,this.context=n,this.name=`WorkflowToolError`}},_=class extends Error{constructor(e,t,n={},r){super(e,r),this.code=t,this.context=n,this.name=`CronError`}};const v=`# workflow-mcp:cron:`,y=`crontab`,b=`claude`,x=`codex`,S=`--cwd`,C=`CRON_WRITE_FAILED`,ee=n.z.enum([b,x]),te=n.z.object({name:n.z.string().min(1),cwd:n.z.string().min(1),cli:ee,schedule:n.z.string().min(1),prompt:n.z.string().optional(),promptFile:n.z.string().optional(),createdAt:n.z.string().min(1)}),w=n.z.object({name:n.z.string().min(1),cwd:n.z.string().min(1),cli:ee.optional(),prompt:n.z.string().optional(),promptFile:n.z.string().optional(),schedule:n.z.string().optional(),intervalMinutes:n.z.number().positive().optional()});function ne(e){return`'${e.replace(/'/g,`'\\''`)}'`}function re(e,t,n,r){let i=n?ne(n):r?`"$(cat ${ne(r)})"`:void 0;if(e===`codex`){let e=[x,`--approval-mode`,`full-auto`];return i&&e.push(`-q`,i),e.push(S,ne(t)),e.join(` `)}let a=[b,`--dangerously-skip-permissions`];return i&&a.push(`-p`,i),a.push(S,ne(t)),a.join(` `)}function ie(e){if(e<=0)throw Error(`Interval must be a positive number of minutes`);if(e<60)return`*/${e} * * * *`;let t=Math.floor(e/60);return t<24?`0 */${t} * * *`:`0 0 */${Math.floor(t/24)} * *`}const T=(0,i.promisify)(r.execFile);var ae=class{logger;constructor(e){this.logger=e??{info:e=>process.stdout.write(`${e}\n`),error:e=>console.error(e),warn:e=>console.error(e)}}async readCrontab(){try{let{stdout:e}=await T(y,[`-l`]);return e}catch(e){let t=e.code;if(t===`ENOENT`||(e.stderr??``).includes(`no crontab for`))return``;throw this.logger.error(`[CronService.readCrontab] failed exitCode=${t}`),new _(`Failed to read current crontab.`,`CRON_READ_FAILED`,{exitCode:t},{cause:e})}}async writeCrontab(e){let t=``,n=(0,r.execFile)(y,[`-`]);n.stderr?.on(`data`,e=>{t+=e}),n.stdin?.write(e),n.stdin?.end(),await new Promise((r,i)=>{n.on(`close`,n=>{n===0?r():(this.logger.error(`[CronService.writeCrontab] failed exitCode=${n} stderr=${t}`),i(new _(`crontab rejected input (exit ${n}).`,C,{exitCode:n,stderr:t,contentLength:e.length})))}),n.on(`error`,e=>{this.logger.error(`[CronService.writeCrontab] spawn failed: ${e.message}`),i(new _(`Failed to spawn crontab process.`,C,{},{cause:e}))})})}async schedule(e){let t=e.cli??`claude`;if(!e.schedule&&!e.intervalMinutes)throw new _(`Either schedule (cron expression) or intervalMinutes must be provided.`,`CRON_INVALID_INPUT`,{name:e.name});let n=e.schedule??ie(e.intervalMinutes),r=re(t,e.cwd,e.prompt,e.promptFile),i=new Date().toISOString(),a=te.parse({name:e.name,cwd:e.cwd,cli:t,schedule:n,prompt:e.prompt,promptFile:e.promptFile,createdAt:i}),o=await this.readCrontab(),s=this.removeCronBlock(o,e.name),c=`${`${v}${e.name}`}\n${`# workflow-mcp:meta:${JSON.stringify(a)}`}\n${`${n} ${r}`}`,l=s.trimEnd()?`${s.trimEnd()}\n${c}\n`:`${c}\n`;return await this.writeCrontab(l),this.logger.info(`Scheduled cron "${e.name}" [${n}]`),a}async list(){let e=await this.readCrontab(),t=[],n=e.split(`
|
|
2
|
-
`);for(let e=0;e<n.length;e++){let r=n[e];if(r.startsWith(`# workflow-mcp:meta:`))try{let e=r.slice(20),n=te.parse(JSON.parse(e));t.push(n)}catch(t){this.logger.warn(`[CronService.list] skipping malformed metadata at line ${e+1}: ${t.message}`)}}return t}async remove(e){let t=await this.readCrontab(),n=this.removeCronBlock(t,e);return n===t?!1:(await this.writeCrontab(n),this.logger.info(`Removed cron "${e}"`),!0)}removeCronBlock(e,t){let n=e.split(`
|
|
3
|
-
`),r=[],i=`${v}${t}`,a=!1;for(let e of n){if(e===i){a=!0;continue}if(a){if(e.startsWith(`# workflow-mcp:meta:`))continue;a=!1;continue}r.push(e)}return r.join(`
|
|
4
|
-
`)}},E=class e{static TOOL_NAME=`list-crons`;constructor(e=new ae){this.service=e}getInputSchema(){return n.z.object({})}getDefinition(){return{name:e.TOOL_NAME,description:`List all cron jobs scheduled via workflow-mcp, showing name, schedule, CLI, cwd, and prompt.`,inputSchema:n.z.toJSONSchema(n.z.object({}))}}async execute(){try{let e=await this.service.list();return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}catch(t){let n=new g(`Failed to list cron jobs.`,`LIST_CRONS_TOOL_FAILED`,{tool:e.TOOL_NAME},{cause:t});return console.error(`[${e.TOOL_NAME}] ${n.message}`,n.context),{content:[{type:`text`,text:JSON.stringify({code:n.code,context:n.context,message:n.message},null,2)}],isError:!0}}}},D=class extends Error{code=`INVALID_WORKFLOW_RUN_RECORD`;constructor(e,t,n){super(`Invalid workflow run record at "${e}": ${t}`,n),this.recordPath=e,this.name=`InvalidWorkflowRunRecordError`}},O=class extends Error{code=`WORKFLOW_RUN_CONFLICT`;constructor(e,t){super(`Workflow "${t}" is already running in workspace "${e}"`),this.workspace=e,this.runKey=t,this.name=`WorkflowRunConflictError`}};const oe=n.z.record(n.z.string(),n.z.coerce.string()),se=n.z.object({description:n.z.string().optional(),required:n.z.boolean().optional(),default:n.z.string().optional(),type:n.z.string().optional(),options:n.z.array(n.z.string()).optional()}),ce=n.z.record(n.z.string(),n.z.string()),le=n.z.record(n.z.string(),n.z.string()),ue=n.z.union([n.z.string(),le]),de=n.z.object({"fail-fast":n.z.boolean().optional(),matrix:n.z.looseObject({include:n.z.array(ce).optional()}).optional()}),k=n.z.object({name:n.z.string().optional(),uses:n.z.string().optional(),run:ue.optional(),interactiveRun:ue.optional(),"timeout-minutes":n.z.number().optional(),env:oe.optional(),with:n.z.record(n.z.string(),n.z.string()).optional(),"working-directory":n.z.string().optional(),if:n.z.string().optional(),"continue-on-error":n.z.boolean().optional(),"timeout-retries":n.z.number().optional(),id:n.z.string().optional()}),fe=n.z.object({name:n.z.string(),run:n.z.string(),env:oe.optional(),"working-directory":n.z.string().optional(),"ready-check":n.z.union([n.z.string(),n.z.boolean()]).optional(),"ready-timeout":n.z.number().optional(),host:n.z.string().optional(),port:n.z.number().int().min(1).max(65535).optional(),"port-range":n.z.object({min:n.z.number().int().min(1).max(65535),max:n.z.number().int().min(1).max(65535)}).optional(),"service-type":n.z.enum([`tool`,`service`]).optional()}),pe=n.z.object({services:n.z.array(fe).optional(),steps:n.z.array(k).optional()}),me=n.z.object({steps:n.z.array(k).optional()}),he=n.z.object({"runs-on":n.z.string().optional(),needs:n.z.union([n.z.string(),n.z.array(n.z.string())]).optional(),extends:n.z.union([n.z.string(),n.z.array(n.z.string())]).optional(),description:n.z.string().optional(),strategy:de.optional(),steps:n.z.array(k),preJob:me.optional(),postJob:me.optional(),env:oe.optional(),if:n.z.string().optional(),"system-prompt":n.z.string().optional(),context:n.z.string().optional()}),ge=n.z.object({steps:n.z.array(k)}),_e=n.z.object({steps:n.z.array(k)}),ve=n.z.object({beforeCreate:_e.optional(),afterCreate:_e.optional(),beforeCompleted:_e.optional(),afterCompleted:_e.optional()}),ye=n.z.object({STOP:n.z.string().optional()}),be=n.z.object({name:n.z.string().optional(),workspace:n.z.string().optional(),imports:n.z.array(n.z.string()).optional(),"system-prompt":n.z.string().optional(),"max-workflows":n.z.number().int().positive().optional(),"launch-command":n.z.string().optional(),keybindings:ye.optional(),on:n.z.looseObject({workflow_dispatch:n.z.object({inputs:n.z.record(n.z.string(),se).optional()}).nullable().optional(),agent_decision:ge.optional()}).optional(),env:oe.optional(),pre:pe.optional(),post:pe.optional(),worktree:ve.optional(),jobs:n.z.record(n.z.string(),he)}),xe=n.z.enum([`running`,`completed`,`error`]),Se=n.z.enum([`success`,`skipped`,`failed`,`interrupted`]),Ce=n.z.object({displayName:n.z.string(),dryRun:n.z.boolean(),errorMessage:n.z.string().optional(),exitCode:n.z.number().optional(),finishedAt:n.z.string().optional(),outcome:Se.optional(),pid:n.z.number().int().positive().optional(),runKey:n.z.string(),stale:n.z.boolean().optional(),staleReason:n.z.string().optional(),stage:xe,startedAt:n.z.string(),workflowPath:n.z.string(),workspace:n.z.string()});n.z.object({changelogPath:n.z.string(),contextPath:n.z.string(),displayName:n.z.string(),recordPath:n.z.string(),runDir:n.z.string(),runKey:n.z.string(),stopRequestPath:n.z.string(),workspace:n.z.string()});const we=`default`,A=`running`,Te=`completed`,j=`error`,Ee=`workspaces`,M=`run.json`,De=`stop-request.json`,Oe=`workflow-run`,ke=`Workflow process is no longer running`;var Ae=class{constructor(e=(0,s.resolve)((0,o.homedir)(),`.workflow-mcp`)){this.homeDir=e}resolveWorkspace(e,t){return this.slugifySegment(e||t||we,we)}async createRun(e){let t=this.resolveWorkspace(e.workspace,e.workflowWorkspace),n=this.slugifySegment(e.displayName,Oe);await this.ensureWorkspaceStructure(t);let r=await this.findReusableRunStage(t,n);if(r===A)throw new O(t,n);let i=this.getRunDirectory(t,A,n);r?(await(0,a.rm)(i,{recursive:!0,force:!0}),await(0,a.rename)(this.getRunDirectory(t,r,n),i),await this.removeFileIfExists((0,s.resolve)(i,`fix.md`)),await this.removeFileIfExists((0,s.resolve)(i,De))):await(0,a.mkdir)(i,{recursive:!0});let o={displayName:e.displayName,dryRun:e.dryRun,runKey:n,stage:A,startedAt:new Date().toISOString(),pid:e.pid??process.pid,workflowPath:e.workflowPath,workspace:t},c=(0,s.resolve)(i,M);return await this.writeRunRecord(c,o),{changelogPath:(0,s.resolve)(i,`changelog.md`),contextPath:(0,s.resolve)(i,`context.md`),displayName:e.displayName,recordPath:c,runDir:i,runKey:n,stopRequestPath:(0,s.resolve)(i,De),workspace:t}}async finalizeRun(e,t){await this.ensureWorkspaceStructure(e.workspace);let n=this.getRunDirectory(e.workspace,t.stage,e.runKey),r=await this.readRunRecord(e.recordPath),i={...r,errorMessage:t.errorMessage,exitCode:t.exitCode,finishedAt:new Date().toISOString(),outcome:t.outcome,pid:r.pid,stage:t.stage};e.runDir!==n&&(await(0,a.rm)(n,{recursive:!0,force:!0}),await(0,a.rename)(e.runDir,n));let o=(0,s.resolve)(n,M);return await this.writeRunRecord(o,i),{...e,recordPath:o,runDir:n,stopRequestPath:(0,s.resolve)(n,De)}}async requestStop(e,t,n){let r=this.resolveWorkspace(e),i=this.slugifySegment(t,Oe),o=this.getRunDirectory(r,A,i),c=(0,s.resolve)(o,M);if(!await this.pathExists(c))throw Error(`Running workflow not found: ${r}/${t}`);let l=await this.inspectRunningRecord(r,i);if(l.stale)throw Error(l.staleReason??`Running workflow is stale: ${r}/${t}`);let u={reason:n?.trim()?n.trim():void 0,requestedAt:new Date().toISOString()};return await(0,a.writeFile)((0,s.resolve)(o,De),`${JSON.stringify(u,null,2)}\n`,`utf-8`),u}async hasStopRequest(e){return await this.pathExists(e.stopRequestPath)}async readRunRecord(e){try{return this.validateRunRecord(JSON.parse(await(0,a.readFile)(e,`utf-8`)),e)}catch(t){throw t instanceof D?t:new D(e,t instanceof Error?t.message:`Unknown parse failure`,{cause:t})}}async listRuns(e){let t=e?[this.resolveWorkspace(e)]:await this.listWorkspaceNames();return(await Promise.all(t.map(async e=>this.listWorkspaceRuns(e)))).flat().sort((e,t)=>this.compareRunRecordsByLatest(e,t))}async listRunsPage(e={}){let t=e.page??1,n=e.pageSize??20,r=await this.listRuns(e.workspace),i=r.length,a=Math.ceil(i/n),o=(t-1)*n,s=r.slice(o,o+n);return{hasNextPage:t<a,hasPreviousPage:t>1&&i>0,items:s,page:t,pageSize:n,total:i,totalPages:a}}async countRunningWorkflows(e){let t=this.getRunStageDirectory(e,A);if(!await this.pathExists(t))return 0;let n=await(0,a.readdir)(t,{withFileTypes:!0}),r=0;for(let e of n){if(!e.isDirectory())continue;let n=(0,s.resolve)(t,e.name,M);if(await this.pathExists(n))try{let e=await this.readRunRecord(n);e.pid&&this.isProcessAlive(e.pid)&&r++}catch{}}return r}async ensureWorkspaceStructure(e){await(0,a.mkdir)(this.getRunStageDirectory(e,A),{recursive:!0}),await(0,a.mkdir)(this.getRunStageDirectory(e,Te),{recursive:!0}),await(0,a.mkdir)(this.getRunStageDirectory(e,j),{recursive:!0})}async findRunStage(e,t){for(let n of[A,Te,j])if(await this.pathExists(this.getRunDirectory(e,n,t)))return n;return null}async listWorkspaceRuns(e){let t=new Map;for(let n of[A,Te,j]){let r=this.getRunStageDirectory(e,n);if(!await this.pathExists(r))continue;let i=await(0,a.readdir)(r,{withFileTypes:!0});for(let a of i){if(!a.isDirectory())continue;let i=(0,s.resolve)(r,a.name,M);if(!await this.pathExists(i))continue;let o=await this.readListableRunRecord(e,n,a.name,i);o&&t.set(o.runKey,o)}}return[...t.values()]}async findReusableRunStage(e,t){let n=await this.findRunStage(e,t);return n===A?(await this.reconcileStaleRunningRecord(e,t),this.findRunStage(e,t)):n}async inspectRunningRecord(e,t){let n=(0,s.resolve)(this.getRunDirectory(e,A,t),M),r=await this.readRunRecord(n);return!r.pid||this.isProcessAlive(r.pid)?r:{...r,stale:!0,staleReason:`${ke}: pid ${r.pid}`}}async readListableRunRecord(e,t,n,r){try{return t===A?await this.inspectRunningRecord(e,n):await this.readRunRecord(r)}catch(e){if(e instanceof D)return null;throw e}}async reconcileStaleRunningRecord(e,t){let n=this.getRunDirectory(e,A,t),r=(0,s.resolve)(n,M),i=await this.readRunRecord(r);if(!i.pid||this.isProcessAlive(i.pid))return i;let o=this.getRunDirectory(e,j,t),c={...i,errorMessage:`${ke}: pid ${i.pid}`,exitCode:130,finishedAt:new Date().toISOString(),outcome:`interrupted`,stage:j};return await(0,a.rm)(o,{recursive:!0,force:!0}),await(0,a.rename)(n,o),await this.writeRunRecord((0,s.resolve)(o,M),c),c}async listWorkspaceNames(){let e=(0,s.resolve)(this.homeDir,Ee);return await this.pathExists(e)?(await(0,a.readdir)(e,{withFileTypes:!0})).filter(e=>e.isDirectory()).map(e=>e.name).sort((e,t)=>e.localeCompare(t)):[]}compareRunRecordsByLatest(e,t){let n=e.finishedAt??e.startedAt,r=(t.finishedAt??t.startedAt).localeCompare(n);if(r!==0)return r;let i=e.workspace.localeCompare(t.workspace);return i===0?e.runKey.localeCompare(t.runKey):i}async writeRunRecord(e,t){await(0,a.writeFile)(e,`${JSON.stringify(t,null,2)}\n`,`utf-8`)}validateRunRecord(e,t){let n=Ce.safeParse(e);if(!n.success)throw new D(t,n.error.message);return n.data}getRunStageDirectory(e,t){return(0,s.resolve)(this.homeDir,Ee,e,t)}getRunDirectory(e,t,n){return(0,s.resolve)(this.getRunStageDirectory(e,t),n)}async pathExists(e){try{return await(0,a.access)(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async removeFileIfExists(e){try{await(0,a.unlink)(e)}catch(e){if(e.code!==`ENOENT`)throw e}}slugifySegment(e,t){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)||t}isProcessAlive(e){try{return process.kill(e,0),!0}catch(e){let t=e.code;if(t===`ESRCH`)return!1;if(t===`EPERM`)return!0;throw e}}};const je=n.z.object({page:n.z.number().int().min(1).optional().describe(`Page number to return. Defaults to 1.`),pageSize:n.z.number().int().min(1).max(100).optional().describe(`Number of workflow runs per page. Defaults to 20 and is capped at 100.`),workspace:n.z.string().optional().describe(`Optional workspace filter. When omitted, runs from all workspaces are returned.`)});var Me=class e{static TOOL_NAME=`list_workflow_statuses`;constructor(e=new Ae){this.registry=e}getInputSchema(){return je}getDefinition(){return{name:e.TOOL_NAME,description:`List tracked workflow runs from the local workflow registry, including their workspace, stage, outcome, and timestamps.`,inputSchema:n.z.toJSONSchema(je)}}async execute(e={}){try{let t=je.parse(e),n=await this.registry.listRunsPage({page:t.page??1,pageSize:t.pageSize??20,workspace:t.workspace});return{content:[{type:`text`,text:JSON.stringify(n,null,2)}]}}catch(t){let n=new g(`Failed to list workflow statuses.`,`LIST_WORKFLOW_STATUSES_TOOL_FAILED`,{workspace:e.workspace??`all`},{cause:t});return{content:[{type:`text`,text:JSON.stringify({code:n.code,context:n.context,message:n.message},null,2)}],isError:!0}}}},Ne=class extends Error{code=`WORKFLOW_CAPACITY_EXCEEDED`;constructor(e,t,n){super(`Workspace "${e}" is at capacity: ${t}/${n} workflows running.\n → Check running workflows: list-workflow-statuses --workspace ${e}\n → Wait for a running workflow to complete, or cancel one before dispatching again.`),this.workspace=e,this.running=t,this.max=n,this.name=`WorkflowCapacityError`}},N=class extends Error{code=`WORKFLOW_INTERRUPTED`;context;constructor(e,t={}){let n=t.context?` during ${t.context.phase}`:``;super(`Workflow interrupted by ${e}${n}`,{cause:t.cause??t.context}),this.signal=e,this.name=`WorkflowInterruptedError`,this.context=t.context}};const P=`\x1B[0m`,Pe=`\x1B[1m`,Fe=`\x1B[2m`,Ie=`\x1B[31m`,Le=`\x1B[34m`,Re=[`pnpm-workspace.yaml`,`nx.json`,`.git`];function ze(e){let t=(0,s.resolve)(e);for(;;){for(let e of Re)if((0,c.existsSync)((0,s.join)(t,e)))return t;let n=(0,s.dirname)(t);if(n===t)return e;t=n}}var Be=class{runningServices=[];processRegistry=new u.ProcessRegistryService(process.env.PROCESS_REGISTRY_PATH);portRegistry=new l.PortRegistryService(process.env.PORT_REGISTRY_PATH);constructor(e){this.logger=e}resolveWorkingDirectory(e,t){return e[`working-directory`]?(0,s.resolve)(t,e[`working-directory`]):t}getRunningServices(){return this.runningServices}async startService(e,t,n,i){let a=e.run;if(i)return this.logger.info(` ${Le}dry ${P} ${e.name}`),this.logger.info(` ${Fe}$ ${a}${P}`),null;this.logger.info(` ${Le}start${P} ${e.name}`),this.logger.info(` ${Fe}$ ${a}${P}`);let o={...process.env,...t};if(e.env)for(let[t,n]of Object.entries(e.env))o[t]=String(n);let s=this.resolveWorkingDirectory(e,n),c=ze(s),l=o.NODE_ENV??process.env.NODE_ENV??`development`,u=e.host??`127.0.0.1`,d;if(e.port!==void 0||e[`port-range`]){let t=await this.portRegistry.reservePort({repositoryPath:c,serviceName:e.name,serviceType:e[`service-type`]??`tool`,environment:l,preferredPort:e.port,portRange:e[`port-range`],host:u,force:!0});if(!t.success||t.port===void 0)throw Error(t.error??`Failed to reserve port for background service ${e.name}`);d=t.port,o.PORT??=String(d),o.SERVICE_PORT??=String(d),o.HOST??=u,o.SERVICE_HOST??=u}let f=(0,r.spawn)(a,[],{stdio:[`ignore`,`pipe`,`pipe`],cwd:s,env:{...o,FORCE_COLOR:`1`},shell:`/bin/zsh`,detached:!0});if(f.pid===void 0)throw d!==void 0&&await this.portRegistry.releasePort({repositoryPath:c,serviceName:e.name,serviceType:e[`service-type`]??`tool`,environment:l,force:!0}),Error(`Failed to spawn background service ${e.name}`);let p=`${Le}[${e.name}]${P}`;f.stdout?.on(`data`,e=>{for(let t of e.toString().split(`
|
|
5
|
-
`))t.trim()&&process.stdout.write(`${p} ${t}\n`)}),f.stderr?.on(`data`,e=>{for(let t of e.toString().split(`
|
|
6
|
-
`))t.trim()&&process.stderr.write(`${p} ${t}\n`)}),f.on(`error`,e=>{this.logger.error(`${p} Process error: ${e.message}`)});let m=async()=>{d!==void 0&&await this.portRegistry.releasePort({repositoryPath:c,serviceName:e.name,serviceType:e[`service-type`]??`tool`,environment:l,force:!0})};if(f.pid!==void 0){let t=await this.processRegistry.registerProcess({repositoryPath:c,serviceName:e.name,serviceType:e[`service-type`]??`tool`,environment:l,pid:f.pid,port:d,host:d===void 0?void 0:u,command:a,args:[],metadata:{workingDirectory:s,readyCheck:e[`ready-check`]},force:!0});if(!t.success){try{process.kill(-f.pid,`SIGTERM`)}catch{f.kill(`SIGTERM`)}throw d!==void 0&&await this.portRegistry.releasePort({repositoryPath:c,serviceName:e.name,serviceType:e[`service-type`]??`tool`,environment:l,force:!0}),Error(t.error??`Failed to register process for background service ${e.name}`)}m=async()=>{let t=await this.processRegistry.releaseProcess({repositoryPath:c,serviceName:e.name,serviceType:e[`service-type`]??`tool`,environment:l,pid:f.pid,kill:!0,releasePort:!0,force:!0});if(!t.success&&!t.error?.includes(`No matching process entry`))throw Error(t.error??`Failed to release ${e.name}`)}}let h={name:e.name,process:f,env:o,release:m};return this.runningServices.push(h),h}async waitForServiceReady(e,t,n,i){if(!e[`ready-check`]||typeof e[`ready-check`]!=`string`)return!0;let a=(e[`ready-timeout`]||30)*1e3,o=Date.now(),s=e[`ready-check`],c=this.resolveWorkingDirectory(e,t),l=this.runningServices.find(t=>t.name===e.name)?.env??{...process.env,...n};for(this.logger.info(` ${Fe}wait${P} Waiting for ${e.name} to be ready...`);Date.now()-o<a;){if(i?.())return!1;try{return(0,r.execSync)(s,{stdio:`ignore`,cwd:c,env:l,shell:`/bin/zsh`,timeout:5e3}),this.logger.info(` [32mready${P} ${e.name}`),!0}catch{if(i?.())return!1}await new Promise(e=>{setTimeout(e,1e3)})}return i?.()||this.logger.error(` ${Ie}timeout${P} ${e.name} not ready after ${e[`ready-timeout`]||30}s`),!1}async stopAll(){if(this.runningServices.length!==0){this.logger.info(`\n ${Le}${Pe}pre${P} ${Pe}Stopping services${P}`),this.logger.info(` ${`─`.repeat(50)}`);for(let e of this.runningServices){if(!e.process.killed&&e.process.pid&&this.logger.info(` ${Fe}stop${P} ${e.name} (pid ${e.process.pid})`),e.release)try{await e.release();continue}catch(t){this.logger.warn(` ${Ie}warn${P} Failed registry cleanup for ${e.name}: ${t instanceof Error?t.message:String(t)}`)}if(!e.process.killed&&e.process.pid)try{process.kill(-e.process.pid,`SIGTERM`)}catch{e.process.kill(`SIGTERM`)}}this.runningServices=[]}}};const F=`\x1B[0m`,Ve=`\x1B[1m`,I=`\x1B[2m`,He=`\x1B[33m`,Ue=`WORKFLOW_JOB_ID`,We=`WORKFLOW_JOB_NAME`,Ge=`PROCESS_REGISTRY_TAG`;var Ke=class{constructor(e,t,n){this.parser=e,this.stepRunner=t,this.logger=n}async runJob(e,t,n,r){let i=this.parser.expandMatrix(t),a=r.maxRetries;for(let o of i){let i=(0,d.randomUUID)(),l=Object.keys(o).length>0?` ${I}(${Object.entries(o).map(([e,t])=>`${e}=${t}`).join(`, `)})${F}`:``;this.logger.info(`\n [35m${Ve}job${F} ${Ve}${e}${F}${l}`),this.logger.info(` ${`─`.repeat(50)}`);let u={...n.workflowEnv,[Ue]:i,[We]:e,[Ge]:i};if(t.env)for(let[e,r]of Object.entries(t.env))u[e]=this.parser.interpolate(String(r),{inputs:n.inputs,matrix:o,secrets:n.secrets,env:u});u[Ue]=i,u[We]=e,u[Ge]=i,this.logger.info(` ${I}jobid${F} ${i}`);let f=[];if(u.WORKFLOW_RUN_DIR){let t=n.jobOrder.indexOf(e),r=n.jobOrder.slice(0,t+1).map(e=>{let t=n.allJobs[e]?.description;return t?` - ${e}: ${t}`:` - ${e}`}).join(`
|
|
7
|
-
`);f.push(`You are currently running job "${e}" in the following workflow:\n${r}\n\nWhen you have completed your task, you MUST either:\n1. If you find bugs, missing features, or issues that need fixes from a previous job, write to ${u.WORKFLOW_RUN_DIR}/fix.md with a YAML frontmatter restart-from field specifying which job should handle the fix, followed by a detailed description. Example:\n---\nrestart-from: development\n---\nDescription of what needs to be fixed...\n\nThe workflow runner will restart from the specified job. Only create fix.md for issues that require code changes — fix minor issues yourself.\n2. Otherwise, stop. Do not continue with unrelated work.`)}if(n.workflowSystemPrompt&&f.push(this.parser.interpolate(n.workflowSystemPrompt,{inputs:n.inputs,matrix:o,secrets:n.secrets,env:u})),t[`system-prompt`]&&f.push(this.parser.interpolate(t[`system-prompt`],{inputs:n.inputs,matrix:o,secrets:n.secrets,env:u})),f.length>0){let e=f.join(`
|
|
8
|
-
|
|
9
|
-
`);u.JOB_SYSTEM_PROMPT=e,this.logger.info(` ${I}prompt${F} ${e.split(`
|
|
10
|
-
`)[0].slice(0,80)}${e.includes(`
|
|
11
|
-
`)?`...`:``}`)}let p=t.context?this.parser.interpolate(t.context,{inputs:n.inputs,matrix:o,secrets:n.secrets,env:u}):u.CONTEXT_FILE;if(p){let e=(0,s.resolve)(r.workflowDir,p);(0,c.existsSync)(e)?(u.WORKFLOW_CONTEXT=e,u.WORKFLOW_CONTEXT_FILE=e,this.logger.info(` ${I}ctx ${F} ${p}`)):r.dryRun||this.logger.warn(` ${He}warn${F} context file not found: ${p}`)}if(u.CHANGELOG_FILE){let e=(0,s.resolve)(r.workflowDir,u.CHANGELOG_FILE),t=(0,s.dirname)(e);(0,c.existsSync)(t)||(0,c.mkdirSync)(t,{recursive:!0}),(0,c.existsSync)(e)||(0,c.writeFileSync)(e,`# Changelog
|
|
12
|
-
`,`utf-8`),u.WORKFLOW_CHANGELOG=e,this.logger.info(` ${I}log ${F} changelog at ${u.CHANGELOG_FILE}`)}let m={inputs:n.inputs,matrix:o,secrets:n.secrets,env:u},h=!1,g=t.preJob?.steps??[],_=t.steps??[],v=t.postJob?.steps??[];for(let t=1;t<=a;t++){t>1&&(this.logger.info(`\n ${He}retry${F} ${Ve}${e}${F}${l} (attempt ${t}/${a})`),this.logger.info(` ${`─`.repeat(50)}`));let n=!0;if(g.length>0&&(n=await this.runStepSequence(g,m,r)),n&&=await this.runStepSequence(_,m,r),v.length>0){let e=await this.runStepSequence(v,m,r);n&&=e}if(n){h=!0;break}t<a&&this.logger.warn(` ${He}Job "${e}" failed, retrying...${F}`)}if(h)this.logger.info(` [32mJob "${e}" completed${F}${l}`);else if(this.logger.error(`\n [31mJob "${e}" failed after ${a} attempts${F}`),t.strategy?.[`fail-fast`]!==!1)return!1}return!0}async runStepSequence(e,t,n){for(let r of e)if(!await this.stepRunner.runStep(r,t,n))return!1;return!0}},qe=class extends Error{code=`WORKFLOW_STEP_SPAWN_FAILED`;constructor(e,t={}){super(`Failed to start workflow step "${e.stepName}"`,{cause:t.cause??e}),this.context=e,this.name=`WorkflowStepSpawnError`}},Je=class extends Error{code=`WORKFLOW_STEP_TIMEOUT_CONFIG_INVALID`;constructor(e,t={}){super(`Invalid ${e.configKey} for workflow step "${e.stepName}"`,{cause:t.cause??e}),this.context=e,this.name=`WorkflowStepTimeoutConfigError`}};const Ye=`/backend-api`;var Xe=class{codexHome;fetchFn;now;readTextFile;constructor(e={}){this.codexHome=e.codexHome??(0,s.join)((0,o.homedir)(),`.codex`),this.fetchFn=e.fetchFn??fetch,this.now=e.now??(()=>Date.now()),this.readTextFile=e.readTextFile??(e=>(0,a.readFile)(e,`utf8`))}isCodexCommand(e,t){let n=e.trim();return n===`codex`||n.startsWith(`codex `)}async getQuotaStatus(){let e=await this.readAuthFile(),t=e?.tokens?.access_token?.trim(),n=e?.tokens?.account_id?.trim();if(!t||!n)return null;let r=await this.readChatgptBaseUrl(),i=await this.fetchFn(this.buildUsageUrl(r),{headers:{Authorization:`Bearer ${t}`,"ChatGPT-Account-Id":n,"User-Agent":`codex-cli`}});if(!i.ok)throw Error(`codex quota request failed with HTTP ${i.status}`);let a=await i.json();return{blockingLimit:this.findBlockingLimit(a),planType:a.plan_type??null}}async readAuthFile(){let e=await this.readOptionalTextFile((0,s.join)(this.codexHome,`auth.json`));return e?JSON.parse(e):null}async readChatgptBaseUrl(){let e=(await this.readOptionalTextFile((0,s.join)(this.codexHome,`config.toml`)))?.match(/^\s*chatgpt_base_url\s*=\s*"([^"]+)"/m);return this.normalizeBaseUrl(e?.[1]??`https://chatgpt.com/backend-api/`)}buildUsageUrl(e){return e.includes(Ye)?`${e}/wham/usage`:`${e}/api/codex/usage`}normalizeBaseUrl(e){let t=e.trim().replace(/\/+$/,``);return(t.startsWith(`https://chatgpt.com`)||t.startsWith(`https://chat.openai.com`))&&!t.includes(Ye)&&(t=`${t}${Ye}`),t}async readOptionalTextFile(e){try{return await this.readTextFile(e)}catch(e){if(e.code===`ENOENT`)return null;throw e}}findBlockingLimit(e){let t=[];this.collectBlockingLimit(t,`codex`,`codex`,e.rate_limit);for(let n of e.additional_rate_limits??[])this.collectBlockingLimit(t,n.metered_feature??n.limit_name??`codex`,n.limit_name??n.metered_feature??`codex`,n.rate_limit);return t.sort((e,t)=>e.resetAt-t.resetAt||t.usedPercent-e.usedPercent),t[0]??null}collectBlockingLimit(e,t,n,r){if(!r)return;let i=[{payload:r.primary_window,window:`primary`},{payload:r.secondary_window,window:`secondary`}];for(let{payload:a,window:o}of i){let i=a?.reset_at,s=a?.used_percent??0;typeof i==`number`&&(s>=100||r.limit_reached===!0&&i*1e3>this.now()||r.allowed===!1&&i*1e3>this.now())&&e.push({limitId:t,limitName:n,resetAfterSeconds:a?.reset_after_seconds??null,resetAt:i,usedPercent:s,window:o,windowSeconds:a?.limit_window_seconds??null})}}};const L=`\x1B[0m`,R=`\x1B[2m`,Ze=`\x1B[36m`,Qe=`\x1B[32m`,z=`\x1B[33m`,B=`\x1B[31m`,$e=`SIGINT`,V=`SIGTERM`,et=`unnamed`,tt=`/bin/zsh`,nt=`FORCE_COLOR`,H=`inherit`,rt=`pipe`,it=` `,at=`
|
|
13
|
-
${it}\$ `,ot=`skip`,U=`warn`,W=`error`,G=`fail`,K=`interrupted`,st=`already stopping`,ct=`failed to signal`,q=`(continue-on-error)`,lt=`ESRCH`,ut=process.platform!==`win32`,dt=`interactiveRun`,ft=`timeout-minutes`,pt=`timeout-retries`,mt=`retry`,J=`SIGKILL`,ht=1e3,gt=1e3,_t=6e4,vt=Math.floor(2147483647/_t),yt=`WORKFLOW_STEP_DISPLAY`,bt=`workflow-mcp`,xt={status:`status_completed`},St=new Set([`ENOENT`,`EBUSY`,`EAGAIN`,`EPERM`]),Ct=1e3,wt=`done`,Tt=`stop`,Et=1e3,Dt=`stop_requested`,Ot=n.z.number().positive().finite().max(vt),kt=n.z.number().int().min(0).max(10).default(2);var At=class{activeStep=null;activeQuotaWait=null;constructor(e,t,n=new Xe,r=c.watch){this.parser=e,this.logger=t,this.quotaService=n,this.watchStatusFile=r}stopActiveStep(e){if(this.activeQuotaWait){if(this.activeQuotaWait.controller.signal.aborted){this.logger.info(` ${R}${ot}${L} ${this.activeQuotaWait.stepName} ${st}`);return}this.activeQuotaWait.signal=e,this.activeQuotaWait.controller.abort(),this.logger.info(` ${z}${K}${L} cancelling quota wait for ${this.activeQuotaWait.stepName}`);return}if(!this.activeStep){this.logger.info(` ${R}${ot}${L} no active step to stop`);return}if(this.activeStep.process.killed){this.logger.info(` ${R}${ot}${L} ${this.activeStep.stepName} ${st}`);return}this.logger.info(` ${z}${K}${L} sending ${e} to ${this.activeStep.stepName}`),this.killActiveStep(e)||this.logger.warn(` ${z}${U}${L} ${ct} ${this.activeStep.stepName}`)}async runStep(e,t,n){let r=this.resolveRunner(n),i=this.resolveStepCommand(e,t,r),a=e.name?this.parser.interpolate(e.name,t):i?.command.slice(0,60)||e.uses||et;if(e.uses){let n=this.parser.interpolate(e.uses,t);return this.parser.isActionSkipped(n)?(this.logger.info(` ${R}${ot}${L} ${n}`),!0):(this.logger.warn(` ${z}${U}${L} Unsupported action: ${n} (skipped)`),!0)}if(!i)return!0;if(i.missingRunner)return this.logger.error(` ${B}${W}${L} runner "${i.missingRunner.runner}" not found for step "${a}" (available runner keys: ${i.missingRunner.availableKeys.join(`, `)})`),e[`continue-on-error`]||n.continueOnError?(this.logger.warn(` ${z}${G}${L} ${a} ${q}\n`),!0):(this.logger.error(` ${B}${G}${L} ${a}\n`),!1);let{command:o,interactive:l}=i,u=this.quotaService.isCodexCommand(o,i.agentKey),d=e[`continue-on-error`]||n.continueOnError,f;try{f=this.resolveTimeoutMs(e,a)}catch(e){if(!(e instanceof Je))throw e;return this.logger.error(` ${B}${W}${L} invalid ${e.context.configKey} for "${a}": ${String(e.context.timeoutValue)}`),d?(this.logger.warn(` ${z}${G}${L} ${a} ${q}\n`),!0):(this.logger.error(` ${B}${G}${L} ${a}\n`),!1)}let p={...process.env,...t.env};if(e.env)for(let[n,r]of Object.entries(e.env))p[n]=this.parser.interpolate(String(r),t);p.WORKFLOW_STEP_NAME=a,p[yt]=this.formatStepDisplay(p.WORKFLOW_JOB_NAME,a);let m;l&&(m=this.createStatusFile(),p.WORKFLOW_STATUS_FILE=m,this.logger.info(` ${R}status-file${L} ${m}`));let h=e[`working-directory`]?(0,s.resolve)(n.workflowDir,this.parser.interpolate(e[`working-directory`],t)):n.workflowDir;if(n.dryRun)return this.logger.info(` ${Ze}dry ${L} ${a}`),this.logger.info(`${it}${R}\$ ${o.split(`
|
|
14
|
-
`).join(at)}${L}`),!0;let g;try{g=this.resolveTimeoutRetries(e,a)}catch(e){if(!(e instanceof Je))throw e;return this.logger.error(` ${B}${W}${L} invalid ${e.context.configKey} for "${a}": ${String(e.context.timeoutValue)}`),d?(this.logger.warn(` ${z}${G}${L} ${a} ${q}\n`),!0):(this.logger.error(` ${B}${G}${L} ${a}\n`),!1)}let _=!1;for(let e=0;e<=g;e++){if(await this.waitForCodexQuotaAvailability(a,o,u),e>0?this.logger.warn(` ${z}${mt}${L} retrying step after timeout "${a}" (attempt ${e+1}/${g+1})`):this.logger.info(` ${Ze}run ${L} ${a}`),this.logger.info(`${it}${R}\$ ${o.split(`
|
|
15
|
-
`)[0]}${o.includes(`
|
|
16
|
-
`)?` ...`:``}${L}`),n.stopRequestPath&&(0,c.existsSync)(n.stopRequestPath))throw this.logger.info(`\n ${z}${K}${L} ${a} (${Tt})`),new N(V,{cause:Error(`Workflow stop requested before "${a}"`),context:this.createInterruptContext(a,o)});let t=l?this.withInteractiveTerminalTitle(o,p):o,r=this.executeCommand(t,h,p,a,l,f),i=l&&m?await this.raceInteractiveCompletion(r,m,a,n.stopRequestPath):n.stopRequestPath?await this.raceStopRequest(r,a,n.stopRequestPath):await r;if(i.status===`stop_requested`)throw this.logger.info(`\n ${z}${K}${L} ${a} (${Tt})`),new N(V,{cause:Error(`Workflow stop requested during "${a}"`),context:this.createInterruptContext(a,o)});if(i.status===`signaled`)throw this.logger.info(`\n ${z}${K}${L} ${a}`),new N(i.signal,{cause:Error(`Step process ended with ${i.signal}`),context:this.createInterruptContext(a,o)});if(i.status===`completed`&&(i.exitCode===130||i.exitCode===143)){let e=i.exitCode===130?$e:V;throw this.logger.info(`\n ${z}${K}${L} ${a}`),new N(e,{cause:Error(`Step process exited with ${i.exitCode}`),context:this.createInterruptContext(a,o)})}if(i.status===`spawn_error`)return this.logger.error(` ${B}${W}${L} unable to start step "${a}" in ${i.error.context.workDir} (${this.formatSpawnError(i.error)})`),d?(this.logger.warn(` ${z}${G}${L} ${a} ${q}\n`),!0):(this.logger.error(` ${B}${G}${L} ${a}\n`),!1);if(i.status===`timed_out`){if(this.logger.error(` ${B}${W}${L} step timed out after ${this.formatTimeoutMs(i.timeoutMs)} "${a}" (${o.split(`
|
|
17
|
-
`)[0]})`),e<g){if(m)try{(0,c.writeFileSync)(m,``,`utf-8`)}catch(e){this.logger.warn(` ${z}${U}${L} status-file reset failed for ${a}: ${e instanceof Error?e.message:String(e)}`)}continue}return m&&this.cleanupStatusFile(m),d?(this.logger.warn(` ${z}${G}${L} ${a} ${q}\n`),!0):(this.logger.error(` ${B}${G}${L} ${a}\n`),!1)}if(m&&this.cleanupStatusFile(m),i.status===`status_completed`)return this.logger.info(`\n ${Qe}${wt}${L} ${a} (status-file signaled completion)\n`),!0;if(i.status===`completed`&&i.exitCode===0)return this.logger.info(`\n ${Qe}pass${L} ${a}\n`),!0;if(i.status===`completed`&&this.logger.error(` ${B}${W}${L} step "${a}" exited with code ${i.exitCode} (${o.split(`
|
|
18
|
-
`)[0]})`),!_&&await this.shouldRetryForCodexQuota(a,u)){_=!0,this.logger.warn(` ${z}${mt}${L} codex quota reached after failed step, retrying after reset`),--e;continue}return d?(this.logger.warn(` ${z}${G}${L} ${a} ${q}\n`),!0):(this.logger.error(` ${B}${G}${L} ${a}\n`),!1)}return!1}async executeCommand(e,t,n,i,a,o){return a&&this.logger.info(` ${R}(interactive: output renders directly to terminal)${L}`),await new Promise(s=>{let c=a?this.captureTerminalState():null,l=a?(0,r.spawn)(e,[],{stdio:[H,H,H],cwd:t,detached:!1,env:{...n,[nt]:`1`},shell:tt}):(0,r.spawn)(e,[],{stdio:[H,rt,rt],cwd:t,detached:ut,env:{...n,[nt]:`1`},shell:tt});this.activeStep={command:e,interactive:a,lastSignaledProcessIds:[],process:l,processGroupId:ut&&!a&&typeof l.pid==`number`?l.pid:null,rootProcessId:typeof l.pid==`number`?l.pid:null,stepName:i};let u=null,d=!1,f=!1,p=async e=>{f||(f=!0,m&&clearTimeout(m),u&&clearTimeout(u),a&&(await this.cleanupInteractiveProcessTree(V),this.restoreTerminalState(c)),this.activeStep=null,s(e))},m=o===null?null:setTimeout(()=>{if(d=!0,this.killActiveStep(V)){u=setTimeout(()=>{f||(this.logger.warn(` ${z}${U}${L} ${i} forcing SIGKILL`),this.killActiveStep(J))},ht);return}p({status:`timed_out`,timeoutMs:o})},o);l.stdout?.on(`data`,e=>{for(let t of e.toString().split(`
|
|
19
|
-
`))t&&this.logger.info(t)}),l.stderr?.on(`data`,e=>{for(let t of e.toString().split(`
|
|
20
|
-
`))t&&this.logger.error(t)}),l.on(`error`,n=>{p({status:`spawn_error`,error:new qe({commandPreview:e.split(`
|
|
21
|
-
`)[0],source:`StepRunnerService.executeCommand`,stepName:i,workDir:t},{cause:n})})}),l.on(`exit`,(e,t)=>{if(a||this.cleanupProcessGroup(),d&&o!==null){p({status:`timed_out`,timeoutMs:o});return}if(t===$e){p({status:`signaled`,signal:$e});return}if(t===V){p({status:`signaled`,signal:V});return}p({status:`completed`,exitCode:e??1})})})}createInterruptContext(e,t){return{phase:`step_execution`,stepName:e,commandPreview:t.split(`
|
|
22
|
-
`)[0],source:`StepRunnerService.runStep`}}formatSpawnError(e){let t=e.cause;return t instanceof Error?`${`code`in t&&typeof t.code==`string`?t.code:`unknown-spawn-error`}${`path`in t&&typeof t.path==`string`?` at ${t.path}`:``}; verify command, shell, and permissions`:`check shell availability, PATH, and permissions`}resolveStepCommand(e,t,n){let r=e[dt]!=null,i=r?{command:e[dt],interactive:!0}:{command:e.run,interactive:!1},a=r?{command:e.run,interactive:!1}:{command:e[dt],interactive:!0},o=this.resolveExactAgentCommand(i.command,t,n);if(o)return{...o,interactive:i.interactive};let s=this.resolveExactAgentCommand(a.command,t,n);if(s)return{...s,interactive:a.interactive};let c=this.resolveMissingExplicitRunner(e,n);if(c)return{command:``,interactive:!1,missingRunner:c};let l=this.resolveStringCommand(i.command,t);if(l)return{command:l,interactive:i.interactive};let u=this.resolveStringCommand(a.command,t);if(u)return{command:u,interactive:a.interactive};let d=this.resolveFirstMappedCommand(i.command,t);if(d)return{command:d,interactive:i.interactive};let f=this.resolveFirstMappedCommand(a.command,t);return f?{command:f,interactive:a.interactive}:null}resolveExactAgentCommand(e,t,n){if(!n||!e||typeof e==`string`)return null;let r=e[n];return r?{agentKey:n,command:this.parser.interpolate(r,t),interactive:!1}:null}resolveStringCommand(e,t){return!e||typeof e!=`string`?null:this.parser.interpolate(e,t)}resolveFirstMappedCommand(e,t){if(!e||typeof e==`string`)return null;let[n]=Object.values(e);return n?this.parser.interpolate(n,t):null}resolveMissingExplicitRunner(e,t){if(!t)return null;let n=this.collectMappedRunnerKeys(e);return n.length===0||n.includes(t)?null:{availableKeys:n,runner:t}}collectMappedRunnerKeys(e){let t=new Set;for(let n of[e[dt],e.run])if(n&&typeof n!=`string`)for(let e of Object.keys(n))t.add(e);return[...t]}resolveRunner(e){return e.runner??e.cliAgent}formatStepDisplay(e,t){return e?`${e} > ${t}`:t}withInteractiveTerminalTitle(e,t){let n=`${bt}: ${t[yt]??e.split(`
|
|
23
|
-
`)[0]??et}`,r=`[ -t 1 ] && printf '\\033]0;%s\\007' ${this.escapeShellArg(n)}`,i=`[ -t 1 ] && printf '\\033]0;%s\\007' ${this.escapeShellArg(bt)}`;return`trap ${this.escapeShellArg(i)} EXIT
|
|
24
|
-
${r}
|
|
25
|
-
${e}`}escapeShellArg(e){return`'${e.replace(/'/g,`'\\''`)}'`}async shouldRetryForCodexQuota(e,t){return t?(await this.readCodexQuotaStatus(e))?.blockingLimit!=null:!1}async waitForCodexQuotaAvailability(e,t,n){if(n)for(;;){let n=await this.readCodexQuotaStatus(e),r=n?.blockingLimit;if(!r)return;let i=r.resetAt*1e3+Et,a=Math.max(i-Date.now(),Et),o=new Date(i).toLocaleString(),s=n?.planType?` (${n.planType})`:``;this.logger.warn(` ${z}wait ${L} codex quota ${r.limitName}/${r.window} is at ${r.usedPercent}%${s}; waiting until ${o}`),await this.waitForQuotaDelay(e,t,a)}}async readCodexQuotaStatus(e){try{return await this.quotaService.getQuotaStatus()}catch(t){return this.logger.warn(` ${z}${U}${L} unable to read codex quota for "${e}" (${this.formatQuotaError(t)})`),null}}async waitForQuotaDelay(e,t,n){let r=new AbortController;this.activeQuotaWait={controller:r,signal:null,stepName:e};try{let e=n;for(;e>0;){let t=Math.min(e,3e4);await this.waitForDelay(t,r.signal),e-=t}}catch(n){throw r.signal.aborted?new N(this.activeQuotaWait?.signal??V,{cause:Error(`Interrupted while waiting for Codex quota reset`),context:{...this.createInterruptContext(e,t),phase:`StepRunnerService.waitForCodexQuota`}}):n}finally{this.activeQuotaWait=null}}async waitForDelay(e,t){await new Promise((n,r)=>{let i=setTimeout(()=>{t.removeEventListener(`abort`,a),n()},e),a=()=>{clearTimeout(i),t.removeEventListener(`abort`,a),r(Error(`aborted`))};t.addEventListener(`abort`,a,{once:!0})})}formatQuotaError(e){return e instanceof Error&&e.message.trim().length>0?e.message:`unknown quota error`}resolveTimeoutMs(e,t){let n=e[ft];if(n===void 0)return null;try{let e=Ot.parse(n);return Math.ceil(e*_t)}catch(e){throw new Je({stepName:t,configKey:ft,timeoutValue:n},{cause:e})}}resolveTimeoutRetries(e,t){let n=e[pt];try{return kt.parse(n)}catch(e){throw new Je({stepName:t,configKey:pt,timeoutValue:n},{cause:e})}}formatTimeoutMs(e){return e%_t===0?`${e/_t} minute(s)`:`${e}ms`}cleanupProcessGroup(){if(!this.activeStep)return;let{processGroupId:e,stepName:t}=this.activeStep;if(e!==null)try{process.kill(-e,V)}catch(n){let r=n.code;r===lt?this.logger.info(` ${R}cleanup${L} process group ${e} already exited (ESRCH)`):this.logger.warn(` ${z}${U}${L} failed to clean up process group for ${t} (pgid=${e}, error=${r})`)}}async cleanupInteractiveProcessTree(e){if(!this.activeStep||!this.activeStep.interactive)return!1;let t=this.collectInteractiveProcessIds();if(t.length===0)return!1;this.activeStep.lastSignaledProcessIds=t;let n=this.signalProcessIds(t,e);if(await this.waitForProcessIdsToExit(t,gt),e!==J){let e=this.uniqueLiveProcessIds(t);e.length>0&&(this.signalProcessIds(e,J),await this.waitForProcessIdsToExit(e,gt))}return n}collectInteractiveProcessIds(){if(!this.activeStep?.interactive||this.activeStep.rootProcessId===null)return[];let e=this.activeStep.rootProcessId,t=[...this.snapshotProcessTree(e).map(e=>e.pid),...this.activeStep.lastSignaledProcessIds,e];return this.uniqueLiveProcessIds(t)}snapshotProcessTree(e){let t;try{t=(0,r.execFileSync)(`ps`,[`-axo`,`pid=,ppid=`],{encoding:`utf-8`,stdio:[`ignore`,rt,`ignore`]})}catch(t){return this.logger.warn(` ${z}${U}${L} unable to inspect process tree for ${e} (${t instanceof Error?t.message:String(t)})`),this.isProcessAlive(e)?[{depth:0,pid:e}]:[]}let n=new Map;for(let e of t.split(`
|
|
26
|
-
`)){let t=e.trim();if(!t)continue;let[r,i]=t.split(/\s+/),a=Number(r),o=Number(i);if(!Number.isInteger(a)||!Number.isInteger(o))continue;let s=n.get(o)??[];s.push(a),n.set(o,s)}let i=[],a=new Set,o=(e,t)=>{if(!a.has(e)){a.add(e),e!==process.pid&&i.push({depth:t,pid:e});for(let r of n.get(e)??[])o(r,t+1)}};return o(e,0),i.sort((e,t)=>t.depth-e.depth)}signalProcessIds(e,t){let n=!1;for(let r of e)if(r!==process.pid)try{process.kill(r,t),n=!0}catch(e){let t=e.code;t!==lt&&this.logger.warn(` ${z}${U}${L} ${ct} pid ${r} (${t??e.message})`)}return n}uniqueLiveProcessIds(e){let t=new Set,n=[];for(let r of e)!Number.isInteger(r)||r<=0||r===process.pid||t.has(r)||(t.add(r),this.isProcessAlive(r)&&n.push(r));return n}isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}async waitForProcessIdsToExit(e,t){let n=Date.now()+t;for(;Date.now()<n;){if(e.every(e=>!this.isProcessAlive(e)))return;await new Promise(e=>setTimeout(e,50))}}killActiveStep(e){if(!this.activeStep)return!1;if(this.activeStep.interactive){let t=this.collectInteractiveProcessIds();if(t.length>0)return this.activeStep.lastSignaledProcessIds=t,this.signalProcessIds(t,e)}let{process:t,processGroupId:n}=this.activeStep;if(n!==null)try{return process.kill(-n,e),!0}catch(e){e.code===lt?this.logger.info(` ${R}signal${L} process group for ${this.activeStep.stepName} already exited (ESRCH)`):this.logger.warn(` ${z}${U}${L} ${ct} process group for ${this.activeStep.stepName}`)}try{return t.kill(e)}catch(e){return this.logger.warn(` ${z}${U}${L} ${ct} ${this.activeStep.stepName} (${e.message})`),!1}}createStatusFile(){let e=(0,s.join)((0,o.tmpdir)(),`workflow-step-${(0,d.randomUUID)()}.status`);return(0,c.writeFileSync)(e,``,`utf-8`),e}async raceInteractiveCompletion(e,t,n,r){return new Promise(i=>{let a=!1,o=!1,s=!1,l=null,u=null,d=null,f=null,p=null,m=e=>{a||(a=!0,u&&=(u.close(),null),d&&=(d.close(),null),f&&=(clearInterval(f),null),p&&=(clearInterval(p),null),l&&=(clearTimeout(l),null),i(e))},h=!1,g=!1,_=()=>{try{return(0,c.existsSync)(t)&&(0,c.readFileSync)(t,`utf-8`).trim()===`YES`}catch(e){let t=e.code;return!t||!St.has(t)?this.logger.warn(` ${z}${U}${L} status-file read failed for ${n}: ${e instanceof Error?e.message:String(e)}`):this.logger.info(` ${R}status-file${L} transient FS error (${t}) polling ${n}`),!1}},v=()=>{if(!(o||!_())){if(o=!0,h=this.killActiveStep(V),!h){this.logger.warn(` ${z}${U}${L} ${n} status-file: SIGTERM could not be delivered, process may have already exited`);return}l=setTimeout(()=>{a||(g=!0,this.logger.warn(` ${z}${U}${L} ${n} did not exit after status-file SIGTERM, forcing SIGKILL`),this.killActiveStep(J))},ht)}},y=()=>!!(r&&(0,c.existsSync)(r)),b=()=>{if(!(s||!y())){if(s=!0,h=this.killActiveStep(V),!h){this.logger.warn(` ${z}${U}${L} ${n} stop request: SIGTERM could not be delivered, process may have already exited`);return}l=setTimeout(()=>{a||(g=!0,this.logger.warn(` ${z}${U}${L} ${n} did not exit after stop-request SIGTERM, forcing SIGKILL`),this.killActiveStep(J))},ht)}};try{u=this.watchStatusFile(t,()=>v())}catch(e){this.logger.warn(` ${z}${U}${L} status-file watcher setup failed for ${n}: ${e instanceof Error?e.message:String(e)}`)}if(f=setInterval(v,1e3),r){try{d=this.watchStatusFile(r,()=>b())}catch(e){e.code!==`ENOENT`&&this.logger.warn(` ${z}${U}${L} stop-request watcher setup failed for ${n}: ${e instanceof Error?e.message:String(e)}`)}p=setInterval(b,Ct)}v(),b(),e.then(e=>{if(s){g&&this.logger.warn(` ${z}${U}${L} ${n} required SIGKILL escalation after stop request`),m({status:Dt});return}if(!(o||_())){m(e);return}switch(o||(o=!0,this.logger.info(` ${Qe}${wt}${L} ${n} status-file observed during process exit handling`)),e.status){case`spawn_error`:case`timed_out`:m(e);return;case`signaled`:g&&this.logger.warn(` ${z}${U}${L} ${n} required SIGKILL escalation (work completed via status-file)`),m(xt);return;case`completed`:e.exitCode===0||e.exitCode>128||g||!h?(g&&this.logger.warn(` ${z}${U}${L} ${n} required SIGKILL escalation (work completed via status-file, exit code ${e.exitCode})`),m(xt)):m(e);return;case`status_completed`:m(e);return;case Dt:m(e);return;default:m(e)}})})}async raceStopRequest(e,t,n){return new Promise(r=>{let i=!1,a=!1,o=null,s=null,l=null,u=e=>{i||(i=!0,l&&=(l.close(),null),s&&=(clearInterval(s),null),o&&=(clearTimeout(o),null),r(e))},d=()=>{if(!(a||!(0,c.existsSync)(n))){if(a=!0,!this.killActiveStep(V)){this.logger.warn(` ${z}${U}${L} ${t} stop request: SIGTERM could not be delivered, process may have already exited`);return}o=setTimeout(()=>{i||(this.logger.warn(` ${z}${U}${L} ${t} did not exit after stop-request SIGTERM, forcing SIGKILL`),this.killActiveStep(J))},ht)}};try{l=this.watchStatusFile(n,()=>d())}catch(e){e.code!==`ENOENT`&&this.logger.warn(` ${z}${U}${L} stop-request watcher setup failed for ${t}: ${e instanceof Error?e.message:String(e)}`)}s=setInterval(d,Ct),d(),e.then(e=>{u(a?{status:Dt}:e)})})}captureTerminalState(){if(!process.stdin.isTTY)return null;try{return(0,r.execFileSync)(`stty`,[`-g`],{encoding:`utf-8`,stdio:[H,rt,`ignore`]}).trim()}catch{return null}}restoreTerminalState(e){if(e&&process.stdin.isTTY)try{(0,r.execFileSync)(`stty`,[e],{stdio:[H,`ignore`,`ignore`]})}catch{}process.stdout.isTTY&&process.stdout.write(`\x1B[0m\x1B[?25h\x1B[?1049l`)}cleanupStatusFile(e){try{(0,c.existsSync)(e)&&(0,c.unlinkSync)(e)}catch(e){this.logger.warn(` ${z}${U}${L} status-file cleanup failed: ${e instanceof Error?e.message:String(e)}`)}}};const Y=`\x1B[0m`,jt=`\x1B[1m`,Mt=`\x1B[2m`,Nt=`\x1B[36m`,Pt=`\x1B[32m`,Ft=`\x1B[31m`,It=`\x1B[34m`;var Lt=class{activePrompt=null;activePromptSignal=null;constructor(e,t){this.stepRunner=e,this.logger=t}async pathExists(e){try{return await(0,a.access)(e),!0}catch{return!1}}abortActivePrompt(e){this.activePromptSignal=e,this.activePrompt?.close()}async handleUserPrompt(e,t,n,r,i){if(!e.on||!(`user_prompt`in e.on))return!0;this.logger.info(`\n ${It}${jt}trigger${Y} ${jt}user_prompt${Y}`),this.logger.info(` ${`─`.repeat(50)}`);let o=t,c=n.CONTEXT_FILE;if(!o&&c){let e=(0,s.resolve)(r,c);await this.pathExists(e)&&(o=(await(0,a.readFile)(e,`utf-8`)).trim(),o&&this.logger.info(` ${Pt}found${Y} Existing context.md -> ${c}`))}if(!o)if(i)this.logger.info(` ${Nt}dry ${Y} Would prompt user for input`),o=`(dry-run: no prompt collected)`;else{this.logger.info(` ${Nt}input${Y} Enter your prompt (press Enter twice to finish):\n`);let e=[],t=(0,f.createInterface)({input:process.stdin,output:process.stdout});this.activePrompt=t,this.activePromptSignal=null,o=await new Promise((n,r)=>{let i=!1,a=e=>{i||(i=!0,this.activePrompt=null,e())};t.on(`line`,n=>{n===``&&e.length>0&&e[e.length-1]===``?t.close():e.push(n)}),t.on(`SIGINT`,()=>{this.activePromptSignal=`SIGINT`,t.close()}),t.on(`close`,()=>a(()=>{let t=this.activePromptSignal;if(this.activePromptSignal=null,t){r(new N(t));return}e.length>0&&e[e.length-1]===``&&e.pop(),n(e.join(`
|
|
27
|
-
`))}))})}if(!o)return this.logger.error(` ${Ft}fail${Y} No prompt provided. Aborting.`),!1;if(c){let e=(0,s.resolve)(r,c);await(0,a.mkdir)((0,s.dirname)(e),{recursive:!0}),await(0,a.writeFile)(e,o,`utf-8`),this.logger.info(` ${Pt}saved${Y} ${o.split(`
|
|
28
|
-
`).length} line(s) -> ${c}`)}return n.USER_PROMPT=o,this.logger.info(` ${Mt}prompt${Y} ${o.split(`
|
|
29
|
-
`)[0].slice(0,80)}${o.includes(`
|
|
30
|
-
`)?`...`:``}`),!0}async handleAgentDecision(e,t,n,r,i,o){let c=e.on?.agent_decision;if(!c?.steps)return!0;this.logger.info(`\n ${It}${jt}trigger${Y} ${jt}agent_decision${Y}`),this.logger.info(` ${`─`.repeat(50)}`),o&&(t.HEARTBEAT_PROMPT=o,this.logger.info(` ${Mt}prompt${Y} ${o.split(`
|
|
31
|
-
`)[0].slice(0,80)}${o.includes(`
|
|
32
|
-
`)?`...`:``}`));let l=t.CONTEXT_FILE;l&&await(0,a.mkdir)((0,s.dirname)((0,s.resolve)(i.workflowDir,l)),{recursive:!0});let u={inputs:n,matrix:{},secrets:r,env:t};for(let e of c.steps)if(!await this.stepRunner.runStep(e,u,i))return this.logger.error(`\n ${Ft}Agent decision aborted workflow${Y}`),!1;if(l&&!i.dryRun){let e=(0,s.resolve)(i.workflowDir,l);if(!await this.pathExists(e))return this.logger.error(` ${Ft}fail${Y} Context file not created: ${l}`),!1;let t=(await(0,a.readFile)(e,`utf-8`)).trim();if(!t)return this.logger.error(` ${Ft}fail${Y} Context file is empty: ${l}`),!1;this.logger.info(` ${Pt}ready${Y} context has ${t.split(`
|
|
33
|
-
`).length} line(s)`)}return!0}};const Rt=[`actions/checkout`,`actions/setup-node`,`actions/cache`,`actions/upload-artifact`,`actions/download-artifact`,`pnpm/action-setup`],zt=`bold.calm.cool.dark.deep.fair.fast.free.gold.keen.kind.loud.neat.pure.rare.safe.slim.soft.tall.warm.wild.wise.blue.gray.jade.iron.zinc.ruby.opal.onyx`.split(`.`),Bt=`arch.beam.bird.bolt.cape.cove.dawn.dove.echo.fern.flux.gale.hawk.haze.iris.jade.kite.lake.lynx.mesa.moth.node.palm.peak.pine.raft.reef.sage.tide.vale`.split(`.`);var Vt=class{generateHumanReadableId(){return`${zt[Math.floor(Math.random()*zt.length)]}-${Bt[Math.floor(Math.random()*Bt.length)]}`}parseWorkflowFile(e){let t=(0,s.resolve)(e);if(!(0,c.existsSync)(t))throw Error(`Workflow file not found: ${t}`);let n=(0,c.readFileSync)(t,`utf-8`),r=be.parse((0,p.load)(n));if(r.imports&&this.resolveImports(r,t),!r.jobs||Object.keys(r.jobs).length===0)throw Error(`No jobs found in workflow file`);return this.resolveExtends(r),r}resolveImports(e,t,n=new Set){let r=(0,s.resolve)(t);if(n.has(r))throw Error(`Circular import detected: ${r}`);n.add(r);let i=r.replace(/\/[^/]+$/,``);for(let t of e.imports??[]){let a=(0,s.resolve)(i,t);if(!(0,c.existsSync)(a))throw Error(`Imported workflow file not found: ${a} (from ${r})`);let o=(0,p.load)((0,c.readFileSync)(a,`utf-8`));if(o.imports&&this.resolveImports(o,a,n),o.env&&(e.env={...o.env,...e.env}),o.pre&&(e.pre||={},o.pre.services&&(e.pre.services=[...o.pre.services,...e.pre.services??[]]),o.pre.steps&&(e.pre.steps=[...o.pre.steps,...e.pre.steps??[]])),o.post&&(e.post||={},o.post.services&&(e.post.services=[...o.post.services,...e.post.services??[]]),o.post.steps&&(e.post.steps=[...o.post.steps,...e.post.steps??[]])),o.worktree){e.worktree||={};for(let t of[`beforeCreate`,`afterCreate`,`beforeCompleted`,`afterCompleted`])o.worktree[t]&&!e.worktree[t]&&(e.worktree[t]=o.worktree[t])}if(o[`max-workflows`]&&!e[`max-workflows`]&&(e[`max-workflows`]=o[`max-workflows`]),o[`launch-command`]&&!e[`launch-command`]&&(e[`launch-command`]=o[`launch-command`]),o.keybindings&&(e.keybindings={...o.keybindings,...e.keybindings}),o[`system-prompt`]&&(e[`system-prompt`]?e[`system-prompt`]=`${o[`system-prompt`]}\n\n${e[`system-prompt`]}`:e[`system-prompt`]=o[`system-prompt`]),o.jobs)for(let[t,n]of Object.entries(o.jobs))t in(e.jobs??{})||(e.jobs||={},e.jobs[t]=n)}delete e.imports}resolveExtends(e){let{jobs:t}=e,n=new Map;for(let[e,r]of Object.entries(t))e.startsWith(`.`)&&n.set(e,r);for(let[e,r]of Object.entries(t)){if(e.startsWith(`.`)||!r.extends)continue;let t=Array.isArray(r.extends)?r.extends:[r.extends],i=[...r.steps??[]],a=[...r.preJob?.steps??[]],o=[...r.postJob?.steps??[]],s=[],c=[],l=[];for(let i of t){let t=n.get(i);if(!t)throw Error(`Job "${e}" extends "${i}" but template not found`);s.push(...t.steps??[]),c.push(...t.preJob?.steps??[]),l.push(...t.postJob?.steps??[]),this.applyTemplate(r,t)}r.steps=[...s,...i],this.assignJobHookSteps(r,`preJob`,[...c,...a]),this.assignJobHookSteps(r,`postJob`,[...l,...o]),delete r.extends}for(let e of n.keys())delete t[e]}applyTemplate(e,t){e.steps=[...t.steps??[],...e.steps??[]],this.mergeJobHookSteps(e,t,`preJob`),this.mergeJobHookSteps(e,t,`postJob`),(t.env||e.env)&&(e.env={...t.env,...e.env}),t[`system-prompt`]&&e[`system-prompt`]?e[`system-prompt`]=`${t[`system-prompt`]}\n\n${e[`system-prompt`]}`:t[`system-prompt`]&&(e[`system-prompt`]=t[`system-prompt`]),t[`runs-on`]&&!e[`runs-on`]&&(e[`runs-on`]=t[`runs-on`]),t.strategy&&!e.strategy&&(e.strategy=t.strategy),t.context&&!e.context&&(e.context=t.context)}mergeJobHookSteps(e,t,n){let r=t[n]?.steps??[],i=e[n]?.steps??[];this.assignJobHookSteps(e,n,[...r,...i])}assignJobHookSteps(e,t,n){if(n.length>0){e[t]={steps:n};return}delete e[t]}loadSecrets(e){let t=new Map;if(!(0,c.existsSync)(e))return t;let n=(0,c.readFileSync)(e,`utf-8`);for(let e of n.split(`
|
|
34
|
-
`)){let n=e.trim();if(!n||n.startsWith(`#`))continue;let r=n.indexOf(`=`);r!==-1&&t.set(n.slice(0,r),n.slice(r+1))}return t}interpolate(e,t){return e.replace(/\$\{\{\s*(.+?)\s*\}\}/g,(e,n)=>{let i=n.trim().split(`.`);if(i[0]===`inputs`&&i[1])return t.inputs.get(i[1])||``;if(i[0]===`matrix`&&i[1])return t.matrix[i[1]]||``;if(i[0]===`secrets`&&i[1])return t.secrets.get(i[1])||process.env[i[1]]||``;if(i[0]===`env`&&i[1])return t.env[i[1]]||process.env[i[1]]||``;if(i[0]===`runner`&&i[1]===`os`)return`macOS`;if(i[0]===`github`&&i[1]===`sha`)try{return(0,r.execSync)(`git rev-parse HEAD`,{encoding:`utf-8`,stdio:[`ignore`,`pipe`,`ignore`]}).trim()}catch{return`local`}return n.includes(`hashFiles`)?`local`:`\${{ ${n} }}`})}isActionSkipped(e){return Rt.some(t=>e.startsWith(t))}resolveJobOrder(e,t){let n=new Set,r=[],i=t=>{if(n.has(t))return;n.add(t);let a=e[t];if(!a)throw Error(`Job not found: ${t}`);let o=a.needs?Array.isArray(a.needs)?a.needs:[a.needs]:[];for(let e of o)i(e);r.push(t)};if(t)i(t);else for(let t of Object.keys(e))i(t);return r}expandMatrix(e){if(!e.strategy?.matrix)return[{}];let{include:t,...n}=e.strategy.matrix;if(t&&t.length>0)return t;let r=Object.keys(n).filter(e=>Array.isArray(n[e]));if(r.length===0)return[{}];let i=[{}];for(let e of r){let t=n[e],r=[];for(let n of i)for(let i of t)r.push({...n,[e]:String(i)});i=r}return i}};const Ht=`\x1B[0m`,Ut=`\x1B[2m`;var Wt=class{constructor(e,t){this.stepRunner=e,this.logger=t}getWorktreeBranchName(e){return`worktree/${e.toLowerCase().replace(/[^a-z0-9-]+/g,`-`).replace(/^-|-$/g,``)}`}createWorktree(e,t){let n=this.getWorktreeBranchName(t),i=n.slice(9),a=(0,s.resolve)((0,s.dirname)(e),`${(0,s.basename)(e)}-worktree`),o=(0,s.resolve)(a,i);(0,c.existsSync)(a)||(0,c.mkdirSync)(a,{recursive:!0}),(0,c.existsSync)(o)&&(this.logger.info(` ${Ut}clean${Ht} Removing stale worktree at ${o}`),this.cleanupWorktreePath(e,o));try{(0,r.execSync)(`git branch -D "${n}"`,{cwd:e,stdio:[`ignore`,`pipe`,`ignore`]})}catch{}return this.logger.info(` [36mcreate${Ht} Worktree at ${o} (branch: ${n})`),(0,r.execSync)(`git worktree add -b "${n}" "${o}" HEAD`,{cwd:e,stdio:[`ignore`,`pipe`,`ignore`]}),o}removeWorktree(e,t){if((0,c.existsSync)(t)){this.logger.info(` ${Ut}remove${Ht} Worktree at ${t}`);try{this.cleanupWorktreePath(e,t)}catch{this.logger.warn(` [33mwarn${Ht} Failed to remove worktree (may need manual cleanup)`)}}}cleanupWorktreePath(e,t){if(this.isRegisteredWorktree(e,t)){(0,r.execSync)(`git worktree remove --force "${t}"`,{cwd:e,stdio:[`ignore`,`pipe`,`ignore`]});return}(0,c.rmSync)(t,{recursive:!0,force:!0})}isRegisteredWorktree(e,t){try{return(0,r.execSync)(`git worktree list --porcelain`,{cwd:e,encoding:`utf-8`,stdio:[`ignore`,`pipe`,`ignore`]}).split(`
|
|
35
|
-
`).some(e=>e.startsWith(`worktree `)&&(0,s.resolve)(e.slice(9))===t)}catch{return!1}}async runHook(e,t,n,r,i,a){let o={inputs:r,matrix:{},secrets:i,env:n};for(let n of e.steps)if(!await this.stepRunner.runStep(n,o,{...a,workflowDir:t}))return!1;return!0}};const X=`\x1B[0m`,Z=`\x1B[1m`,Gt=`\x1B[2m`,Kt=`\x1B[32m`,qt=`\x1B[33m`,Q=`\x1B[31m`,$=`\x1B[34m`,Jt=`SIGINT`,Yt=`SIGTERM`,Xt=`workflow_execution`,Zt=`restart-from`,Qt=`user_prompt`,$t=`agent_decision`,en=`workflow_dispatch`,tn=`Workflow post-cleanup failed`;function nn(e,t){let n=Number(e);return Number.isInteger(n)&&n>0?n:t}var rn=class{logger;parser;serviceManager;stepRunner;jobRunner;triggerService;worktreeService;registry;outputLines=[];interruptedSignal=null;constructor(e,t={}){let n=e||{info:e=>process.stdout.write(`${e}\n`),error:e=>console.error(e),warn:e=>console.error(e)},r=e=>{this.outputLines.push(e),this.outputLines.length>5e3&&this.outputLines.shift()};this.logger={info:e=>{r(e),n.info(e)},error:e=>{r(e),n.error(e)},warn:e=>{r(e),n.warn(e)}},this.parser=t.parser??new Vt,this.serviceManager=t.serviceManager??new Be(this.logger),this.stepRunner=t.stepRunner??new At(this.parser,this.logger),this.jobRunner=t.jobRunner??new Ke(this.parser,this.stepRunner,this.logger),this.triggerService=t.triggerService??new Lt(this.stepRunner,this.logger),this.worktreeService=t.worktreeService??new Wt(this.stepRunner,this.logger),this.registry=t.registry??new Ae}async run(e){this.outputLines=[],this.interruptedSignal=null;let t=e.dryRun??!1,n=e.continueOnError??!1,r=!1,i=e=>{r||(r=!0,this.interrupt(e))},a=()=>i(Jt),o=()=>i(Yt);process.on(Jt,a),process.on(Yt,o);try{return await this.executeWorkflow(e,t,n,e.keepWorktree??!1)}catch(e){if(e instanceof N||this.isInterrupted())return await this.serviceManager.stopAll(),this.createInterruptedResult();throw e}finally{process.off(Jt,a),process.off(Yt,o),await this.serviceManager.stopAll()}}interrupt(e,t={phase:Xt}){if(this.interruptedSignal)return;this.interruptedSignal=e;let n=t.phase===Xt?``:` (${t.phase})`;this.logger.info(`\n\n${qt}${Z}Interrupted — shutting down...${X}${n}`),this.triggerService.abortActivePrompt(e),this.stepRunner.stopActiveStep(e),this.serviceManager.stopAll()}isInterrupted(){return this.interruptedSignal===Jt||this.interruptedSignal===Yt}createInterruptedResult(){return{exitCode:130,output:this.outputLines.join(`
|
|
36
|
-
`)}}parseFixRestartFrom(e,t){if(!e.startsWith(`---`))return{};let n=e.indexOf(`---`,3);if(n<0)return{};let r=e.slice(3,n);for(let e of r.split(`
|
|
37
|
-
`)){let n=e.trim();if(n.startsWith(`${Zt}:`)){let e=n.slice(`${Zt}:`.length).trim();return t.includes(e)?{restartFrom:e}:{invalidTarget:e}}}return{}}async pathExists(e){try{return await(0,a.access)(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async waitForServiceStartup(){await new Promise(e=>{setTimeout(e,2e3)})}resolveRunner(e){if(e.runner&&e.cliAgent&&e.runner!==e.cliAgent)throw Error(`Conflicting runner selectors: runner="${e.runner}" cliAgent="${e.cliAgent}"`);return e.runner??e.cliAgent}async executeWorkflow(e,t,n,i=!1){let o=(0,s.resolve)(e.workflowPath),c=this.parser.parseWorkflowFile(o),l=this.resolveRunner(e),u=null,d=null,f=null,p=(0,s.dirname)(o),m=p,h=null,g=!1,_=!1,v=!!c.worktree,y=new Map,b=e.secretFile?this.parser.loadSecrets(e.secretFile):new Map,x={};try{let f=c.on?.[en]?.inputs||{};for(let[e,t]of Object.entries(f))t.default&&y.set(e,t.default);if(e.inputs)for(let[t,n]of Object.entries(e.inputs))y.set(t,n);if(c.env)for(let[e,t]of Object.entries(c.env))x[e]=String(t);if(e.env)for(let[t,n]of Object.entries(e.env))x[t]=n;l&&(x.WORKFLOW_RUNNER=l,x.WORKFLOW_CLI_AGENT=l);let S=p;for(;S!==`/`;){if(await this.pathExists((0,s.resolve)(S,`.git`))){p=S;break}S=(0,s.dirname)(S)}let C=c[`max-workflows`];if(C){let t=this.registry.resolveWorkspace(e.workspace,c.workspace),n=await this.registry.countRunningWorkflows(t);if(n>=C)throw new Ne(t,n,C)}let ee=c[`launch-command`];if(ee&&!e.skipLaunch){let t=this.buildLaunchCliCommand(e,o),n=e.name||c.name||(0,s.basename)(o),i=e.name?n:`${n}-${this.parser.generateHumanReadableId()}`,a=ee.replace(`{name}`,i).replace(`{command}`,t);this.logger.info(`${Gt}Delegating via launch-command: ${a}${X}`);try{return(0,r.execSync)(a,{stdio:`inherit`,cwd:p,env:this.buildLaunchEnvironment()}),{exitCode:0,output:this.outputLines.join(`
|
|
38
|
-
`)}}catch(e){return{exitCode:e.status??1,output:this.outputLines.join(`
|
|
39
|
-
`)}}}let te=e.name||c.name||(0,s.basename)(o),w=e.name?te:`${te}-${this.parser.generateHumanReadableId()}`;if(u=await this.registry.createRun({displayName:w,dryRun:t,workflowPath:o,workflowWorkspace:c.workspace,workspace:e.workspace}),x.WORKFLOW_RUN_DIR=u.runDir,x.WORKFLOW_WORKSPACE=u.workspace,x.CONTEXT_FILE&&(x.CONTEXT_FILE=u.contextPath,x.CHANGELOG_FILE=u.changelogPath),this.logger.info(`${Z}${`═`.repeat(60)}${X}`),this.logger.info(` ${Z}run-workflow${X} - ${u.displayName}`),this.logger.info(`${Z}${`═`.repeat(60)}${X}`),this.logger.info(` File: ${o}`),this.logger.info(` Workspace: ${u.workspace||`default`}`),this.logger.info(` Run Dir: ${u.runDir}`),this.logger.info(` CWD: ${p}`),y.size>0&&this.logger.info(` Inputs: ${[...y.entries()].map(([e,t])=>`${e}=${t}`).join(`, `)}`),b.size>0&&this.logger.info(` Secrets: ${[...b.keys()].join(`, `)}`),e.job&&this.logger.info(` Target: ${e.job}`),l&&this.logger.info(` Runner: ${l}`),c.pre){let e=c.pre.services?.length||0,t=c.pre.steps?.length||0;this.logger.info(` Pre: ${e} service(s), ${t} setup step(s)`)}if(c.post){let e=c.post.services?.length||0,t=c.post.steps?.length||0;this.logger.info(` Post: ${e} service(s), ${t} cleanup step(s)`)}v&&this.logger.info(` Worktree: enabled${i?` (keep on completion)`:``}`);let ne=c.on&&Qt in c.on?Qt:c.on?.[$t]?$t:en;if(this.logger.info(` Trigger: ${ne}`),this.logger.info(` Mode: ${t?`dry-run`:`execute`}`),this.logger.info(`${Z}${`═`.repeat(60)}${X}`),!await this.triggerService.handleUserPrompt(c,e.prompt||null,x,p,t))return this.isInterrupted()?(d=this.createInterruptedResult(),d):(this.logger.error(`\n${Q}${Z}Workflow aborted: no prompt provided${X}`),d={exitCode:1,output:this.outputLines.join(`
|
|
40
|
-
`)},d);if(!await this.triggerService.handleAgentDecision(c,x,y,b,{runner:l,cliAgent:e.cliAgent,dryRun:t,continueOnError:n,stopRequestPath:u.stopRequestPath,workflowDir:p},e.prompt||null))return this.isInterrupted()?(d=this.createInterruptedResult(),d):(this.logger.info(`\n${qt}${Z}Workflow skipped: agent decided nothing to do${X}`),d={exitCode:2,output:this.outputLines.join(`
|
|
41
|
-
`)},d);if(m=p,v&&!t){if(c.worktree?.beforeCreate&&(this.logger.info(`\n ${$}${Z}worktree${X} ${Z}beforeCreate${X}`),this.logger.info(` ${`─`.repeat(50)}`),await this.worktreeService.runHook(c.worktree.beforeCreate,p,x,y,b,{runner:l,cliAgent:e.cliAgent,dryRun:t,continueOnError:n,stopRequestPath:u.stopRequestPath})||(this.isInterrupted()?d=this.createInterruptedResult():(this.logger.error(`\n${Q}${Z}Workflow aborted: worktree beforeCreate hook failed${X}`),d={exitCode:1,output:this.outputLines.join(`
|
|
42
|
-
`)}))),!d){this.logger.info(`\n ${$}${Z}worktree${X} ${Z}Creating worktree${X}`),this.logger.info(` ${`─`.repeat(50)}`);let r=this.worktreeService.getWorktreeBranchName(u.displayName);h=this.worktreeService.createWorktree(p,u.displayName),p=h,x.WORKTREE_PATH=h,x.WORKTREE_BRANCH=r,x.WORKFLOW_NAME=u.displayName,x.ORIGINAL_REPO_PATH=m,c.worktree?.afterCreate&&(this.logger.info(`\n ${$}${Z}worktree${X} ${Z}afterCreate${X}`),this.logger.info(` ${`─`.repeat(50)}`),await this.worktreeService.runHook(c.worktree.afterCreate,h,x,y,b,{runner:l,cliAgent:e.cliAgent,dryRun:t,continueOnError:n,stopRequestPath:u.stopRequestPath})||(this.isInterrupted()?d=this.createInterruptedResult():(this.logger.error(`\n${Q}${Z}Workflow aborted: worktree afterCreate hook failed${X}`),d={exitCode:1,output:this.outputLines.join(`
|
|
43
|
-
`)}),_=!i))}}else if(v&&t){let e=(0,s.dirname)(p),t=(0,s.basename)(p),n=u.displayName.toLowerCase().replace(/[^a-z0-9-]+/g,`-`).replace(/^-|-$/g,``),r=(0,s.resolve)(e,`${t}-worktree`,n);this.logger.info(`\n ${$}${Z}worktree${X} ${Z}(dry-run)${X} Would create at ${r}`)}!d&&c.pre&&(await this.runPreBlock(c.pre,x,y,b,{runner:l,cliAgent:e.cliAgent,dryRun:t,continueOnError:n,stopRequestPath:u.stopRequestPath,workflowDir:p})||(this.isInterrupted()?d=this.createInterruptedResult():(this.logger.error(`\n${Q}${Z}Workflow aborted: pre-conditions failed${X}`),d={exitCode:1,output:this.outputLines.join(`
|
|
44
|
-
`)}),_=!!(h&&!i)));let re=nn(x.MAX_RETRIES,3),ie=nn(x.FIX_LOOP_MAX_CYCLES,3),T=this.parser.resolveJobOrder(c.jobs,e.job||null);this.logger.info(`\n ${Gt}Job order: ${T.join(` -> `)} (max retries: ${re})${X}`);let ae=new Set,E=x.WORKFLOW_RUN_DIR?(0,s.resolve)(x.WORKFLOW_RUN_DIR,`fix.md`):null,D=0,O=0;for(;!d&&O<T.length;){let r=T[O],i=c.jobs[r],o=await this.jobRunner.runJob(r,i,{inputs:y,secrets:b,workflowEnv:x,workflowSystemPrompt:c[`system-prompt`],jobOrder:T,allJobs:c.jobs},{runner:l,cliAgent:e.cliAgent,dryRun:t,continueOnError:n,stopRequestPath:u.stopRequestPath,workflowDir:p,maxRetries:re});if(this.isInterrupted()&&(d=this.createInterruptedResult()),!d&&!o&&(this.logger.error(`\n${Q}${Z}Workflow failed at job "${r}"${X}`),await this.serviceManager.stopAll(),d={exitCode:1,output:this.outputLines.join(`
|
|
45
|
-
`)}),!d){if(ae.add(r),E&&await this.pathExists(E)&&!t){if(D++,D>ie){this.logger.error(`\n${Q}${Z}Fix loop limit reached (${ie} cycles). Aborting.${X}`),d={exitCode:1,output:this.outputLines.join(`
|
|
46
|
-
`)};continue}let e=(await(0,a.readFile)(E,`utf-8`)).trim();await(0,a.unlink)(E);let{restartFrom:t,invalidTarget:n}=this.parseFixRestartFrom(e,T);if(this.logger.info(`\n${qt}${Z}fix.md detected after "${r}" (cycle ${D}/${ie})${X}`),this.logger.info(`${Gt}${e.split(`
|
|
47
|
-
`)[0].slice(0,100)}${e.includes(`
|
|
48
|
-
`)?`...`:``}${X}`),n&&this.logger.warn(`${qt}fix.md restart-from "${n}" is not a valid job (available: ${T.join(`, `)}), falling back to default${X}`),x.CONTEXT_FILE&&await this.pathExists(x.CONTEXT_FILE)){let t=await(0,a.readFile)(x.CONTEXT_FILE,`utf-8`);await(0,a.writeFile)(x.CONTEXT_FILE,`${t}\n\n---\n## Fix Request (cycle ${D})\n${e}`,`utf-8`)}let i=t?T.indexOf(t):-1,o=T.indexOf(`development`);O=i>=0?i:o>=0?o:1,this.logger.info(`${qt}Restarting from job "${T[O]}"${X}\n`);continue}O++}}!d&&this.isInterrupted()&&(d=this.createInterruptedResult()),d||=(g=!0,this.logger.info(`\n${Z}${`═`.repeat(60)}${X}`),this.logger.info(` ${Kt}${Z}Workflow completed successfully${X}`),this.logger.info(` Jobs run: ${[...ae].join(`, `)}`),h&&this.logger.info(` Worktree: ${h}`),this.logger.info(`${Z}${`═`.repeat(60)}${X}\n`),{exitCode:0,output:this.outputLines.join(`
|
|
49
|
-
`)})}catch(e){if(f=e,e instanceof N||this.isInterrupted())d=this.createInterruptedResult();else throw e}finally{if(g&&d?.exitCode===0&&v&&c.worktree?.beforeCompleted&&!t&&h&&(this.logger.info(`\n ${$}${Z}worktree${X} ${Z}beforeCompleted${X}`),this.logger.info(` ${`─`.repeat(50)}`),await this.worktreeService.runHook(c.worktree.beforeCompleted,h,x,y,b,{runner:l,cliAgent:e.cliAgent,dryRun:t,continueOnError:n})||(this.isInterrupted()?d=this.createInterruptedResult():(this.logger.error(`\n${Q}${Z}worktree beforeCompleted hook failed${X}`),d={exitCode:1,output:this.outputLines.join(`
|
|
50
|
-
`)}))),c.post)try{await this.runPostBlock(c.post,x,y,b,{runner:l,cliAgent:e.cliAgent,dryRun:t,continueOnError:n,workflowDir:p})||(this.logger.error(`\n${Q}${Z}${tn}${X}`),(!d||d.exitCode===0||d.exitCode===2)&&(d={exitCode:1,output:this.outputLines.join(`
|
|
51
|
-
`)}))}catch(e){f??=e,this.logger.error(`\n${Q}${Z}${tn}${X}`),(!d||d.exitCode===0||d.exitCode===2)&&(d={exitCode:1,output:this.outputLines.join(`
|
|
52
|
-
`)})}g&&d?.exitCode===0&&v&&c.worktree?.afterCompleted&&!t&&!i&&(this.logger.info(`\n ${$}${Z}worktree${X} ${Z}afterCompleted${X}`),this.logger.info(` ${`─`.repeat(50)}`),await this.worktreeService.runHook(c.worktree.afterCompleted,m,x,y,b,{runner:l,cliAgent:e.cliAgent,dryRun:t,continueOnError:n})||(this.isInterrupted()?d=this.createInterruptedResult():(this.logger.error(`\n${Q}${Z}worktree afterCompleted hook failed${X}`),d={exitCode:1,output:this.outputLines.join(`
|
|
53
|
-
`)}))),_&&h&&this.worktreeService.removeWorktree(m,h),d&&={...d,output:this.outputLines.join(`
|
|
54
|
-
`)},u&&await this.finalizeRegistryRun(u,d,f)}return d??{exitCode:1,output:this.outputLines.join(`
|
|
55
|
-
`)}}async finalizeRegistryRun(e,t,n){let r=t?.exitCode===130||n instanceof N,i=t?.exitCode??(r?130:1),a=i===0||i===2?`completed`:`error`,o=i===0?`success`:i===2?`skipped`:r||this.isInterrupted()?`interrupted`:`failed`,s=n instanceof Error?n.message:i===1?this.lastMeaningfulOutputLine():void 0;await this.registry.finalizeRun(e,{errorMessage:s,exitCode:i,outcome:o,stage:a})}resolveCliPath(){let e=__dirname,t=(0,s.resolve)(`/`);for(;e!==t;){let t=(0,s.resolve)(e,`cli.cjs`);if((0,c.existsSync)(t))return t;let n=(0,s.resolve)(e,`dist`,`cli.cjs`);if((0,c.existsSync)(n))return n;e=(0,s.dirname)(e)}throw Error(`Unable to locate workflow-mcp cli.cjs from `+__dirname)}buildLaunchEnvironment(){let e={...process.env};return delete e.CMUX_WORKSPACE_ID,e}buildLaunchCliCommand(e,t){let n=[`node`,this.resolveCliPath(),`run-workflow`,t,`--skip-launch`],r=this.resolveRunner(e);if(e.job&&n.push(`--job`,e.job),r&&n.push(`--runner`,r),e.dryRun&&n.push(`--dry-run`),e.continueOnError&&n.push(`--continue-on-error`),e.keepWorktree&&n.push(`--keep-worktree`),e.prompt&&n.push(`--prompt`,`'${e.prompt.replace(/'/g,`'\\''`)}'`),e.name&&n.push(`--name`,`'${e.name}'`),e.workspace&&n.push(`--workspace`,`'${e.workspace}'`),e.secretFile&&n.push(`--secret-file`,e.secretFile),e.inputs)for(let[t,r]of Object.entries(e.inputs))n.push(`--input`,`${t}=${r}`);if(e.env)for(let[t,r]of Object.entries(e.env))n.push(`--env`,`${t}=${r}`);return n.join(` `)}lastMeaningfulOutputLine(){return[...this.outputLines].reverse().find(e=>e.trim().length>0)}async runPreBlock(e,t,n,r,i){if(this.logger.info(`\n ${$}${Z}pre${X} ${Z}Pre-conditions${X}`),this.logger.info(` ${`─`.repeat(50)}`),t.CONTEXT_FILE&&await(0,a.mkdir)((0,s.dirname)((0,s.resolve)(i.workflowDir,t.CONTEXT_FILE)),{recursive:!0}),e.services&&e.services.length>0){this.logger.info(`\n ${$}${Z}services${X}`);for(let n of e.services)if(await this.serviceManager.startService(n,t,i.workflowDir,i.dryRun)&&n[`ready-check`]&&!i.dryRun){let e=await this.serviceManager.waitForServiceReady(n,i.workflowDir,t,()=>this.interruptedSignal!==null);if(this.isInterrupted())return!1;if(!e&&!i.continueOnError)return await this.serviceManager.stopAll(),!1}!i.dryRun&&this.serviceManager.getRunningServices().length>0&&await this.waitForServiceStartup()}if(e.steps&&e.steps.length>0){this.logger.info(`\n ${$}${Z}setup${X}`);let a={inputs:n,matrix:{},secrets:r,env:t};for(let t of e.steps)if(!await this.stepRunner.runStep(t,a,i))return this.logger.error(`\n ${Q}Pre-condition step failed${X}`),await this.serviceManager.stopAll(),!1}return this.logger.info(`\n ${Kt}Pre-conditions ready${X}`),!0}async runPostBlock(e,t,n,r,i){this.logger.info(`\n ${$}${Z}post${X} ${Z}Cleanup${X}`),this.logger.info(` ${`─`.repeat(50)}`),await this.serviceManager.stopAll();try{if(e.services&&e.services.length>0){this.logger.info(`\n ${$}${Z}services${X}`);for(let n of e.services)if(await this.serviceManager.startService(n,t,i.workflowDir,i.dryRun)&&n[`ready-check`]&&!i.dryRun&&!await this.serviceManager.waitForServiceReady(n,i.workflowDir,t,()=>!1)&&!i.continueOnError)return!1;!i.dryRun&&this.serviceManager.getRunningServices().length>0&&await this.waitForServiceStartup()}if(e.steps&&e.steps.length>0){this.logger.info(`\n ${$}${Z}cleanup${X}`);let a={inputs:n,matrix:{},secrets:r,env:t};for(let t of e.steps)if(!await this.stepRunner.runStep(t,a,i))return this.logger.error(`\n ${Q}Post-cleanup step failed${X}`),!1}return this.logger.info(`\n ${Kt}Cleanup complete${X}`),!0}finally{await this.serviceManager.stopAll()}}};const an=n.z.object({workflowPath:n.z.string().describe(`Path to the workflow YAML file (e.g., .github/workflows/deploy.yml)`),runner:n.z.string().optional().describe(`Preferred runner key for step command maps (e.g. ollama, claude, codex)`),cliAgent:n.z.string().optional().describe(`Deprecated alias for runner. Preferred runner command key for step command maps.`),job:n.z.string().optional().describe(`Run only this job (and its dependencies)`),inputs:n.z.record(n.z.string(),n.z.string()).optional().describe(`Workflow dispatch inputs as key-value pairs`),env:n.z.record(n.z.string(),n.z.string()).optional().describe(`Extra environment variables as key-value pairs`),secretFile:n.z.string().optional().describe(`Path to a dotenv-style secrets file`),dryRun:n.z.boolean().optional().describe(`Print steps without executing`),continueOnError:n.z.boolean().optional().describe(`Continue past step failures`),keepWorktree:n.z.boolean().optional().describe(`Keep worktree on completion (skip merge and cleanup for retry)`),prompt:n.z.string().optional().describe(`User prompt for user_prompt trigger workflows`),name:n.z.string().optional().describe(`Name for the workflow run context directory`),workspace:n.z.string().optional().describe(`Workspace for workflow registry storage`)});var on=class e{static TOOL_NAME=`run_workflow`;constructor(e=new rn){this.service=e}getInputSchema(){return an}getDefinition(){return{name:e.TOOL_NAME,description:`Run a GitHub Actions workflow file locally. Parses the workflow YAML and executes run steps on the host machine, respecting job dependencies, matrix strategies, environment variables, and workflow_dispatch inputs.`,inputSchema:n.z.toJSONSchema(an)}}async execute(e){try{let t=an.parse(e);if(t.runner&&t.cliAgent&&t.runner!==t.cliAgent)throw Error(`Conflicting runner selectors: runner="${t.runner}" cliAgent="${t.cliAgent}"`);let n={cliAgent:t.cliAgent,runner:t.runner??t.cliAgent,workflowPath:t.workflowPath,job:t.job,inputs:t.inputs,env:t.env,secretFile:t.secretFile,dryRun:t.dryRun,continueOnError:t.continueOnError,keepWorktree:t.keepWorktree,prompt:t.prompt,name:t.name,workspace:t.workspace},r=await this.service.run(n);return r.exitCode!==0&&r.exitCode!==2?{content:[{type:`text`,text:`Workflow failed (exit code ${r.exitCode}):\n\n${r.output}`}],isError:!0}:{content:[{type:`text`,text:r.output||`Workflow completed successfully.`}]}}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:`Unknown error`}`}],isError:!0}}}},sn=class e{static TOOL_NAME=`schedule-cron`;constructor(e=new ae){this.service=e}getInputSchema(){return w}getDefinition(){return{name:e.TOOL_NAME,description:`Schedule a headless Claude Code or Codex CLI run as a system cron job. Specify either a cron expression or an interval in minutes.`,inputSchema:n.z.toJSONSchema(w)}}async execute(t){try{let e=w.parse(t),n=await this.service.schedule(e);return{content:[{type:`text`,text:JSON.stringify(n,null,2)}]}}catch(n){let r=new g(`Failed to schedule cron job.`,`SCHEDULE_CRON_TOOL_FAILED`,{tool:e.TOOL_NAME,name:t.name,cwd:t.cwd},{cause:n});return console.error(`[${e.TOOL_NAME}] ${r.message}`,r.context),{content:[{type:`text`,text:JSON.stringify({code:r.code,context:r.context,message:r.message},null,2)}],isError:!0}}}};const cn=n.z.object({reason:n.z.string().optional().describe(`Optional stop reason to record.`),runKey:n.z.string().min(1).describe(`Run key of the running workflow to stop.`),workspace:n.z.string().optional().describe(`Workspace containing the running workflow. Defaults to default.`)});var ln=class e{static TOOL_NAME=`stop_workflow`;constructor(e=new Ae){this.registry=e}getInputSchema(){return cn}getDefinition(){return{name:e.TOOL_NAME,description:`Request a running workflow to stop gracefully without taking over terminal stdin.`,inputSchema:n.z.toJSONSchema(cn)}}async execute(e){try{let t=cn.parse(e),n=await this.registry.requestStop(t.workspace,t.runKey,t.reason);return{content:[{type:`text`,text:JSON.stringify({reason:n.reason,requestedAt:n.requestedAt,runKey:t.runKey,workspace:this.registry.resolveWorkspace(t.workspace)},null,2)}]}}catch(e){return{content:[{type:`text`,text:`Failed to request workflow stop. ${e instanceof Error?e.message:`Unknown error`}`}],isError:!0}}}};const un=[on.TOOL_NAME,Me.TOOL_NAME,sn.TOOL_NAME,E.TOOL_NAME,ln.TOOL_NAME];function dn(){let n=new e.Server({name:`workflow-mcp`,version:`0.1.0`},{capabilities:{tools:{}}}),r=new on,i=new Me,a=new sn,o=new E,s=new ln;return n.setRequestHandler(t.ListToolsRequestSchema,async()=>({tools:[r.getDefinition(),i.getDefinition(),a.getDefinition(),o.getDefinition(),s.getDefinition()]})),n.setRequestHandler(t.CallToolRequestSchema,async e=>{let{name:t,arguments:n}=e.params;if(t===on.TOOL_NAME)return await r.execute(n);if(t===Me.TOOL_NAME)return await i.execute(n);if(t===sn.TOOL_NAME)return await a.execute(n);if(t===E.TOOL_NAME)return await o.execute();if(t===ln.TOOL_NAME)return await s.execute(n);throw new h(t,un)}),n}var fn=class{server;transport=null;constructor(e){this.server=e}async start(){this.transport=new m.StdioServerTransport,await this.server.connect(this.transport),console.error(`workflow-mcp MCP server started on stdio`)}async stop(){this.transport&&=(await this.transport.close(),null)}};Object.defineProperty(exports,`a`,{enumerable:!0,get:function(){return Ae}}),Object.defineProperty(exports,`c`,{enumerable:!0,get:function(){return w}}),Object.defineProperty(exports,`i`,{enumerable:!0,get:function(){return Xe}}),Object.defineProperty(exports,`n`,{enumerable:!0,get:function(){return dn}}),Object.defineProperty(exports,`o`,{enumerable:!0,get:function(){return ae}}),Object.defineProperty(exports,`r`,{enumerable:!0,get:function(){return rn}}),Object.defineProperty(exports,`s`,{enumerable:!0,get:function(){return`claude`}}),Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return fn}});
|