yaml-flow 8.4.13 → 8.4.14

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.
@@ -147,4 +147,4 @@ ${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.pus
147
147
  `)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
148
148
  `,r)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let r=mi(e),s=wr(r);return s.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let r=mi(e),s=wr(r);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,r){return this.type!=="comment"||this.indent<=r?!1:e.every(s=>s.type==="newline"||s.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};pm.Parser=nl});var vm=w(Os=>{"use strict";var mm=zc(),v1=ws(),Ns=Ss(),b1=Vo(),S1=x(),_1=sl(),ym=il();function gm(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new _1.LineCounter||null,prettyErrors:e}}function $1(t,e={}){let{lineCounter:r,prettyErrors:s}=gm(e),n=new ym.Parser(r?.addNewLine),i=new mm.Composer(e),a=Array.from(i.compose(n.parse(t)));if(s&&r)for(let o of a)o.errors.forEach(Ns.prettifyError(t,r)),o.warnings.forEach(Ns.prettifyError(t,r));return a.length>0?a:Object.assign([],{empty:!0},i.streamInfo())}function wm(t,e={}){let{lineCounter:r,prettyErrors:s}=gm(e),n=new ym.Parser(r?.addNewLine),i=new mm.Composer(e),a=null;for(let o of i.compose(n.parse(t),!0,t.length))if(!a)a=o;else if(a.options.logLevel!=="silent"){a.errors.push(new Ns.YAMLParseError(o.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return s&&r&&(a.errors.forEach(Ns.prettifyError(t,r)),a.warnings.forEach(Ns.prettifyError(t,r))),a}function E1(t,e,r){let s;typeof e=="function"?s=e:r===void 0&&e&&typeof e=="object"&&(r=e);let n=wm(t,r);if(!n)return null;if(n.warnings.forEach(i=>b1.warn(n.options.logLevel,i)),n.errors.length>0){if(n.options.logLevel!=="silent")throw n.errors[0];n.errors=[]}return n.toJS(Object.assign({reviver:s},r))}function k1(t,e,r){let s=null;if(typeof e=="function"||Array.isArray(e)?s=e:r===void 0&&e&&(r=e),typeof r=="string"&&(r=r.length),typeof r=="number"){let n=Math.round(r);r=n<1?void 0:n>8?{indent:8}:{indent:n}}if(t===void 0){let{keepUndefined:n}=r??e??{};if(!n)return}return S1.isDocument(t)&&!s?t.toString(r):new v1.Document(t,s,r).toString(r)}Os.parse=E1;Os.parseAllDocuments=$1;Os.parseDocument=wm;Os.stringify=k1});var Sm=w(U=>{"use strict";var N1=zc(),O1=ws(),T1=kc(),al=Ss(),P1=ts(),gt=x(),q1=dt(),A1=se(),I1=pt(),C1=mt(),j1=hi(),M1=tl(),R1=sl(),D1=il(),yi=vm(),bm=Qr();U.Composer=N1.Composer;U.Document=O1.Document;U.Schema=T1.Schema;U.YAMLError=al.YAMLError;U.YAMLParseError=al.YAMLParseError;U.YAMLWarning=al.YAMLWarning;U.Alias=P1.Alias;U.isAlias=gt.isAlias;U.isCollection=gt.isCollection;U.isDocument=gt.isDocument;U.isMap=gt.isMap;U.isNode=gt.isNode;U.isPair=gt.isPair;U.isScalar=gt.isScalar;U.isSeq=gt.isSeq;U.Pair=q1.Pair;U.Scalar=A1.Scalar;U.YAMLMap=I1.YAMLMap;U.YAMLSeq=C1.YAMLSeq;U.CST=j1;U.Lexer=M1.Lexer;U.LineCounter=R1.LineCounter;U.Parser=D1.Parser;U.parse=yi.parse;U.parseAllDocuments=yi.parseAllDocuments;U.parseDocument=yi.parseDocument;U.stringify=yi.stringify;U.visit=bm.visit;U.visitAsync=bm.visitAsync});var ZT=Si(td(),1);import*as K from"fs";import{existsSync as qm}from"fs";import*as z from"path";import{dirname as Am,resolve as bi}from"path";import{createRequire as cl}from"module";import{fileURLToPath as Im}from"url";import{spawn as _m,execFile as L1,execFileSync as x1}from"child_process";import*as Cm from"os";var nP=Si(Cd(),1);import{randomUUID as F1}from"crypto";function K1(t,e,r,s){let n=t.steps[r];if(!n)throw new Error(`Step "${r}" not found in flow configuration`);if(s.result==="failure"&&n.retry){let o=e.retryCounts[r]??0;if(o<n.retry.max_attempts)return{newState:{...e,retryCounts:{...e.retryCounts,[r]:o+1},updatedAt:Date.now()},nextStep:r,isTerminal:!1,isCircuitBroken:!1,shouldRetry:!0}}let i=n.failure_transitions?.[s.result]??n.transitions[s.result];if(!i)throw new Error(`No transition defined for result "${s.result}" in step "${r}"`);let a=!!t.terminal_states[i];return{newState:{...e,currentStep:i,stepHistory:[...e.stepHistory,r],retryCounts:{...e.retryCounts,[r]:0},updatedAt:Date.now()},nextStep:i,isTerminal:a,isCircuitBroken:!1,shouldRetry:!1}}function U1(t,e,r){let s=t.steps[r];if(!s?.circuit_breaker)return{broken:!1,newState:{...e,iterationCounts:{...e.iterationCounts,[r]:(e.iterationCounts[r]??0)+1},updatedAt:Date.now()}};let n=e.iterationCounts[r]??0;return n>=s.circuit_breaker.max_iterations?{broken:!0,redirectStep:s.circuit_breaker.on_open,newState:{...e,currentStep:s.circuit_breaker.on_open,updatedAt:Date.now()}}:{broken:!1,newState:{...e,iterationCounts:{...e.iterationCounts,[r]:n+1},updatedAt:Date.now()}}}function V1(t,e,r){let s=t.steps[e];if(!s)throw new Error(`Step "${e}" not found`);if(s.expects_data){let n={};for(let i of s.expects_data)n[i]=r[i];return n}return{...r}}function B1(t,e){if(t===!1||t===void 0)return{};if(typeof t=="string")return{[t]:e[t]};if(Array.isArray(t)){let r={};for(let s of t)r[s]=e[s];return r}return{}}function z1(t,e){let r=Date.now();return{runId:e,flowId:t.id??"unnamed",currentStep:t.settings.start_step,status:"running",stepHistory:[],iterationCounts:{},retryCounts:{},startedAt:r,updatedAt:r}}var jm=class{runs=new Map;data=new Map;async saveRunState(t,e){this.runs.set(t,{...e})}async loadRunState(t){let e=this.runs.get(t);return e?{...e}:null}async deleteRunState(t){this.runs.delete(t),this.data.delete(t)}async setData(t,e,r){this.data.has(t)||this.data.set(t,{});let s=this.data.get(t);s[e]=r}async getData(t,e){return this.data.get(t)?.[e]}async getAllData(t){return{...this.data.get(t)??{}}}async clearData(t){this.data.delete(t)}async listRuns(){return Array.from(this.runs.keys())}clear(){this.runs.clear(),this.data.clear()}};function J1(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}var Y1=class{flow;handlers;store;components;options;listeners=new Map;aborted=!1;constructor(t,e,r={}){this.flow=t,this.handlers=new Map(Object.entries(e)),this.store=r.store??new jm,this.components=r.components??{},this.options=r,r.signal&&r.signal.addEventListener("abort",()=>{this.aborted=!0}),this.validateFlow()}validateFlow(){let{settings:t,steps:e,terminal_states:r}=this.flow;if(!t?.start_step)throw new Error("Flow must have settings.start_step defined");if(!e||Object.keys(e).length===0)throw new Error("Flow must have at least one step defined");if(!r||Object.keys(r).length===0)throw new Error("Flow must have at least one terminal_state defined");if(!e[t.start_step]&&!r[t.start_step])throw new Error(`Start step "${t.start_step}" not found`);for(let[s,n]of Object.entries(e)){for(let[i,a]of Object.entries(n.transitions))if(!e[a]&&!r[a])throw new Error(`Step "${s}" transition "${i}" points to unknown step "${a}"`);if(n.failure_transitions){for(let[i,a]of Object.entries(n.failure_transitions))if(!e[a]&&!r[a])throw new Error(`Step "${s}" failure_transition "${i}" points to unknown step "${a}"`)}}}on(t,e){this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(e)}off(t,e){this.listeners.get(t)?.delete(e)}emit(t){let e=this.listeners.get(t.type);if(e)for(let r of e)try{r(t)}catch{}}sleep(t){return new Promise(e=>setTimeout(e,t))}async run(t){let e=J1(),r=z1(this.flow,e);if(await this.store.saveRunState(e,r),t)for(let[s,n]of Object.entries(t))await this.store.setData(e,s,n);this.emit({type:"flow:start",runId:e,timestamp:r.startedAt,data:{initialData:t??{}}});try{return await this.executeLoop(e,r)}catch(s){let n=s instanceof Error?s:new Error(String(s));return this.emit({type:"flow:error",runId:e,timestamp:Date.now(),data:{error:n.message}}),this.options.onError?.(n),r={...r,status:"failed",updatedAt:Date.now()},await this.store.saveRunState(e,r),{runId:e,status:"failed",data:await this.store.getAllData(e),finalStep:r.currentStep,stepHistory:r.stepHistory,durationMs:Date.now()-r.startedAt,error:n}}}async resume(t){let e=await this.store.loadRunState(t);if(!e)throw new Error(`No run found with ID: ${t}`);if(e.status==="completed"||e.status==="failed")throw new Error(`Cannot resume a ${e.status} run`);let r={...e,status:"running",pausedAt:void 0,updatedAt:Date.now()};return await this.store.saveRunState(t,r),this.emit({type:"flow:resumed",runId:t,timestamp:Date.now(),data:{currentStep:r.currentStep}}),this.executeLoop(t,r)}async pause(t){let e=await this.store.loadRunState(t);if(!e)throw new Error(`No run found with ID: ${t}`);let r={...e,status:"paused",pausedAt:Date.now(),updatedAt:Date.now()};await this.store.saveRunState(t,r),this.emit({type:"flow:paused",runId:t,timestamp:Date.now(),data:{currentStep:r.currentStep}})}async executeLoop(t,e){let r=this.flow.settings.max_total_steps??1e6,s=this.flow.settings.timeout_ms,n=e,i=0;for(;i<r;){if(this.aborted)return n={...n,status:"cancelled",updatedAt:Date.now()},await this.store.saveRunState(t,n),{runId:t,status:"cancelled",data:await this.store.getAllData(t),finalStep:n.currentStep,stepHistory:n.stepHistory,durationMs:Date.now()-n.startedAt};if(s&&Date.now()-n.startedAt>s)return n={...n,status:"completed",updatedAt:Date.now()},await this.store.saveRunState(t,n),{runId:t,status:"timeout",intent:"timeout",data:await this.store.getAllData(t),finalStep:n.currentStep,stepHistory:n.stepHistory,durationMs:Date.now()-n.startedAt};let a=n.currentStep,o=this.flow.terminal_states[a];if(o){n={...n,status:"completed",updatedAt:Date.now()},await this.store.saveRunState(t,n);let m=await this.store.getAllData(t),h={runId:t,status:"completed",intent:o.return_intent,data:B1(o.return_artifacts,m),finalStep:a,stepHistory:n.stepHistory,durationMs:Date.now()-n.startedAt};return this.emit({type:"flow:complete",runId:t,timestamp:Date.now(),data:{...h}}),this.options.onComplete?.(h),h}let c=U1(this.flow,n,a);if(c.broken){n=c.newState,await this.store.saveRunState(t,n),i++;continue}n=c.newState;let l=await this.store.getAllData(t),u=V1(this.flow,a,l),f={runId:t,stepName:a,components:this.components,store:this.store,signal:this.options.signal,emit:(m,h)=>{this.emit({type:"step:complete",runId:t,timestamp:Date.now(),data:{event:m,payload:h}})}};this.emit({type:"step:start",runId:t,timestamp:Date.now(),data:{step:a,input:u}});let d;try{let m=this.handlers.get(a);if(!m)throw new Error(`No handler registered for step "${a}"`);d=await m(u,f)}catch(m){let h=m instanceof Error?m:new Error(String(m));this.emit({type:"step:error",runId:t,timestamp:Date.now(),data:{step:a,error:h.message}}),d={result:"failure",data:{error:h.message}}}if(d.data)for(let[m,h]of Object.entries(d.data))await this.store.setData(t,m,h);this.emit({type:"step:complete",runId:t,timestamp:Date.now(),data:{step:a,result:d.result}}),this.options.onStep?.(a,d);let p=K1(this.flow,n,a,d);if(n=p.newState,p.shouldRetry){await this.store.saveRunState(t,n);let m=this.flow.steps[a];if(m.retry?.delay_ms){let h=n.retryCounts[a]??0,y=m.retry.backoff_multiplier?m.retry.delay_ms*Math.pow(m.retry.backoff_multiplier,h-1):m.retry.delay_ms;await this.sleep(y)}i++;continue}await this.store.saveRunState(t,n),this.emit({type:"transition",runId:t,timestamp:Date.now(),data:{from:a,to:n.currentStep,result:d.result}}),this.options.onTransition?.(a,n.currentStep),i++}return n={...n,status:"completed",updatedAt:Date.now()},await this.store.saveRunState(t,n),{runId:t,status:"max_iterations",intent:"max_iterations",data:await this.store.getAllData(t),finalStep:n.currentStep,stepHistory:n.stepHistory,durationMs:Date.now()-n.startedAt}}};function G1(t,e,r){return new Y1(t,e,r)}async function Mm(t){return(await Promise.resolve().then(()=>Si(Sm(),1))).parse(t)}async function H1(t){let e=await fetch(t);if(!e.ok)throw new Error(`Failed to load flow from ${t}: ${e.statusText}`);let r=e.headers.get("content-type")??"",s=await e.text();return r.includes("json")||t.endsWith(".json")?JSON.parse(s):Mm(s)}async function W1(t){let e=await(await import("fs/promises")).readFile(t,"utf-8");return t.endsWith(".json")?JSON.parse(e):Mm(e)}function Q1(t){let e=[];if(!t||typeof t!="object")return["Flow must be an object"];let r=t;if(!r.settings||typeof r.settings!="object"?e.push('Flow must have a "settings" object'):typeof r.settings.start_step!="string"&&e.push("settings.start_step must be a string"),!r.steps||typeof r.steps!="object")e.push('Flow must have a "steps" object');else{let s=r.steps;for(let[n,i]of Object.entries(s)){if(!i||typeof i!="object"){e.push(`Step "${n}" must be an object`);continue}let a=i;(!a.transitions||typeof a.transitions!="object")&&e.push(`Step "${n}" must have a "transitions" object`),a.failure_transitions!==void 0&&typeof a.failure_transitions!="object"&&e.push(`Step "${n}" failure_transitions must be an object when provided`)}}if(!r.terminal_states||typeof r.terminal_states!="object")e.push('Flow must have a "terminal_states" object');else{let s=r.terminal_states;for(let[n,i]of Object.entries(s)){if(!i||typeof i!="object"){e.push(`Terminal state "${n}" must be an object`);continue}typeof i.return_intent!="string"&&e.push(`Terminal state "${n}" must have a "return_intent" string`)}}return e}async function X1(t){let e;typeof t=="string"?t.startsWith("http://")||t.startsWith("https://")?e=await H1(t):t.includes("{")?e=JSON.parse(t):e=await W1(t):e=t;let r=Q1(e);if(r.length>0)throw new Error(`Invalid step flow configuration:
149
149
  - ${r.join(`
150
- - `)}`);return e}function ol(t){return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function $m(t){return atob(t.replace(/-/g,"+").replace(/_/g,"/"))}var Z1=class{constructor(t){this.kv=t}kv;stateKey(t){return`state_${ol(t)}`}dataPrefix(t){return`data_${ol(t)}_`}dataKey(t,e){return`${this.dataPrefix(t)}${ol(e)}`}async saveRunState(t,e){this.kv.write(this.stateKey(t),e)}async loadRunState(t){let e=this.kv.read(this.stateKey(t));return e!=null&&typeof e=="object"?e:null}async deleteRunState(t){this.kv.delete(this.stateKey(t));for(let e of this.kv.listKeys(this.dataPrefix(t)))this.kv.delete(e)}async setData(t,e,r){this.kv.write(this.dataKey(t,e),r)}async getData(t,e){return this.kv.read(this.dataKey(t,e))}async getAllData(t){let e=this.dataPrefix(t),r={};for(let s of this.kv.listKeys(e))r[$m(s.slice(e.length))]=this.kv.read(s);return r}async clearData(t){for(let e of this.kv.listKeys(this.dataPrefix(t)))this.kv.delete(e)}async listRuns(){return this.kv.listKeys("state_").map(t=>$m(t.slice(6)))}},Em=Am(Im(import.meta.url)),ek=cl(import.meta.url);function tk(){let t=bi(Em,"./jsonata-sync.cjs");return qm(t)?t:bi(Em,"../card-compute/jsonata-sync.cjs")}var Rm=ek(tk());function rk(t,e){if(!t||typeof t!="object")throw new Error(`[step-machine-public] Step "${e}" returned a non-object result.`);let r=t,s=r.result??r.status;if(typeof s=="string"&&s.trim().length>0){let n=r.data&&typeof r.data=="object"&&!Array.isArray(r.data)?{...r.data}:{},i=typeof r.error=="string"?r.error:void 0;return i&&!("error"in n)&&(n.error=i),{result:s,data:n,...i?{error:i}:{}}}return{result:"success",data:{...r}}}function sk(t,e){if(!e||e.length===0)return t;let r={};for(let s of e)Object.prototype.hasOwnProperty.call(t,s)&&(r[s]=t[s]);return r}function nk(t,e){return async(r,s)=>{let n=await t(r,s),i=rk(n,s?.stepName??"unknown");return{result:i.result,data:sk(i.data,e),...i.error?{error:i.error}:{}}}}function ik(t,e,r){if(!e||e.length===0)return null;for(let s of e)try{if(!Rm(s).evaluate(t))return{result:"failure",data:{error:`[${r}] input validation failed: ${s}`}}}catch(n){let i=n instanceof Error?n.message:String(n);return{result:"failure",data:{error:`[${r}] input validation error on "${s}": ${i}`}}}return null}function ak(t,e,r){return!e||e.length===0?t:async(s,n)=>ik(s,e,r)||t(s,n)}var km=Am(Im(import.meta.url)),ok=cl(import.meta.url);function ck(){let t=bi(km,"./jsonata-sync.cjs");return qm(t)?t:bi(km,"../../card-compute/jsonata-sync.cjs")}var wt=ok(ck()),wi="b64:";function lk(t){let e=new TextEncoder().encode(t),r=globalThis.Buffer,s;if(r)s=r.from(e).toString("base64");else if(typeof btoa=="function"){let n="";for(let i of e)n+=String.fromCharCode(i);s=btoa(n)}else throw new Error("No base64 encoder available in this runtime");return s.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function uk(t){let e=t.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-t.length%4)%4),r=globalThis.Buffer;if(r)return r.from(e,"base64").toString("utf8");if(typeof atob=="function"){let s=atob(e),n=new Uint8Array(s.length);for(let i=0;i<s.length;i+=1)n[i]=s.charCodeAt(i);return new TextDecoder().decode(n)}throw new Error("No base64 decoder available in this runtime")}function ll(t){return`${wi}${lk(JSON.stringify(t))}`}function Dm(t){if(!t.startsWith(wi))throw new Error(`Invalid ref format (expected ${wi}<base64url(json)>): ${t}`);let e;try{e=JSON.parse(uk(t.slice(wi.length)))}catch{throw new Error(`Invalid ref format (malformed base64url/json): ${t}`)}if(!e||typeof e!="object")throw new Error(`Invalid ref format (expected object payload): ${t}`);let r=e;if(typeof r.kind!="string"||typeof r.value!="string")throw new Error(`Invalid ref format (payload must contain string kind/value): ${t}`);return{kind:r.kind,value:r.value}}function vt(t){t.registerFunction("fsPathRef",e=>ll({kind:"fs-path",value:String(e)}),"<s:s>")}function fk(t,e,r){if(!t||typeof t!="object")return{};let s={};if(Array.isArray(t.cmdTemplate)){let n=[];for(let i of t.cmdTemplate)try{let a=wt(i);vt(a),n.push(String(a.evaluate(e)))}catch(a){let o=a instanceof Error?a.message:String(a);throw new Error(`[${r}] argsMassaging.cmdTemplate failed on "${i}": ${o}`)}s.cmdArgs=n}if(typeof t.stdinTemplate=="string")try{let n=wt(t.stdinTemplate);vt(n),s.stdin=n.evaluate(e)}catch(n){let i=n instanceof Error?n.message:String(n);throw new Error(`[${r}] argsMassaging.stdinTemplate failed: ${i}`)}if(typeof t.urlTemplate=="string")try{let n=wt(t.urlTemplate);vt(n),s.url=String(n.evaluate(e))}catch(n){let i=n instanceof Error?n.message:String(n);throw new Error(`[${r}] argsMassaging.urlTemplate failed: ${i}`)}if(typeof t.headerTemplate=="string")try{let n=wt(t.headerTemplate);vt(n);let i=n.evaluate(e);if(typeof i!="object"||i===null)throw new Error(`headerTemplate must produce an object, got: ${JSON.stringify(i)}`);s.headers=i}catch(n){let i=n instanceof Error?n.message:String(n);throw new Error(`[${r}] argsMassaging.headerTemplate failed: ${i}`)}if(typeof t.bodyTemplate=="string")try{let n=wt(t.bodyTemplate);vt(n),s.body=n.evaluate(e)}catch(n){let i=n instanceof Error?n.message:String(n);throw new Error(`[${r}] argsMassaging.bodyTemplate failed: ${i}`)}return s}function dk(t,e,r){if(!t||typeof t!="object")return e;let s={output:e},n=e.result,i=e.data,a=e.error;if(typeof t.resultExpr=="string")try{let o=wt(t.resultExpr);vt(o);let c=o.evaluate(s);if(typeof c!="string"||!c.trim())throw new Error(`resultExpr did not produce a non-empty string (got ${JSON.stringify(c)})`);n=c}catch(o){let c=o instanceof Error?o.message:String(o);throw new Error(`[${r}] outputTransforms.resultExpr failed: ${c}`)}if(typeof t.dataTemplate=="string")try{let o=wt(t.dataTemplate);vt(o);let c=o.evaluate(s);if(!c||typeof c!="object"||Array.isArray(c))throw new Error(`dataTemplate did not produce an object (got ${JSON.stringify(c)})`);i=c}catch(o){let c=o instanceof Error?o.message:String(o);throw new Error(`[${r}] outputTransforms.dataTemplate failed: ${c}`)}if(typeof t.errorExpr=="string")try{let o=wt(t.errorExpr);vt(o);let c=o.evaluate(s);a=c!=null?String(c):void 0}catch(o){let c=o instanceof Error?o.message:String(o);throw new Error(`[${r}] outputTransforms.errorExpr failed: ${c}`)}return a!==void 0?{result:n,data:i,error:a}:{result:n,data:i}}function hk(t){return!!t&&typeof t=="object"&&t.type==="compute-jsonata"&&Array.isArray(t.expr)&&t.expr.length>0}function pk(t){if(!t||typeof t!="object")return!1;let e=t;if(e.type!=="ref"||typeof e.howToRun!="string")return!1;if(typeof e.whatToRun=="string")return!0;if(e.whatToRun&&typeof e.whatToRun=="object"){let r=e.whatToRun;return typeof r.kind=="string"&&typeof r.value=="string"}return!1}function mk(t){if(typeof t=="string"){let e=t.indexOf("=");if(e<1)throw new Error(`[step-machine-public] Invalid compute expression (missing "="): "${t}"`);return{bindTo:t.slice(0,e).trim(),expr:t.slice(e+1).trim()}}if(t&&typeof t=="object"&&typeof t.bindTo=="string"&&typeof t.expr=="string")return t;throw new Error(`[step-machine-public] Invalid compute step: ${JSON.stringify(t)}`)}function yk(t,e,r){let s=e.split("."),n=t;for(let i=0;i<s.length-1;i++){let a=s[i];(n[a]==null||typeof n[a]!="object")&&(n[a]={}),n=n[a]}n[s[s.length-1]]=r}function gk(t,e,r){let s=t.expr.map(mk);return async n=>{let i=n&&typeof n=="object"&&!Array.isArray(n)?{...n}:{},a={},o={expects_data:i,data:a,...r?{config:r}:{}},c,l;for(let u of s)try{let f=Rm(u.expr).evaluate(o);if(u.bindTo==="result")c=f!=null?String(f):"success";else if(u.bindTo==="error")l=f!=null?String(f):void 0;else if(u.bindTo.startsWith("data."))yk(a,u.bindTo.slice(5),f);else return{result:"failure",data:{},error:`[${e}] invalid bindTo "${u.bindTo}": must be "result", "error", or start with "data."`}}catch(f){let d=f instanceof Error?f.message:String(f);return{result:"failure",data:{},error:`[${e}] compute "${u.bindTo}" failed: ${d}`}}return c===void 0?{result:"failure",data:{},error:`[${e}] compute-jsonata: no "result" binding declared \u2014 add '- result = "success"' to expr`}:l?{result:c,data:a,error:l}:{result:c,data:a}}}function wk(t,e,r,s){let{type:n,...i}=t,a={...i,whatToRun:typeof i.whatToRun=="object"?ll(i.whatToRun):i.whatToRun};return async o=>{let c=o&&typeof o=="object"&&!Array.isArray(o)?{...o}:{};s&&(c.config=s);try{let l=await r(a,c);if(!t.outputTransforms)return l;try{return dk(t.outputTransforms,l,e)}catch(u){let f=u instanceof Error?u.message:String(u);return{result:"failure",data:{},error:f}}}catch(l){let u=l instanceof Error?l.message:String(l);return{result:"failure",data:{error:`[step-machine-public] step "${e}" invoke threw: ${u}`}}}}}function vk(){return async t=>({result:"success",data:t&&typeof t=="object"&&!Array.isArray(t)?t:{}})}function bk(t,e,r){return async(s,n)=>{let i=s?.[e.items];if(!Array.isArray(i))return{result:"failure",data:{},error:`[${r}] forEach: "${e.items}" is not an array (got ${typeof i})`};let a=i,o=e.collectAs??`${e.items}_results`;if(a.length===0)return{result:"success",data:{[o]:[]}};let{[e.items]:c,...l}=s,u=Math.max(1,e.concurrency??1),f=new Array(a.length),d=0,p=0,m=0;return await new Promise(h=>{function y(){for(;d<u&&p<a.length;){let g=p++;d++;let b={...l,[e.as]:a[g]};t(b,n).then(v=>{f[g]=v}).catch(v=>{let _=v instanceof Error?v.message:String(v);f[g]={result:"failure",data:{},error:_}}).finally(()=>{d--,f[g]?.result==="failure"&&m++,p>=a.length&&d===0?h():y()})}d===0&&p>=a.length&&h()}y()}),m>0?{result:"failure",data:{errors:f.filter(h=>h.result==="failure").map(h=>h.error)},error:`[${r}] forEach: ${m}/${a.length} items failed`}:{result:"success",data:{[o]:f.map(h=>h.data)}}}}function Sk(t,e,r){let s=Array.isArray(e?.produces_data)?e?.produces_data:void 0,n=Array.isArray(e?.input_validations)?e?.input_validations:void 0,i=e?.config??void 0,a=e?.handler,o;return hk(a)?o=gk(a,t,i):pk(a)?o=wk(a,t,r.invoke,i):o=vk(),e?.forEach&&(o=bk(o,e.forEach,t)),ak(nk(o,s),n,t)}function _k(t,e){let r={};for(let[s,n]of Object.entries(t.steps??{}))r[s]=Sk(s,n,e);return r}function $k(t){if(typeof t=="object"&&t!==null){let{command:r,args:s=[],...n}=t,i=Nm(r,s);return{...n,command:i.command,args:i.args}}let e=Lm(t);if(e.length===0)throw new Error(`Empty command spec: ${JSON.stringify(t)}`);return Nm(e[0],e.slice(1))}function Nm(t,e){return/^(node|node\.exe)$/i.test(t)?{command:process.execPath,args:e}:/\.m?js$/i.test(t)?{command:process.execPath,args:[t,...e]}:{command:t,args:e}}function Lm(t){let e=[],r="",s=null;for(let n of t.trim()){if(s){n===s?s=null:r+=n;continue}if(n==='"'||n==="'"){s=n;continue}if(/\s/.test(n)){r&&(e.push(r),r="");continue}r+=n}if(s)throw new Error(`Unterminated quote in command: ${t}`);return r&&e.push(r),e}function ul(t){return process.platform==="win32"&&/\.(cmd|bat)$/i.test(t)}function Ek(t,e){let{command:r,args:s=[],cwd:n,env:i,timeoutMs:a}=t;return x1(r,s,{shell:ul(r),timeout:a,encoding:e?.encoding??"utf-8",cwd:n,windowsHide:!0,env:i?{...process.env,...i}:void 0,input:e?.input})}function kk(t,e){let{command:r,args:s=[],cwd:n,env:i,timeoutMs:a=3e4}=t;L1(r,s,{shell:ul(r),encoding:"utf8",windowsHide:!0,timeout:a,maxBuffer:10*1024*1024,cwd:n,env:i?{...process.env,...i}:void 0},(o,c,l)=>e(o??null,c,l))}z.join(Cm.tmpdir(),".board-live-cards-git-bash-cache.json");function Nk(t){let{command:e,args:r=[]}=t;if(process.platform==="win32"){let s=!!process.env.VITEST||process.env.NODE_ENV==="test";_m(e,r,{detached:!s,stdio:"ignore",windowsHide:!0,shell:ul(e)}).unref();return}_m(e,r,{detached:!0,stdio:"ignore"}).unref()}function Ok(t,e,r){let s=z.join(t,"board-live-cards-cli.js");if(K.existsSync(s))return{cmd:process.execPath,args:[s,e,...r]};let n=z.join(t,"board-live-cards-cli.ts"),i=[z.join(t,"..","..","..","node_modules","tsx","dist","cli.mjs"),z.join(t,"..","..","node_modules","tsx","dist","cli.mjs"),z.join(t,"..","..","..","node_modules",".bin","tsx"),z.join(t,"..","..","node_modules",".bin","tsx")].find(a=>K.existsSync(a));return K.existsSync(n)&&K.existsSync(i)?{cmd:process.execPath,args:[i,n,e,...r]}:{cmd:process.platform==="win32"?"npx.cmd":"npx",args:["tsx",n,e,...r]}}function Tk(){return{executeSync(t,e,r){return Ek({command:t,args:e,cwd:r?.cwd,timeoutMs:r?.timeout,env:r?.env},{encoding:r?.encoding,input:r?.input})},executeAsync(t,e,r){kk({command:t,args:e},r)},resolveInvocation(t,e){let r=$k({command:t,args:e});return{cmd:r.command,args:r.args??[]}},splitCommand:Lm,spawnDetached(t,e){Nk({command:t,args:e})}}}var Pk=cl(import.meta.url);function qk(t){return typeof t=="object"?t:Dm(t)}function Ak(t){let e=z.basename(String(t||"").trim());if(!e)throw new Error(`resolveYamlFlowCliPath: expected non-empty cli file name, got ${JSON.stringify(t)}`);let r=z.dirname(Pk.resolve("yaml-flow/package.json")),s=e.replace(/\.[^.]+$/,""),n=z.join(r,"cli","bundled",`${s}.mjs`);if(K.existsSync(n))return n;let i=z.join(r,"cli","node",e);if(K.existsSync(i))return i;throw new Error(`resolveYamlFlowCliPath: could not find ${e} under cli/bundled or cli/node in ${r}`)}function fl(t){let e=qk(t);return e.kind==="yaml-flow-cli"?Ak(e.value):e.value}function Ik(t,e){let r=fl(t);switch(r){case"source-cli-task-executor":{let s=z.join(e,"source-cli-task-executor.js");if(K.existsSync(s))return{command:process.execPath,args:[s]};let n=z.join(e,"source-cli-task-executor.ts"),i=z.join(e,"..","..","node_modules","tsx","dist","cli.mjs"),a=z.join(e,"..","..","node_modules",".bin","tsx"),o=K.existsSync(i)?i:a;return K.existsSync(n)&&K.existsSync(o)?{command:process.execPath,args:[o,n]}:{command:process.execPath,args:[s]}}case"board-live-cards":{let{cmd:s,args:n}=Ok(e,"_",[]);return{command:s,args:n}}default:throw new Error(`resolveBuiltIn: unknown built-in name "${r}". Supported: source-cli-task-executor, board-live-cards`)}}function Ck(t,e){if(t.howToRun==="built-in"){let{command:s,args:n}=Ik(t.whatToRun,e);return{command:s,baseArgs:n}}let r=(t.whatToRun,fl(t.whatToRun));switch(t.howToRun){case"local-node":return{command:process.execPath,baseArgs:[r]};case"local-python":return{command:process.platform==="win32"?"python":"python3",baseArgs:[r]};case"local-process":return{command:r,baseArgs:[]};default:throw new Error(`resolveBaseInvocation: howToRun "${t.howToRun}" is not a local transport`)}}function jk(t,e){return Ck(t,e)}function Mk(t){let e=t.trim();if(!e)throw new Error("empty stdout");try{return JSON.parse(e)}catch{let r=e.split(/\r?\n/).filter(Boolean),s=r[r.length-1];return JSON.parse(s)}}function Rk(t,e){return{...e,whatToRun:fl(t.whatToRun),...t.extra?{extra:t.extra}:{}}}function Dk(t,e,r="invokeExecutionRef"){return fk(t,e,r)}function Lk(t){return t&&typeof t=="object"&&!Array.isArray(t)&&typeof t.result=="string"&&t.data&&typeof t.data=="object"&&!Array.isArray(t.data)?t:{result:"success",data:t&&typeof t=="object"&&!Array.isArray(t)?t:{stdout:t}}}function vi(t){return{result:"failure",data:{error:t}}}function gi(t,e,r){let s=r?.label??"invokeExecutionRefSync",n=r?.cliDir??r?.cwd??process.cwd(),i;try{i=Dk(t.argsMassaging,Rk(t,e),s)}catch(f){let d=f instanceof Error?f.message:String(f);return vi(d)}let a;try{a=jk(t,n)}catch(f){let d=f instanceof Error?f.message:String(f);return vi(`[${s}] ref resolution failed: ${d}`)}let o=[...a.baseArgs,...i.cmdArgs??[]],c=JSON.stringify(i.stdin??e),l=Tk(),u;try{u=l.executeSync(a.command,o,{timeout:r?.timeoutMs??3e4,encoding:"utf-8",cwd:r?.cwd,input:c})}catch(f){let d=f,p=(d.stderr?String(d.stderr):"").trim(),m=typeof d.status=="number"?d.status:"unknown",h=p||d.message;return vi(`[${s}] ref exited with status ${m}${h?`: ${h}`:""}`)}try{return Lk(Mk(u))}catch{return{result:"success",data:{stdout:u.trim()}}}}var xk={"local-node":gi,"local-python":gi,"local-process":gi,"built-in":gi};function Fk(t,e,r){let s=r?.syncTransports?.[t.howToRun]??xk[t.howToRun];return s?s(t,e,r):vi(`[${r?.label??"invokeExecutionRefSync"}] unsupported sync howToRun: ${t.howToRun}`)}function Kk(t,e,r){return Fk(t,e,r)}function Uk(t,e){if(process.platform!=="win32"){K.renameSync(t,e);return}let r=[10,20,40,80,160];for(let s=0;s<=r.length;s++)try{K.renameSync(t,e);return}catch(n){let i=n.code;if((i==="EPERM"||i==="EBUSY")&&s<r.length){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,r[s]);continue}throw n}}function Vk(t){function e(s){return z.join(t,...s.split("/"))+".json"}function r(s,n,i,a){if(K.existsSync(s))for(let o of K.readdirSync(s,{withFileTypes:!0})){let c=n?`${n}/${o.name}`:o.name;if(o.isDirectory()){r(z.join(s,o.name),c,i,a);continue}if(!o.isFile()||!o.name.endsWith(".json"))continue;let l=c.replace(/\.json$/,"");(!i||l.startsWith(i))&&a.push(l)}}return{read(s){let n=e(s);if(!K.existsSync(n))return null;try{return JSON.parse(K.readFileSync(n,"utf-8"))}catch{return null}},write(s,n){let i=e(s),a=`${i}.${process.pid}.${F1()}.tmp`;K.mkdirSync(z.dirname(i),{recursive:!0}),K.writeFileSync(a,JSON.stringify(n,null,2),"utf-8"),Uk(a,i)},delete(s){let n=e(s);try{K.existsSync(n)&&K.unlinkSync(n)}catch{}},listKeys(s){let n=[];return r(t,"",s,n),n.sort()}}}var Om=class extends Error{constructor(t,e){super(e),this.code=t,this.name="CliExitError"}code},Bk=".pause",zk=3e5,Jk="YAML_FLOW_STEP_INVOKE_TIMEOUT_MS";async function iP(t){let e=Yk(t);if(e.help||t.length===0)throw rN(),new Om(t.length===0?1:0);let{flowArg:r,dataArg:s,persistRuntimeRefArg:n,resumeRequested:i,pauseRequested:a,statusRequested:o}=e;if((a||o)&&(s||i||r))throw new Error("[step-machine-cli] --pause and --status are store-level operations. Do not provide flow, data, or --resume.");if(i&&s)throw new Error("[step-machine-cli] --initial-data cannot be combined with --resume.");let c=Gk(n);if(o){await Qk(c);return}if(a){await Hk(c);return}if(!r)throw new Error("[step-machine-cli] Flow path is required for run/resume operations.");let l=xm(r),u=z.dirname(l),f=Xk(s),{store:d}=c,p=await X1(l),m=tN(p,u);Tm(c);let h=new AbortController,y=!1,g=G1(p,m,{store:d,signal:h.signal,onStep:()=>{!y&&hl(c)&&(y=!0,h.abort())}}),b;if(i){if(b=await Pm(c),!b){console.warn("[step-machine-cli] No paused run found in the persisted runtime store."),console.log(JSON.stringify({status:"noop",reason:"no-paused-run"},null,2));return}}else c.storeType==="file"&&!f&&(b=await Pm(c));let v=b?await g.resume(b):await g.run(f);if(y&&v.status==="cancelled"){let _=await Wk(d,v.runId);Tm(c),console.log(JSON.stringify({runId:v.runId,status:"paused",currentStep:_?.currentStep,pausedAt:_?.pausedAt,stepHistory:v.stepHistory,data:v.data},null,2));return}if(v.status!=="completed"){let _=v.error?.message??v.intent??v.status;throw console.error(`[step-machine-cli] Run failed: ${_}`),new Om(1)}console.log(JSON.stringify({runId:v.runId,status:v.status,intent:v.intent,finalStep:v.finalStep,stepHistory:v.stepHistory,data:v.data},null,2))}function Yk(t){let e=new Set(["--initial-data","--persist-runtime-ref"]),r={},s=[],n=!1,i=!1,a=!1,o=!1;for(let c=0;c<t.length;c++){let l=t[c];if(l==="-h"||l==="--help"){n=!0;continue}if(l==="--resume"){i=!0;continue}if(l==="--pause"){a=!0;continue}if(l==="--status"){o=!0;continue}if(e.has(l)){let u=t[c+1];if(!u||u.startsWith("--"))throw new Error(`[step-machine-cli] Missing value for ${l}.`);r[l]=u,c++;continue}if(l.startsWith("--"))throw new Error(`[step-machine-cli] Unknown flag: ${l}`);s.push(l)}if([i,a,o].filter(Boolean).length>1)throw new Error("[step-machine-cli] Use only one of --resume, --pause, or --status at a time.");return{help:n,flowArg:s[0],dataArg:r["--initial-data"],persistRuntimeRefArg:r["--persist-runtime-ref"],resumeRequested:i,pauseRequested:a,statusRequested:o}}function xm(t){return z.isAbsolute(t)?t:z.resolve(process.cwd(),t)}function Gk(t){if(!t)return{storeType:"memory",storeDir:void 0,pauseFilePath:void 0,persistRuntimeRef:void 0,store:new jm};let e=Dm(t);if(e.kind!=="fs-path")throw new Error(`[step-machine-cli] --persist-runtime-ref must be an fs-path ref. Received kind "${e.kind}".`);let r=xm(e.value),s=ll({kind:"fs-path",value:r});return{storeType:"file",storeDir:r,pauseFilePath:z.join(r,Bk),persistRuntimeRef:s,store:new Z1(Vk(r))}}async function dl(t){if(!t.listRuns)return[];let e=await t.listRuns(),r=[];for(let s of e){let n=await t.loadRunState(s);n&&r.push(n)}return r.sort((s,n)=>(n.updatedAt??n.startedAt??0)-(s.updatedAt??s.startedAt??0)),r}function hl(t){return t.storeType!=="file"||!t.pauseFilePath?!1:K.existsSync(t.pauseFilePath)}function Tm(t){hl(t)&&K.unlinkSync(t.pauseFilePath)}async function Hk(t){if(t.storeType!=="file"||!t.pauseFilePath)throw new Error("[step-machine-cli] --pause requires --persist-runtime-ref <ref>.");let e=await dl(t.store);if(e.length===0){console.warn("[step-machine-cli] No runs found in the persisted runtime store. Pause is a no-op."),console.log(JSON.stringify({status:"noop",reason:"no-runs"},null,2));return}if(!e.find(r=>r.status==="running")){console.warn("[step-machine-cli] No running run found. Pause is a no-op."),console.log(JSON.stringify({status:"noop",reason:"no-running-run"},null,2));return}K.mkdirSync(t.storeDir,{recursive:!0}),K.writeFileSync(t.pauseFilePath,JSON.stringify({requestedAt:Date.now()}),"utf-8"),console.log(JSON.stringify({status:"pause-requested",persistRuntimeRef:t.persistRuntimeRef},null,2))}async function Pm(t){let e=(await dl(t.store)).filter(r=>r.status==="paused");if(e.length!==0)return e.length>1&&console.warn("[step-machine-cli] Multiple paused runs found; resuming the most recently updated run."),e[0].runId}async function Wk(t,e){let r=await t.loadRunState(e);if(!r)return null;let s={...r,status:"paused",pausedAt:Date.now(),updatedAt:Date.now()};return await t.saveRunState(e,s),s}async function Qk(t){if(t.storeType!=="file")throw new Error("[step-machine-cli] --status requires --persist-runtime-ref <ref>.");let e=await dl(t.store),r={store:"file",persistRuntimeRef:t.persistRuntimeRef,pauseRequested:hl(t),totalRuns:e.length,runs:e.map(s=>({runId:s.runId,status:s.status,currentStep:s.currentStep,startedAt:s.startedAt,updatedAt:s.updatedAt,pausedAt:s.pausedAt}))};console.log(JSON.stringify(r,null,2))}function Xk(t){if(t)try{let e=JSON.parse(t);if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Initial data must be a JSON object.");return e}catch(e){let r=e instanceof Error?e.message:String(e);throw new Error(`[step-machine-cli] Invalid --initial-data value: ${r}`)}}function Zk(t){if(!t||typeof t!="object")return t;let e=t;if(typeof e.whatToRun!="string"||!e.whatToRun.startsWith("b64:"))return t;try{let r=e.whatToRun.slice(4),s=r+"=".repeat((4-r.length%4)%4),n=Buffer.from(s.replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8"),i=JSON.parse(n);return!i||typeof i!="object"||typeof i.value!="string"?t:{...e,whatToRun:i}}catch{return t}}function eN(t){let e=t.settings?.invoke_timeout_ms;if(typeof e=="number"&&Number.isFinite(e)&&e>=0)return Math.trunc(e);let r=process.env[Jk];if(r){let s=Number(r);if(Number.isFinite(s)&&s>=0)return Math.trunc(s)}return zk}function tN(t,e){let r=eN(t);return _k(t,{invoke:(s,n)=>Kk(Zk(s),n,{cliDir:e,cwd:e,timeoutMs:r})})}function rN(){console.error("Usage: step-machine-cli <step-flow.yaml> [--initial-data <json>] [--persist-runtime-ref <ref>] [--resume]"),console.error(" step-machine-cli --persist-runtime-ref <ref> --pause"),console.error(" step-machine-cli --persist-runtime-ref <ref> --status"),console.error(""),console.error("Example:"),console.error(' step-machine-cli examples/cli/step-machine-demo/two-step-math.flow.yaml --initial-data "{"a":3,"b":4}"'),console.error(" step-machine-cli ./flow.yaml --persist-runtime-ref <b64-fs-path-ref>"),console.error(" step-machine-cli ./flow.yaml --persist-runtime-ref <b64-fs-path-ref> --resume"),console.error(" step-machine-cli --persist-runtime-ref <b64-fs-path-ref> --pause"),console.error(" step-machine-cli --persist-runtime-ref <b64-fs-path-ref> --status")}export{Om as CliExitError,iP as cli,eN as resolveStepInvokeTimeoutMs};
150
+ - `)}`);return e}function ol(t){return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function $m(t){return atob(t.replace(/-/g,"+").replace(/_/g,"/"))}var Z1=class{constructor(t){this.kv=t}kv;stateKey(t){return`state_${ol(t)}`}dataPrefix(t){return`data_${ol(t)}_`}dataKey(t,e){return`${this.dataPrefix(t)}${ol(e)}`}async saveRunState(t,e){this.kv.write(this.stateKey(t),e)}async loadRunState(t){let e=this.kv.read(this.stateKey(t));return e!=null&&typeof e=="object"?e:null}async deleteRunState(t){this.kv.delete(this.stateKey(t));for(let e of this.kv.listKeys(this.dataPrefix(t)))this.kv.delete(e)}async setData(t,e,r){this.kv.write(this.dataKey(t,e),r)}async getData(t,e){return this.kv.read(this.dataKey(t,e))}async getAllData(t){let e=this.dataPrefix(t),r={};for(let s of this.kv.listKeys(e))r[$m(s.slice(e.length))]=this.kv.read(s);return r}async clearData(t){for(let e of this.kv.listKeys(this.dataPrefix(t)))this.kv.delete(e)}async listRuns(){return this.kv.listKeys("state_").map(t=>$m(t.slice(6)))}},Em=Am(Im(import.meta.url)),ek=cl(import.meta.url);function tk(){let t=bi(Em,"./jsonata-sync.cjs");return qm(t)?t:bi(Em,"../card-compute/jsonata-sync.cjs")}var Rm=ek(tk());function rk(t,e){if(!t||typeof t!="object")throw new Error(`[step-machine-public] Step "${e}" returned a non-object result.`);let r=t,s=r.result??r.status;if(typeof s=="string"&&s.trim().length>0){let n=r.data&&typeof r.data=="object"&&!Array.isArray(r.data)?{...r.data}:{},i=typeof r.error=="string"?r.error:void 0;return i&&!("error"in n)&&(n.error=i),{result:s,data:n,...i?{error:i}:{}}}return{result:"success",data:{...r}}}function sk(t,e){if(!e||e.length===0)return t;let r={};for(let s of e)Object.prototype.hasOwnProperty.call(t,s)&&(r[s]=t[s]);return r}function nk(t,e){return async(r,s)=>{let n=await t(r,s),i=rk(n,s?.stepName??"unknown");return{result:i.result,data:sk(i.data,e),...i.error?{error:i.error}:{}}}}function ik(t,e,r){if(!e||e.length===0)return null;for(let s of e)try{if(!Rm(s).evaluate(t))return{result:"failure",data:{error:`[${r}] input validation failed: ${s}`}}}catch(n){let i=n instanceof Error?n.message:String(n);return{result:"failure",data:{error:`[${r}] input validation error on "${s}": ${i}`}}}return null}function ak(t,e,r){return!e||e.length===0?t:async(s,n)=>ik(s,e,r)||t(s,n)}var km=Am(Im(import.meta.url)),ok=cl(import.meta.url);function ck(){let t=bi(km,"./jsonata-sync.cjs");return qm(t)?t:bi(km,"../../card-compute/jsonata-sync.cjs")}var wt=ok(ck()),wi="b64:";function lk(t){let e=new TextEncoder().encode(t),r=globalThis.Buffer,s;if(r)s=r.from(e).toString("base64");else if(typeof btoa=="function"){let n="";for(let i of e)n+=String.fromCharCode(i);s=btoa(n)}else throw new Error("No base64 encoder available in this runtime");return s.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function uk(t){let e=t.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-t.length%4)%4),r=globalThis.Buffer;if(r)return r.from(e,"base64").toString("utf8");if(typeof atob=="function"){let s=atob(e),n=new Uint8Array(s.length);for(let i=0;i<s.length;i+=1)n[i]=s.charCodeAt(i);return new TextDecoder().decode(n)}throw new Error("No base64 decoder available in this runtime")}function ll(t){return`${wi}${lk(JSON.stringify(t))}`}function Dm(t){if(!t.startsWith(wi))throw new Error(`Invalid ref format (expected ${wi}<base64url(json)>): ${t}`);let e;try{e=JSON.parse(uk(t.slice(wi.length)))}catch{throw new Error(`Invalid ref format (malformed base64url/json): ${t}`)}if(!e||typeof e!="object")throw new Error(`Invalid ref format (expected object payload): ${t}`);let r=e;if(typeof r.kind!="string"||typeof r.value!="string")throw new Error(`Invalid ref format (payload must contain string kind/value): ${t}`);return{kind:r.kind,value:r.value}}function vt(t){t.registerFunction("fsPathRef",e=>ll({kind:"fs-path",value:String(e)}),"<s:s>")}function fk(t,e,r){if(!t||typeof t!="object")return{};let s={};if(Array.isArray(t.cmdTemplate)){let n=[];for(let i of t.cmdTemplate)try{let a=wt(i);vt(a),n.push(String(a.evaluate(e)))}catch(a){let o=a instanceof Error?a.message:String(a);throw new Error(`[${r}] argsMassaging.cmdTemplate failed on "${i}": ${o}`)}s.cmdArgs=n}if(typeof t.stdinTemplate=="string")try{let n=wt(t.stdinTemplate);vt(n),s.stdin=n.evaluate(e)}catch(n){let i=n instanceof Error?n.message:String(n);throw new Error(`[${r}] argsMassaging.stdinTemplate failed: ${i}`)}if(typeof t.urlTemplate=="string")try{let n=wt(t.urlTemplate);vt(n),s.url=String(n.evaluate(e))}catch(n){let i=n instanceof Error?n.message:String(n);throw new Error(`[${r}] argsMassaging.urlTemplate failed: ${i}`)}if(typeof t.headerTemplate=="string")try{let n=wt(t.headerTemplate);vt(n);let i=n.evaluate(e);if(typeof i!="object"||i===null)throw new Error(`headerTemplate must produce an object, got: ${JSON.stringify(i)}`);s.headers=i}catch(n){let i=n instanceof Error?n.message:String(n);throw new Error(`[${r}] argsMassaging.headerTemplate failed: ${i}`)}if(typeof t.bodyTemplate=="string")try{let n=wt(t.bodyTemplate);vt(n),s.body=n.evaluate(e)}catch(n){let i=n instanceof Error?n.message:String(n);throw new Error(`[${r}] argsMassaging.bodyTemplate failed: ${i}`)}return s}function dk(t,e,r){if(!t||typeof t!="object")return e;let s={output:e},n=e.result,i=e.data,a=e.error;if(typeof t.resultExpr=="string")try{let o=wt(t.resultExpr);vt(o);let c=o.evaluate(s);if(typeof c!="string"||!c.trim())throw new Error(`resultExpr did not produce a non-empty string (got ${JSON.stringify(c)})`);n=c}catch(o){let c=o instanceof Error?o.message:String(o);throw new Error(`[${r}] outputTransforms.resultExpr failed: ${c}`)}if(typeof t.dataTemplate=="string")try{let o=wt(t.dataTemplate);vt(o);let c=o.evaluate(s);if(!c||typeof c!="object"||Array.isArray(c))throw new Error(`dataTemplate did not produce an object (got ${JSON.stringify(c)})`);i=c}catch(o){let c=o instanceof Error?o.message:String(o);throw new Error(`[${r}] outputTransforms.dataTemplate failed: ${c}`)}if(typeof t.errorExpr=="string")try{let o=wt(t.errorExpr);vt(o);let c=o.evaluate(s);a=c!=null?String(c):void 0}catch(o){let c=o instanceof Error?o.message:String(o);throw new Error(`[${r}] outputTransforms.errorExpr failed: ${c}`)}return a!==void 0?{result:n,data:i,error:a}:{result:n,data:i}}function hk(t){return!!t&&typeof t=="object"&&t.type==="compute-jsonata"&&Array.isArray(t.expr)&&t.expr.length>0}function pk(t){if(!t||typeof t!="object")return!1;let e=t;if(e.type!=="ref"||typeof e.howToRun!="string")return!1;if(typeof e.whatToRun=="string")return!0;if(e.whatToRun&&typeof e.whatToRun=="object"){let r=e.whatToRun;return typeof r.kind=="string"&&typeof r.value=="string"}return!1}function mk(t){if(typeof t=="string"){let e=t.indexOf("=");if(e<1)throw new Error(`[step-machine-public] Invalid compute expression (missing "="): "${t}"`);return{bindTo:t.slice(0,e).trim(),expr:t.slice(e+1).trim()}}if(t&&typeof t=="object"&&typeof t.bindTo=="string"&&typeof t.expr=="string")return t;throw new Error(`[step-machine-public] Invalid compute step: ${JSON.stringify(t)}`)}function yk(t,e,r){let s=e.split("."),n=t;for(let i=0;i<s.length-1;i++){let a=s[i];(n[a]==null||typeof n[a]!="object")&&(n[a]={}),n=n[a]}n[s[s.length-1]]=r}function gk(t,e,r){let s=t.expr.map(mk);return async n=>{let i=n&&typeof n=="object"&&!Array.isArray(n)?{...n}:{},a={},o={expects_data:i,data:a,...r?{config:r}:{}},c,l;for(let u of s)try{let f=Rm(u.expr).evaluate(o);if(u.bindTo==="result")c=f!=null?String(f):"success";else if(u.bindTo==="error")l=f!=null?String(f):void 0;else if(u.bindTo.startsWith("data."))yk(a,u.bindTo.slice(5),f);else return{result:"failure",data:{},error:`[${e}] invalid bindTo "${u.bindTo}": must be "result", "error", or start with "data."`}}catch(f){let d=f instanceof Error?f.message:String(f);return{result:"failure",data:{},error:`[${e}] compute "${u.bindTo}" failed: ${d}`}}return c===void 0?{result:"failure",data:{},error:`[${e}] compute-jsonata: no "result" binding declared \u2014 add '- result = "success"' to expr`}:l?{result:c,data:a,error:l}:{result:c,data:a}}}function wk(t,e,r,s){let{type:n,...i}=t,a={...i,whatToRun:typeof i.whatToRun=="object"?ll(i.whatToRun):i.whatToRun};return async o=>{let c=o&&typeof o=="object"&&!Array.isArray(o)?{...o}:{};s&&(c.config=s);try{let l=await r(a,c);if(!t.outputTransforms)return l;try{return dk(t.outputTransforms,l,e)}catch(u){let f=u instanceof Error?u.message:String(u);return{result:"failure",data:{},error:f}}}catch(l){let u=l instanceof Error?l.message:String(l);return{result:"failure",data:{error:`[step-machine-public] step "${e}" invoke threw: ${u}`}}}}}function vk(){return async t=>({result:"success",data:t&&typeof t=="object"&&!Array.isArray(t)?t:{}})}function bk(t,e,r){return async(s,n)=>{let i=s?.[e.items];if(!Array.isArray(i))return{result:"failure",data:{},error:`[${r}] forEach: "${e.items}" is not an array (got ${typeof i})`};let a=i,o=e.collectAs??`${e.items}_results`;if(a.length===0)return{result:"success",data:{[o]:[]}};let{[e.items]:c,...l}=s,u=Math.max(1,e.concurrency??1),f=new Array(a.length),d=0,p=0,m=0;return await new Promise(h=>{function y(){for(;d<u&&p<a.length;){let g=p++;d++;let b={...l,[e.as]:a[g]};t(b,n).then(v=>{f[g]=v}).catch(v=>{let _=v instanceof Error?v.message:String(v);f[g]={result:"failure",data:{},error:_}}).finally(()=>{d--,f[g]?.result==="failure"&&m++,p>=a.length&&d===0?h():y()})}d===0&&p>=a.length&&h()}y()}),m>0?{result:"failure",data:{errors:f.filter(h=>h.result==="failure").map(h=>h.error)},error:`[${r}] forEach: ${m}/${a.length} items failed`}:{result:"success",data:{[o]:f.map(h=>h.data)}}}}function Sk(t,e,r){let s=Array.isArray(e?.produces_data)?e?.produces_data:void 0,n=Array.isArray(e?.input_validations)?e?.input_validations:void 0,i=e?.config??void 0,a=e?.handler,o;return hk(a)?o=gk(a,t,i):pk(a)?o=wk(a,t,r.invoke,i):o=vk(),e?.forEach&&(o=bk(o,e.forEach,t)),ak(nk(o,s),n,t)}function _k(t,e){let r={};for(let[s,n]of Object.entries(t.steps??{}))r[s]=Sk(s,n,e);return r}function $k(t){if(typeof t=="object"&&t!==null){let{command:r,args:s=[],...n}=t,i=Nm(r,s);return{...n,command:i.command,args:i.args}}let e=Lm(t);if(e.length===0)throw new Error(`Empty command spec: ${JSON.stringify(t)}`);return Nm(e[0],e.slice(1))}function Nm(t,e){return/^(node|node\.exe)$/i.test(t)?{command:process.execPath,args:e}:/\.m?js$/i.test(t)?{command:process.execPath,args:[t,...e]}:{command:t,args:e}}function Lm(t){let e=[],r="",s=null;for(let n of t.trim()){if(s){n===s?s=null:r+=n;continue}if(n==='"'||n==="'"){s=n;continue}if(/\s/.test(n)){r&&(e.push(r),r="");continue}r+=n}if(s)throw new Error(`Unterminated quote in command: ${t}`);return r&&e.push(r),e}function ul(t){return process.platform==="win32"&&/\.(cmd|bat)$/i.test(t)}function Ek(t,e){let{command:r,args:s=[],cwd:n,env:i,timeoutMs:a}=t;return x1(r,s,{shell:ul(r),timeout:a,encoding:e?.encoding??"utf-8",cwd:n,windowsHide:!0,env:i?{...process.env,...i}:void 0,input:e?.input})}function kk(t,e){let{command:r,args:s=[],cwd:n,env:i,timeoutMs:a=3e4}=t;L1(r,s,{shell:ul(r),encoding:"utf8",windowsHide:!0,timeout:a,maxBuffer:10*1024*1024,cwd:n,env:i?{...process.env,...i}:void 0},(o,c,l)=>e(o??null,c,l))}z.join(Cm.tmpdir(),".board-live-cards-git-bash-cache.json");function Nk(t){let{command:e,args:r=[]}=t;if(process.platform==="win32"){_m(e,r,{stdio:"ignore",windowsHide:!0,shell:ul(e)}).unref();return}_m(e,r,{detached:!0,stdio:"ignore"}).unref()}function Ok(t,e,r){let s=z.join(t,"board-live-cards-cli.js");if(K.existsSync(s))return{cmd:process.execPath,args:[s,e,...r]};let n=z.join(t,"board-live-cards-cli.ts"),i=[z.join(t,"..","..","..","node_modules","tsx","dist","cli.mjs"),z.join(t,"..","..","node_modules","tsx","dist","cli.mjs"),z.join(t,"..","..","..","node_modules",".bin","tsx"),z.join(t,"..","..","node_modules",".bin","tsx")].find(a=>K.existsSync(a));return K.existsSync(n)&&K.existsSync(i)?{cmd:process.execPath,args:[i,n,e,...r]}:{cmd:process.platform==="win32"?"npx.cmd":"npx",args:["tsx",n,e,...r]}}function Tk(){return{executeSync(t,e,r){return Ek({command:t,args:e,cwd:r?.cwd,timeoutMs:r?.timeout,env:r?.env},{encoding:r?.encoding,input:r?.input})},executeAsync(t,e,r){kk({command:t,args:e},r)},resolveInvocation(t,e){let r=$k({command:t,args:e});return{cmd:r.command,args:r.args??[]}},splitCommand:Lm,spawnDetached(t,e){Nk({command:t,args:e})}}}var Pk=cl(import.meta.url);function qk(t){return typeof t=="object"?t:Dm(t)}function Ak(t){let e=z.basename(String(t||"").trim());if(!e)throw new Error(`resolveYamlFlowCliPath: expected non-empty cli file name, got ${JSON.stringify(t)}`);let r=z.dirname(Pk.resolve("yaml-flow/package.json")),s=e.replace(/\.[^.]+$/,""),n=z.join(r,"cli","bundled",`${s}.mjs`);if(K.existsSync(n))return n;let i=z.join(r,"cli","node",e);if(K.existsSync(i))return i;throw new Error(`resolveYamlFlowCliPath: could not find ${e} under cli/bundled or cli/node in ${r}`)}function fl(t){let e=qk(t);return e.kind==="yaml-flow-cli"?Ak(e.value):e.value}function Ik(t,e){let r=fl(t);switch(r){case"source-cli-task-executor":{let s=z.join(e,"source-cli-task-executor.js");if(K.existsSync(s))return{command:process.execPath,args:[s]};let n=z.join(e,"source-cli-task-executor.ts"),i=z.join(e,"..","..","node_modules","tsx","dist","cli.mjs"),a=z.join(e,"..","..","node_modules",".bin","tsx"),o=K.existsSync(i)?i:a;return K.existsSync(n)&&K.existsSync(o)?{command:process.execPath,args:[o,n]}:{command:process.execPath,args:[s]}}case"board-live-cards":{let{cmd:s,args:n}=Ok(e,"_",[]);return{command:s,args:n}}default:throw new Error(`resolveBuiltIn: unknown built-in name "${r}". Supported: source-cli-task-executor, board-live-cards`)}}function Ck(t,e){if(t.howToRun==="built-in"){let{command:s,args:n}=Ik(t.whatToRun,e);return{command:s,baseArgs:n}}let r=(t.whatToRun,fl(t.whatToRun));switch(t.howToRun){case"local-node":return{command:process.execPath,baseArgs:[r]};case"local-python":return{command:process.platform==="win32"?"python":"python3",baseArgs:[r]};case"local-process":return{command:r,baseArgs:[]};default:throw new Error(`resolveBaseInvocation: howToRun "${t.howToRun}" is not a local transport`)}}function jk(t,e){return Ck(t,e)}function Mk(t){let e=t.trim();if(!e)throw new Error("empty stdout");try{return JSON.parse(e)}catch{let r=e.split(/\r?\n/).filter(Boolean),s=r[r.length-1];return JSON.parse(s)}}function Rk(t,e){return{...e,whatToRun:fl(t.whatToRun),...t.extra?{extra:t.extra}:{}}}function Dk(t,e,r="invokeExecutionRef"){return fk(t,e,r)}function Lk(t){return t&&typeof t=="object"&&!Array.isArray(t)&&typeof t.result=="string"&&t.data&&typeof t.data=="object"&&!Array.isArray(t.data)?t:{result:"success",data:t&&typeof t=="object"&&!Array.isArray(t)?t:{stdout:t}}}function vi(t){return{result:"failure",data:{error:t}}}function gi(t,e,r){let s=r?.label??"invokeExecutionRefSync",n=r?.cliDir??r?.cwd??process.cwd(),i;try{i=Dk(t.argsMassaging,Rk(t,e),s)}catch(f){let d=f instanceof Error?f.message:String(f);return vi(d)}let a;try{a=jk(t,n)}catch(f){let d=f instanceof Error?f.message:String(f);return vi(`[${s}] ref resolution failed: ${d}`)}let o=[...a.baseArgs,...i.cmdArgs??[]],c=JSON.stringify(i.stdin??e),l=Tk(),u;try{u=l.executeSync(a.command,o,{timeout:r?.timeoutMs??3e4,encoding:"utf-8",cwd:r?.cwd,input:c})}catch(f){let d=f,p=(d.stderr?String(d.stderr):"").trim(),m=typeof d.status=="number"?d.status:"unknown",h=p||d.message;return vi(`[${s}] ref exited with status ${m}${h?`: ${h}`:""}`)}try{return Lk(Mk(u))}catch{return{result:"success",data:{stdout:u.trim()}}}}var xk={"local-node":gi,"local-python":gi,"local-process":gi,"built-in":gi};function Fk(t,e,r){let s=r?.syncTransports?.[t.howToRun]??xk[t.howToRun];return s?s(t,e,r):vi(`[${r?.label??"invokeExecutionRefSync"}] unsupported sync howToRun: ${t.howToRun}`)}function Kk(t,e,r){return Fk(t,e,r)}function Uk(t,e){if(process.platform!=="win32"){K.renameSync(t,e);return}let r=[10,20,40,80,160];for(let s=0;s<=r.length;s++)try{K.renameSync(t,e);return}catch(n){let i=n.code;if((i==="EPERM"||i==="EBUSY")&&s<r.length){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,r[s]);continue}throw n}}function Vk(t){function e(s){return z.join(t,...s.split("/"))+".json"}function r(s,n,i,a){if(K.existsSync(s))for(let o of K.readdirSync(s,{withFileTypes:!0})){let c=n?`${n}/${o.name}`:o.name;if(o.isDirectory()){r(z.join(s,o.name),c,i,a);continue}if(!o.isFile()||!o.name.endsWith(".json"))continue;let l=c.replace(/\.json$/,"");(!i||l.startsWith(i))&&a.push(l)}}return{read(s){let n=e(s);if(!K.existsSync(n))return null;try{return JSON.parse(K.readFileSync(n,"utf-8"))}catch{return null}},write(s,n){let i=e(s),a=`${i}.${process.pid}.${F1()}.tmp`;K.mkdirSync(z.dirname(i),{recursive:!0}),K.writeFileSync(a,JSON.stringify(n,null,2),"utf-8"),Uk(a,i)},delete(s){let n=e(s);try{K.existsSync(n)&&K.unlinkSync(n)}catch{}},listKeys(s){let n=[];return r(t,"",s,n),n.sort()}}}var Om=class extends Error{constructor(t,e){super(e),this.code=t,this.name="CliExitError"}code},Bk=".pause",zk=3e5,Jk="YAML_FLOW_STEP_INVOKE_TIMEOUT_MS";async function iP(t){let e=Yk(t);if(e.help||t.length===0)throw rN(),new Om(t.length===0?1:0);let{flowArg:r,dataArg:s,persistRuntimeRefArg:n,resumeRequested:i,pauseRequested:a,statusRequested:o}=e;if((a||o)&&(s||i||r))throw new Error("[step-machine-cli] --pause and --status are store-level operations. Do not provide flow, data, or --resume.");if(i&&s)throw new Error("[step-machine-cli] --initial-data cannot be combined with --resume.");let c=Gk(n);if(o){await Qk(c);return}if(a){await Hk(c);return}if(!r)throw new Error("[step-machine-cli] Flow path is required for run/resume operations.");let l=xm(r),u=z.dirname(l),f=Xk(s),{store:d}=c,p=await X1(l),m=tN(p,u);Tm(c);let h=new AbortController,y=!1,g=G1(p,m,{store:d,signal:h.signal,onStep:()=>{!y&&hl(c)&&(y=!0,h.abort())}}),b;if(i){if(b=await Pm(c),!b){console.warn("[step-machine-cli] No paused run found in the persisted runtime store."),console.log(JSON.stringify({status:"noop",reason:"no-paused-run"},null,2));return}}else c.storeType==="file"&&!f&&(b=await Pm(c));let v=b?await g.resume(b):await g.run(f);if(y&&v.status==="cancelled"){let _=await Wk(d,v.runId);Tm(c),console.log(JSON.stringify({runId:v.runId,status:"paused",currentStep:_?.currentStep,pausedAt:_?.pausedAt,stepHistory:v.stepHistory,data:v.data},null,2));return}if(v.status!=="completed"){let _=v.error?.message??v.intent??v.status;throw console.error(`[step-machine-cli] Run failed: ${_}`),new Om(1)}console.log(JSON.stringify({runId:v.runId,status:v.status,intent:v.intent,finalStep:v.finalStep,stepHistory:v.stepHistory,data:v.data},null,2))}function Yk(t){let e=new Set(["--initial-data","--persist-runtime-ref"]),r={},s=[],n=!1,i=!1,a=!1,o=!1;for(let c=0;c<t.length;c++){let l=t[c];if(l==="-h"||l==="--help"){n=!0;continue}if(l==="--resume"){i=!0;continue}if(l==="--pause"){a=!0;continue}if(l==="--status"){o=!0;continue}if(e.has(l)){let u=t[c+1];if(!u||u.startsWith("--"))throw new Error(`[step-machine-cli] Missing value for ${l}.`);r[l]=u,c++;continue}if(l.startsWith("--"))throw new Error(`[step-machine-cli] Unknown flag: ${l}`);s.push(l)}if([i,a,o].filter(Boolean).length>1)throw new Error("[step-machine-cli] Use only one of --resume, --pause, or --status at a time.");return{help:n,flowArg:s[0],dataArg:r["--initial-data"],persistRuntimeRefArg:r["--persist-runtime-ref"],resumeRequested:i,pauseRequested:a,statusRequested:o}}function xm(t){return z.isAbsolute(t)?t:z.resolve(process.cwd(),t)}function Gk(t){if(!t)return{storeType:"memory",storeDir:void 0,pauseFilePath:void 0,persistRuntimeRef:void 0,store:new jm};let e=Dm(t);if(e.kind!=="fs-path")throw new Error(`[step-machine-cli] --persist-runtime-ref must be an fs-path ref. Received kind "${e.kind}".`);let r=xm(e.value),s=ll({kind:"fs-path",value:r});return{storeType:"file",storeDir:r,pauseFilePath:z.join(r,Bk),persistRuntimeRef:s,store:new Z1(Vk(r))}}async function dl(t){if(!t.listRuns)return[];let e=await t.listRuns(),r=[];for(let s of e){let n=await t.loadRunState(s);n&&r.push(n)}return r.sort((s,n)=>(n.updatedAt??n.startedAt??0)-(s.updatedAt??s.startedAt??0)),r}function hl(t){return t.storeType!=="file"||!t.pauseFilePath?!1:K.existsSync(t.pauseFilePath)}function Tm(t){hl(t)&&K.unlinkSync(t.pauseFilePath)}async function Hk(t){if(t.storeType!=="file"||!t.pauseFilePath)throw new Error("[step-machine-cli] --pause requires --persist-runtime-ref <ref>.");let e=await dl(t.store);if(e.length===0){console.warn("[step-machine-cli] No runs found in the persisted runtime store. Pause is a no-op."),console.log(JSON.stringify({status:"noop",reason:"no-runs"},null,2));return}if(!e.find(r=>r.status==="running")){console.warn("[step-machine-cli] No running run found. Pause is a no-op."),console.log(JSON.stringify({status:"noop",reason:"no-running-run"},null,2));return}K.mkdirSync(t.storeDir,{recursive:!0}),K.writeFileSync(t.pauseFilePath,JSON.stringify({requestedAt:Date.now()}),"utf-8"),console.log(JSON.stringify({status:"pause-requested",persistRuntimeRef:t.persistRuntimeRef},null,2))}async function Pm(t){let e=(await dl(t.store)).filter(r=>r.status==="paused");if(e.length!==0)return e.length>1&&console.warn("[step-machine-cli] Multiple paused runs found; resuming the most recently updated run."),e[0].runId}async function Wk(t,e){let r=await t.loadRunState(e);if(!r)return null;let s={...r,status:"paused",pausedAt:Date.now(),updatedAt:Date.now()};return await t.saveRunState(e,s),s}async function Qk(t){if(t.storeType!=="file")throw new Error("[step-machine-cli] --status requires --persist-runtime-ref <ref>.");let e=await dl(t.store),r={store:"file",persistRuntimeRef:t.persistRuntimeRef,pauseRequested:hl(t),totalRuns:e.length,runs:e.map(s=>({runId:s.runId,status:s.status,currentStep:s.currentStep,startedAt:s.startedAt,updatedAt:s.updatedAt,pausedAt:s.pausedAt}))};console.log(JSON.stringify(r,null,2))}function Xk(t){if(t)try{let e=JSON.parse(t);if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Initial data must be a JSON object.");return e}catch(e){let r=e instanceof Error?e.message:String(e);throw new Error(`[step-machine-cli] Invalid --initial-data value: ${r}`)}}function Zk(t){if(!t||typeof t!="object")return t;let e=t;if(typeof e.whatToRun!="string"||!e.whatToRun.startsWith("b64:"))return t;try{let r=e.whatToRun.slice(4),s=r+"=".repeat((4-r.length%4)%4),n=Buffer.from(s.replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8"),i=JSON.parse(n);return!i||typeof i!="object"||typeof i.value!="string"?t:{...e,whatToRun:i}}catch{return t}}function eN(t){let e=t.settings?.invoke_timeout_ms;if(typeof e=="number"&&Number.isFinite(e)&&e>=0)return Math.trunc(e);let r=process.env[Jk];if(r){let s=Number(r);if(Number.isFinite(s)&&s>=0)return Math.trunc(s)}return zk}function tN(t,e){let r=eN(t);return _k(t,{invoke:(s,n)=>Kk(Zk(s),n,{cliDir:e,cwd:e,timeoutMs:r})})}function rN(){console.error("Usage: step-machine-cli <step-flow.yaml> [--initial-data <json>] [--persist-runtime-ref <ref>] [--resume]"),console.error(" step-machine-cli --persist-runtime-ref <ref> --pause"),console.error(" step-machine-cli --persist-runtime-ref <ref> --status"),console.error(""),console.error("Example:"),console.error(' step-machine-cli examples/cli/step-machine-demo/two-step-math.flow.yaml --initial-data "{"a":3,"b":4}"'),console.error(" step-machine-cli ./flow.yaml --persist-runtime-ref <b64-fs-path-ref>"),console.error(" step-machine-cli ./flow.yaml --persist-runtime-ref <b64-fs-path-ref> --resume"),console.error(" step-machine-cli --persist-runtime-ref <b64-fs-path-ref> --pause"),console.error(" step-machine-cli --persist-runtime-ref <b64-fs-path-ref> --status")}export{Om as CliExitError,iP as cli,eN as resolveStepInvokeTimeoutMs};
@@ -19,8 +19,8 @@
19
19
  <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
20
20
  <script src="https://cdn.jsdelivr.net/npm/dompurify/dist/purify.min.js"></script>
21
21
  <script src="https://cdn.jsdelivr.net/npm/leader-line/leader-line.min.js"></script>
22
- <script src="https://cdn.jsdelivr.net/npm/yaml-flow@8.4.13/browser/live-cards.js"></script>
23
- <script src="https://cdn.jsdelivr.net/npm/yaml-flow@8.4.13/browser/board-livecards-client.js"></script>
22
+ <script src="https://cdn.jsdelivr.net/npm/yaml-flow@8.4.14/browser/live-cards.js"></script>
23
+ <script src="https://cdn.jsdelivr.net/npm/yaml-flow@8.4.14/browser/board-livecards-client.js"></script>
24
24
  </head>
25
25
  <body class="bg-light">
26
26
  <div class="container-fluid py-3">
@@ -37,8 +37,8 @@
37
37
  <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
38
38
  <script src="https://cdn.jsdelivr.net/npm/dompurify/dist/purify.min.js"></script>
39
39
  <script src="https://cdn.jsdelivr.net/npm/leader-line/leader-line.min.js"></script>
40
- <script src="https://cdn.jsdelivr.net/npm/yaml-flow@8.4.13/browser/live-cards.js"></script>
41
- <script src="https://cdn.jsdelivr.net/npm/yaml-flow@8.4.13/browser/board-livecards-client.js"></script>
40
+ <script src="https://cdn.jsdelivr.net/npm/yaml-flow@8.4.14/browser/live-cards.js"></script>
41
+ <script src="https://cdn.jsdelivr.net/npm/yaml-flow@8.4.14/browser/board-livecards-client.js"></script>
42
42
  </head>
43
43
  <body class="bg-light">
44
44
  <div class="container-fluid py-3">
@@ -6,13 +6,13 @@
6
6
  <title>Example Board Demo (LocalStorage Runtime)</title>
7
7
  <link rel="icon" type="image/svg+xml" href="../../browser/favicon.svg" />
8
8
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" />
9
- <script src="https://cdn.jsdelivr.net/npm/yaml-flow@8.4.13/browser/compute-jsonata.js"></script>
9
+ <script src="https://cdn.jsdelivr.net/npm/yaml-flow@8.4.14/browser/compute-jsonata.js"></script>
10
10
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
11
11
  <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
12
12
  <script src="https://cdn.jsdelivr.net/npm/dompurify/dist/purify.min.js"></script>
13
13
  <script src="https://cdn.jsdelivr.net/npm/leader-line/leader-line.min.js"></script>
14
- <script src="https://cdn.jsdelivr.net/npm/yaml-flow@8.4.13/browser/live-cards.js"></script>
15
- <script src="https://cdn.jsdelivr.net/npm/yaml-flow@8.4.13/browser/board-livecards-localstorage.js"></script>
14
+ <script src="https://cdn.jsdelivr.net/npm/yaml-flow@8.4.14/browser/live-cards.js"></script>
15
+ <script src="https://cdn.jsdelivr.net/npm/yaml-flow@8.4.14/browser/board-livecards-localstorage.js"></script>
16
16
  </head>
17
17
  <body class="bg-light">
18
18
  <div class="container-fluid py-3">