yaml-flow 8.4.5 → 8.4.8
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/browser/asset-integrity.json +3 -3
- package/browser/board-livecards-localstorage.js +6 -6
- package/browser/live-cards.js +7 -7
- package/cli/node/fs-board-adapter.d.ts +1 -1
- package/cli/node/fs-board-adapter.js +1 -1
- package/cli/node/step-machine-cli.d.ts +57 -1
- package/cli/node/step-machine-cli.js +3 -3
- package/examples/board/demo-shell-with-server.html +2 -2
- package/examples/board/doc.html +2 -2
- package/examples/board-local/demo-shell-localstorage.html +3 -3
- package/lib/{artifacts-store-lib-454TAuov.d.ts → artifacts-store-lib-CXgRA5J7.d.ts} +1 -1
- package/lib/{artifacts-store-lib-zsGFbBV8.d.cts → artifacts-store-lib-WdoKNAF0.d.cts} +1 -1
- package/lib/artifacts-store-public.d.cts +1 -1
- package/lib/artifacts-store-public.d.ts +1 -1
- package/lib/board-live-cards-node.cjs +1 -1
- package/lib/board-live-cards-node.d.cts +4 -4
- package/lib/board-live-cards-node.d.ts +4 -4
- package/lib/board-live-cards-node.js +1 -1
- package/lib/board-live-cards-server-runtime.cjs +3 -3
- package/lib/board-live-cards-server-runtime.d.cts +2 -2
- package/lib/board-live-cards-server-runtime.d.ts +2 -2
- package/lib/board-live-cards-server-runtime.js +3 -3
- package/lib/{constants-DXxsRN9y.d.cts → constants-C-iQV9ZB.d.cts} +1 -1
- package/lib/{constants-BPVLb3Es.d.ts → constants-dmPZTieN.d.ts} +1 -1
- package/lib/event-graph/index.d.cts +2 -2
- package/lib/event-graph/index.d.ts +2 -2
- package/lib/index.cjs +2 -2
- package/lib/index.d.cts +3 -3
- package/lib/index.d.ts +3 -3
- package/lib/index.js +2 -2
- package/lib/{loader-CuuLjxVA.d.cts → loader-Bw7KRzCK.d.cts} +1 -1
- package/lib/{loader-Zborm2pq.d.ts → loader-D6xGRDWX.d.ts} +1 -1
- package/lib/server-runtime/index.cjs +3 -3
- package/lib/server-runtime/index.d.cts +3 -3
- package/lib/server-runtime/index.d.ts +3 -3
- package/lib/server-runtime/index.js +3 -3
- package/lib/step-machine/index.cjs +2 -2
- package/lib/step-machine/index.d.cts +3 -3
- package/lib/step-machine/index.d.ts +3 -3
- package/lib/step-machine/index.js +2 -2
- package/lib/step-machine-public/index.cjs +1 -1
- package/lib/step-machine-public/index.d.cts +2 -2
- package/lib/step-machine-public/index.d.ts +2 -2
- package/lib/step-machine-public/index.js +1 -1
- package/lib/stores/index.d.cts +1 -1
- package/lib/stores/index.d.ts +1 -1
- package/lib/stores/kv.d.cts +1 -1
- package/lib/stores/kv.d.ts +1 -1
- package/lib/stores/memory.d.cts +1 -1
- package/lib/stores/memory.d.ts +1 -1
- package/lib/{types-DX8wXuZ0.d.cts → types-Dc70aHzf.d.cts} +1 -1
- package/lib/{types-DQ1bKuB1.d.ts → types-DjlwALZC.d.cts} +1 -0
- package/lib/{types-DQ1bKuB1.d.cts → types-DjlwALZC.d.ts} +1 -0
- package/lib/{types-BC8ZnA6i.d.ts → types-YXF9Oai2.d.ts} +1 -1
- package/package.json +1 -1
- package/schema/flow.schema.json +6 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import*as h from'fs';import {existsSync}from'fs';import*as S from'path';import {dirname,resolve}from'path';import'ajv-formats';import {createRequire}from'module';import {fileURLToPath}from'url';import {spawn,execFile,execFileSync}from'child_process';import*as vt from'os';import'net';import {randomUUID}from'crypto';import'proper-lockfile';function V(e,t,n,r){let s=e.steps[n];if(!s)throw new Error(`Step "${n}" not found in flow configuration`);if(r.result==="failure"&&s.retry){let i=t.retryCounts[n]??0;if(i<s.retry.max_attempts)return {newState:{...t,retryCounts:{...t.retryCounts,[n]:i+1},updatedAt:Date.now()},nextStep:n,isTerminal:false,isCircuitBroken:false,shouldRetry:true}}let o=s.failure_transitions?.[r.result]??s.transitions[r.result];if(!o)throw new Error(`No transition defined for result "${r.result}" in step "${n}"`);let a=!!e.terminal_states[o];return {newState:{...t,currentStep:o,stepHistory:[...t.stepHistory,n],retryCounts:{...t.retryCounts,[n]:0},updatedAt:Date.now()},nextStep:o,isTerminal:a,isCircuitBroken:false,shouldRetry:false}}function z(e,t,n){let r=e.steps[n];if(!r?.circuit_breaker)return {broken:false,newState:{...t,iterationCounts:{...t.iterationCounts,[n]:(t.iterationCounts[n]??0)+1},updatedAt:Date.now()}};let s=t.iterationCounts[n]??0;return s>=r.circuit_breaker.max_iterations?{broken:true,redirectStep:r.circuit_breaker.on_open,newState:{...t,currentStep:r.circuit_breaker.on_open,updatedAt:Date.now()}}:{broken:false,newState:{...t,iterationCounts:{...t.iterationCounts,[n]:s+1},updatedAt:Date.now()}}}function q(e,t,n){let r=e.steps[t];if(!r)throw new Error(`Step "${t}" not found`);if(r.expects_data){let s={};for(let o of r.expects_data)s[o]=n[o];return s}return {...n}}function W(e,t){if(e===false||e===void 0)return {};if(typeof e=="string")return {[e]:t[e]};if(Array.isArray(e)){let n={};for(let r of e)n[r]=t[r];return n}return {}}function G(e,t){let n=Date.now();return {runId:t,flowId:e.id??"unnamed",currentStep:e.settings.start_step,status:"running",stepHistory:[],iterationCounts:{},retryCounts:{},startedAt:n,updatedAt:n}}var k=class{runs=new Map;data=new Map;async saveRunState(t,n){this.runs.set(t,{...n});}async loadRunState(t){let n=this.runs.get(t);return n?{...n}:null}async deleteRunState(t){this.runs.delete(t),this.data.delete(t);}async setData(t,n,r){this.data.has(t)||this.data.set(t,{});let s=this.data.get(t);s[n]=r;}async getData(t,n){return this.data.get(t)?.[n]}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 _t(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return (e==="x"?t:t&3|8).toString(16)})}var I=class{flow;handlers;store;components;options;listeners=new Map;aborted=false;constructor(t,n,r={}){this.flow=t,this.handlers=new Map(Object.entries(n)),this.store=r.store??new k,this.components=r.components??{},this.options=r,r.signal&&r.signal.addEventListener("abort",()=>{this.aborted=true;}),this.validateFlow();}validateFlow(){let{settings:t,steps:n,terminal_states:r}=this.flow;if(!t?.start_step)throw new Error("Flow must have settings.start_step defined");if(!n||Object.keys(n).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(!n[t.start_step]&&!r[t.start_step])throw new Error(`Start step "${t.start_step}" not found`);for(let[s,o]of Object.entries(n)){for(let[a,i]of Object.entries(o.transitions))if(!n[i]&&!r[i])throw new Error(`Step "${s}" transition "${a}" points to unknown step "${i}"`);if(o.failure_transitions){for(let[a,i]of Object.entries(o.failure_transitions))if(!n[i]&&!r[i])throw new Error(`Step "${s}" failure_transition "${a}" points to unknown step "${i}"`)}}}on(t,n){this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(n);}off(t,n){this.listeners.get(t)?.delete(n);}emit(t){let n=this.listeners.get(t.type);if(n)for(let r of n)try{r(t);}catch{}}sleep(t){return new Promise(n=>setTimeout(n,t))}async run(t){let n=_t(),r=G(this.flow,n);if(await this.store.saveRunState(n,r),t)for(let[s,o]of Object.entries(t))await this.store.setData(n,s,o);this.emit({type:"flow:start",runId:n,timestamp:r.startedAt,data:{initialData:t??{}}});try{return await this.executeLoop(n,r)}catch(s){let o=s instanceof Error?s:new Error(String(s));return this.emit({type:"flow:error",runId:n,timestamp:Date.now(),data:{error:o.message}}),this.options.onError?.(o),r={...r,status:"failed",updatedAt:Date.now()},await this.store.saveRunState(n,r),{runId:n,status:"failed",data:await this.store.getAllData(n),finalStep:r.currentStep,stepHistory:r.stepHistory,durationMs:Date.now()-r.startedAt,error:o}}}async resume(t){let n=await this.store.loadRunState(t);if(!n)throw new Error(`No run found with ID: ${t}`);if(n.status==="completed"||n.status==="failed")throw new Error(`Cannot resume a ${n.status} run`);let r={...n,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 n=await this.store.loadRunState(t);if(!n)throw new Error(`No run found with ID: ${t}`);let r={...n,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,n){let r=this.flow.settings.max_total_steps??100,s=this.flow.settings.timeout_ms,o=n,a=0;for(;a<r;){if(this.aborted)return o={...o,status:"cancelled",updatedAt:Date.now()},await this.store.saveRunState(t,o),{runId:t,status:"cancelled",data:await this.store.getAllData(t),finalStep:o.currentStep,stepHistory:o.stepHistory,durationMs:Date.now()-o.startedAt};if(s&&Date.now()-o.startedAt>s)return o={...o,status:"completed",updatedAt:Date.now()},await this.store.saveRunState(t,o),{runId:t,status:"timeout",intent:"timeout",data:await this.store.getAllData(t),finalStep:o.currentStep,stepHistory:o.stepHistory,durationMs:Date.now()-o.startedAt};let i=o.currentStep,c=this.flow.terminal_states[i];if(c){o={...o,status:"completed",updatedAt:Date.now()},await this.store.saveRunState(t,o);let p=await this.store.getAllData(t),d={runId:t,status:"completed",intent:c.return_intent,data:W(c.return_artifacts,p),finalStep:i,stepHistory:o.stepHistory,durationMs:Date.now()-o.startedAt};return this.emit({type:"flow:complete",runId:t,timestamp:Date.now(),data:{...d}}),this.options.onComplete?.(d),d}let u=z(this.flow,o,i);if(u.broken){o=u.newState,await this.store.saveRunState(t,o),a++;continue}o=u.newState;let f=await this.store.getAllData(t),l=q(this.flow,i,f),g={runId:t,stepName:i,components:this.components,store:this.store,signal:this.options.signal,emit:(p,d)=>{this.emit({type:"step:complete",runId:t,timestamp:Date.now(),data:{event:p,payload:d}});}};this.emit({type:"step:start",runId:t,timestamp:Date.now(),data:{step:i,input:l}});let y;try{let p=this.handlers.get(i);if(!p)throw new Error(`No handler registered for step "${i}"`);y=await p(l,g);}catch(p){let d=p instanceof Error?p:new Error(String(p));this.emit({type:"step:error",runId:t,timestamp:Date.now(),data:{step:i,error:d.message}}),y={result:"failure",data:{error:d.message}};}if(y.data)for(let[p,d]of Object.entries(y.data))await this.store.setData(t,p,d);this.emit({type:"step:complete",runId:t,timestamp:Date.now(),data:{step:i,result:y.result}}),this.options.onStep?.(i,y);let R=V(this.flow,o,i,y);if(o=R.newState,R.shouldRetry){await this.store.saveRunState(t,o);let p=this.flow.steps[i];if(p.retry?.delay_ms){let d=o.retryCounts[i]??0,v=p.retry.backoff_multiplier?p.retry.delay_ms*Math.pow(p.retry.backoff_multiplier,d-1):p.retry.delay_ms;await this.sleep(v);}a++;continue}await this.store.saveRunState(t,o),this.emit({type:"transition",runId:t,timestamp:Date.now(),data:{from:i,to:o.currentStep,result:y.result}}),this.options.onTransition?.(i,o.currentStep),a++;}return o={...o,status:"completed",updatedAt:Date.now()},await this.store.saveRunState(t,o),{runId:t,status:"max_iterations",intent:"max_iterations",data:await this.store.getAllData(t),finalStep:o.currentStep,stepHistory:o.stepHistory,durationMs:Date.now()-o.startedAt}}};function P(e,t,n){return new I(e,t,n)}async function Y(e){return (await import('yaml')).parse(e)}async function Pt(e){let t=await fetch(e);if(!t.ok)throw new Error(`Failed to load flow from ${e}: ${t.statusText}`);let n=t.headers.get("content-type")??"",r=await t.text();return n.includes("json")||e.endsWith(".json")?JSON.parse(r):Y(r)}async function Ot(e){let n=await(await import('fs/promises')).readFile(e,"utf-8");return e.endsWith(".json")?JSON.parse(n):Y(n)}function rt(e){let t=[];if(!e||typeof e!="object")return ["Flow must be an object"];let n=e;if(!n.settings||typeof n.settings!="object"?t.push('Flow must have a "settings" object'):typeof n.settings.start_step!="string"&&t.push("settings.start_step must be a string"),!n.steps||typeof n.steps!="object")t.push('Flow must have a "steps" object');else {let r=n.steps;for(let[s,o]of Object.entries(r)){if(!o||typeof o!="object"){t.push(`Step "${s}" must be an object`);continue}let a=o;(!a.transitions||typeof a.transitions!="object")&&t.push(`Step "${s}" must have a "transitions" object`),a.failure_transitions!==void 0&&typeof a.failure_transitions!="object"&&t.push(`Step "${s}" failure_transitions must be an object when provided`);}}if(!n.terminal_states||typeof n.terminal_states!="object")t.push('Flow must have a "terminal_states" object');else {let r=n.terminal_states;for(let[s,o]of Object.entries(r)){if(!o||typeof o!="object"){t.push(`Terminal state "${s}" must be an object`);continue}typeof o.return_intent!="string"&&t.push(`Terminal state "${s}" must have a "return_intent" string`);}}return t}async function H(e){let t;typeof e=="string"?e.startsWith("http://")||e.startsWith("https://")?t=await Pt(e):e.includes("{")?t=JSON.parse(e):t=await Ot(e):t=e;let n=rt(t);if(n.length>0)throw new Error(`Invalid step flow configuration:
|
|
1
|
+
import*as h from'fs';import {existsSync}from'fs';import*as S from'path';import {dirname,resolve}from'path';import'ajv-formats';import {createRequire}from'module';import {fileURLToPath}from'url';import {spawn,execFile,execFileSync}from'child_process';import*as vt from'os';import'net';import {randomUUID}from'crypto';import'proper-lockfile';function V(e,t,n,r){let s=e.steps[n];if(!s)throw new Error(`Step "${n}" not found in flow configuration`);if(r.result==="failure"&&s.retry){let i=t.retryCounts[n]??0;if(i<s.retry.max_attempts)return {newState:{...t,retryCounts:{...t.retryCounts,[n]:i+1},updatedAt:Date.now()},nextStep:n,isTerminal:false,isCircuitBroken:false,shouldRetry:true}}let o=s.failure_transitions?.[r.result]??s.transitions[r.result];if(!o)throw new Error(`No transition defined for result "${r.result}" in step "${n}"`);let a=!!e.terminal_states[o];return {newState:{...t,currentStep:o,stepHistory:[...t.stepHistory,n],retryCounts:{...t.retryCounts,[n]:0},updatedAt:Date.now()},nextStep:o,isTerminal:a,isCircuitBroken:false,shouldRetry:false}}function z(e,t,n){let r=e.steps[n];if(!r?.circuit_breaker)return {broken:false,newState:{...t,iterationCounts:{...t.iterationCounts,[n]:(t.iterationCounts[n]??0)+1},updatedAt:Date.now()}};let s=t.iterationCounts[n]??0;return s>=r.circuit_breaker.max_iterations?{broken:true,redirectStep:r.circuit_breaker.on_open,newState:{...t,currentStep:r.circuit_breaker.on_open,updatedAt:Date.now()}}:{broken:false,newState:{...t,iterationCounts:{...t.iterationCounts,[n]:s+1},updatedAt:Date.now()}}}function q(e,t,n){let r=e.steps[t];if(!r)throw new Error(`Step "${t}" not found`);if(r.expects_data){let s={};for(let o of r.expects_data)s[o]=n[o];return s}return {...n}}function W(e,t){if(e===false||e===void 0)return {};if(typeof e=="string")return {[e]:t[e]};if(Array.isArray(e)){let n={};for(let r of e)n[r]=t[r];return n}return {}}function G(e,t){let n=Date.now();return {runId:t,flowId:e.id??"unnamed",currentStep:e.settings.start_step,status:"running",stepHistory:[],iterationCounts:{},retryCounts:{},startedAt:n,updatedAt:n}}var k=class{runs=new Map;data=new Map;async saveRunState(t,n){this.runs.set(t,{...n});}async loadRunState(t){let n=this.runs.get(t);return n?{...n}:null}async deleteRunState(t){this.runs.delete(t),this.data.delete(t);}async setData(t,n,r){this.data.has(t)||this.data.set(t,{});let s=this.data.get(t);s[n]=r;}async getData(t,n){return this.data.get(t)?.[n]}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 _t(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return (e==="x"?t:t&3|8).toString(16)})}var I=class{flow;handlers;store;components;options;listeners=new Map;aborted=false;constructor(t,n,r={}){this.flow=t,this.handlers=new Map(Object.entries(n)),this.store=r.store??new k,this.components=r.components??{},this.options=r,r.signal&&r.signal.addEventListener("abort",()=>{this.aborted=true;}),this.validateFlow();}validateFlow(){let{settings:t,steps:n,terminal_states:r}=this.flow;if(!t?.start_step)throw new Error("Flow must have settings.start_step defined");if(!n||Object.keys(n).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(!n[t.start_step]&&!r[t.start_step])throw new Error(`Start step "${t.start_step}" not found`);for(let[s,o]of Object.entries(n)){for(let[a,i]of Object.entries(o.transitions))if(!n[i]&&!r[i])throw new Error(`Step "${s}" transition "${a}" points to unknown step "${i}"`);if(o.failure_transitions){for(let[a,i]of Object.entries(o.failure_transitions))if(!n[i]&&!r[i])throw new Error(`Step "${s}" failure_transition "${a}" points to unknown step "${i}"`)}}}on(t,n){this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(n);}off(t,n){this.listeners.get(t)?.delete(n);}emit(t){let n=this.listeners.get(t.type);if(n)for(let r of n)try{r(t);}catch{}}sleep(t){return new Promise(n=>setTimeout(n,t))}async run(t){let n=_t(),r=G(this.flow,n);if(await this.store.saveRunState(n,r),t)for(let[s,o]of Object.entries(t))await this.store.setData(n,s,o);this.emit({type:"flow:start",runId:n,timestamp:r.startedAt,data:{initialData:t??{}}});try{return await this.executeLoop(n,r)}catch(s){let o=s instanceof Error?s:new Error(String(s));return this.emit({type:"flow:error",runId:n,timestamp:Date.now(),data:{error:o.message}}),this.options.onError?.(o),r={...r,status:"failed",updatedAt:Date.now()},await this.store.saveRunState(n,r),{runId:n,status:"failed",data:await this.store.getAllData(n),finalStep:r.currentStep,stepHistory:r.stepHistory,durationMs:Date.now()-r.startedAt,error:o}}}async resume(t){let n=await this.store.loadRunState(t);if(!n)throw new Error(`No run found with ID: ${t}`);if(n.status==="completed"||n.status==="failed")throw new Error(`Cannot resume a ${n.status} run`);let r={...n,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 n=await this.store.loadRunState(t);if(!n)throw new Error(`No run found with ID: ${t}`);let r={...n,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,n){let r=this.flow.settings.max_total_steps??1e6,s=this.flow.settings.timeout_ms,o=n,a=0;for(;a<r;){if(this.aborted)return o={...o,status:"cancelled",updatedAt:Date.now()},await this.store.saveRunState(t,o),{runId:t,status:"cancelled",data:await this.store.getAllData(t),finalStep:o.currentStep,stepHistory:o.stepHistory,durationMs:Date.now()-o.startedAt};if(s&&Date.now()-o.startedAt>s)return o={...o,status:"completed",updatedAt:Date.now()},await this.store.saveRunState(t,o),{runId:t,status:"timeout",intent:"timeout",data:await this.store.getAllData(t),finalStep:o.currentStep,stepHistory:o.stepHistory,durationMs:Date.now()-o.startedAt};let i=o.currentStep,c=this.flow.terminal_states[i];if(c){o={...o,status:"completed",updatedAt:Date.now()},await this.store.saveRunState(t,o);let p=await this.store.getAllData(t),d={runId:t,status:"completed",intent:c.return_intent,data:W(c.return_artifacts,p),finalStep:i,stepHistory:o.stepHistory,durationMs:Date.now()-o.startedAt};return this.emit({type:"flow:complete",runId:t,timestamp:Date.now(),data:{...d}}),this.options.onComplete?.(d),d}let u=z(this.flow,o,i);if(u.broken){o=u.newState,await this.store.saveRunState(t,o),a++;continue}o=u.newState;let f=await this.store.getAllData(t),l=q(this.flow,i,f),g={runId:t,stepName:i,components:this.components,store:this.store,signal:this.options.signal,emit:(p,d)=>{this.emit({type:"step:complete",runId:t,timestamp:Date.now(),data:{event:p,payload:d}});}};this.emit({type:"step:start",runId:t,timestamp:Date.now(),data:{step:i,input:l}});let y;try{let p=this.handlers.get(i);if(!p)throw new Error(`No handler registered for step "${i}"`);y=await p(l,g);}catch(p){let d=p instanceof Error?p:new Error(String(p));this.emit({type:"step:error",runId:t,timestamp:Date.now(),data:{step:i,error:d.message}}),y={result:"failure",data:{error:d.message}};}if(y.data)for(let[p,d]of Object.entries(y.data))await this.store.setData(t,p,d);this.emit({type:"step:complete",runId:t,timestamp:Date.now(),data:{step:i,result:y.result}}),this.options.onStep?.(i,y);let R=V(this.flow,o,i,y);if(o=R.newState,R.shouldRetry){await this.store.saveRunState(t,o);let p=this.flow.steps[i];if(p.retry?.delay_ms){let d=o.retryCounts[i]??0,v=p.retry.backoff_multiplier?p.retry.delay_ms*Math.pow(p.retry.backoff_multiplier,d-1):p.retry.delay_ms;await this.sleep(v);}a++;continue}await this.store.saveRunState(t,o),this.emit({type:"transition",runId:t,timestamp:Date.now(),data:{from:i,to:o.currentStep,result:y.result}}),this.options.onTransition?.(i,o.currentStep),a++;}return o={...o,status:"completed",updatedAt:Date.now()},await this.store.saveRunState(t,o),{runId:t,status:"max_iterations",intent:"max_iterations",data:await this.store.getAllData(t),finalStep:o.currentStep,stepHistory:o.stepHistory,durationMs:Date.now()-o.startedAt}}};function P(e,t,n){return new I(e,t,n)}async function Y(e){return (await import('yaml')).parse(e)}async function Pt(e){let t=await fetch(e);if(!t.ok)throw new Error(`Failed to load flow from ${e}: ${t.statusText}`);let n=t.headers.get("content-type")??"",r=await t.text();return n.includes("json")||e.endsWith(".json")?JSON.parse(r):Y(r)}async function Ot(e){let n=await(await import('fs/promises')).readFile(e,"utf-8");return e.endsWith(".json")?JSON.parse(n):Y(n)}function rt(e){let t=[];if(!e||typeof e!="object")return ["Flow must be an object"];let n=e;if(!n.settings||typeof n.settings!="object"?t.push('Flow must have a "settings" object'):typeof n.settings.start_step!="string"&&t.push("settings.start_step must be a string"),!n.steps||typeof n.steps!="object")t.push('Flow must have a "steps" object');else {let r=n.steps;for(let[s,o]of Object.entries(r)){if(!o||typeof o!="object"){t.push(`Step "${s}" must be an object`);continue}let a=o;(!a.transitions||typeof a.transitions!="object")&&t.push(`Step "${s}" must have a "transitions" object`),a.failure_transitions!==void 0&&typeof a.failure_transitions!="object"&&t.push(`Step "${s}" failure_transitions must be an object when provided`);}}if(!n.terminal_states||typeof n.terminal_states!="object")t.push('Flow must have a "terminal_states" object');else {let r=n.terminal_states;for(let[s,o]of Object.entries(r)){if(!o||typeof o!="object"){t.push(`Terminal state "${s}" must be an object`);continue}typeof o.return_intent!="string"&&t.push(`Terminal state "${s}" must have a "return_intent" string`);}}return t}async function H(e){let t;typeof e=="string"?e.startsWith("http://")||e.startsWith("https://")?t=await Pt(e):e.includes("{")?t=JSON.parse(e):t=await Ot(e):t=e;let n=rt(t);if(n.length>0)throw new Error(`Invalid step flow configuration:
|
|
2
2
|
- ${n.join(`
|
|
3
|
-
- `)}`);return t}function X(e){return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function st(e){return atob(e.replace(/-/g,"+").replace(/_/g,"/"))}var $=class{constructor(t){this.kv=t;}kv;stateKey(t){return `state_${X(t)}`}dataPrefix(t){return `data_${X(t)}_`}dataKey(t,n){return `${this.dataPrefix(t)}${X(n)}`}async saveRunState(t,n){this.kv.write(this.stateKey(t),n);}async loadRunState(t){let n=this.kv.read(this.stateKey(t));return n!=null&&typeof n=="object"?n:null}async deleteRunState(t){this.kv.delete(this.stateKey(t));for(let n of this.kv.listKeys(this.dataPrefix(t)))this.kv.delete(n);}async setData(t,n,r){this.kv.write(this.dataKey(t,n),r);}async getData(t,n){return this.kv.read(this.dataKey(t,n))}async getAllData(t){let n=this.dataPrefix(t),r={};for(let s of this.kv.listKeys(n))r[st(s.slice(n.length))]=this.kv.read(s);return r}async clearData(t){for(let n of this.kv.listKeys(this.dataPrefix(t)))this.kv.delete(n);}async listRuns(){return this.kv.listKeys("state_").map(t=>st(t.slice(6)))}};var it=dirname(fileURLToPath(import.meta.url)),Dt=createRequire(import.meta.url);function Nt(){let e=resolve(it,"./jsonata-sync.cjs");return existsSync(e)?e:resolve(it,"../card-compute/jsonata-sync.cjs")}var O=Dt(Nt());function at(e,t){if(!e||typeof e!="object")throw new Error(`[step-machine-public] Step "${t}" returned a non-object result.`);let n=e,r=n.result??n.status;if(typeof r=="string"&&r.trim().length>0){let s=n.data&&typeof n.data=="object"&&!Array.isArray(n.data)?{...n.data}:{},o=typeof n.error=="string"?n.error:void 0;return o&&!("error"in s)&&(s.error=o),{result:r,data:s,...o?{error:o}:{}}}return {result:"success",data:{...n}}}function ct(e,t){if(!t||t.length===0)return e;let n={};for(let r of t)Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function Z(e,t){return async(n,r)=>{let s=await e(n,r),o=at(s,r?.stepName??"unknown");return {result:o.result,data:ct(o.data,t),...o.error?{error:o.error}:{}}}}function ut(e,t,n){if(!t||t.length===0)return null;for(let r of t)try{if(!O(r).evaluate(e))return {result:"failure",data:{error:`[${n}] input validation failed: ${r}`}}}catch(s){let o=s instanceof Error?s.message:String(s);return {result:"failure",data:{error:`[${n}] input validation error on "${r}": ${o}`}}}return null}function Q(e,t,n){return !t||t.length===0?e:async(r,s)=>{let o=ut(r,t,n);return o||e(r,s)}}var pt=dirname(fileURLToPath(import.meta.url)),zt=createRequire(import.meta.url);function qt(){let e=resolve(pt,"./jsonata-sync.cjs");return existsSync(e)?e:resolve(pt,"../../card-compute/jsonata-sync.cjs")}var x=zt(qt());var J="b64:";function Wt(e){let t=new TextEncoder().encode(e),n=globalThis.Buffer,r;if(n)r=n.from(t).toString("base64");else if(typeof btoa=="function"){let s="";for(let o of t)s+=String.fromCharCode(o);r=btoa(s);}else throw new Error("No base64 encoder available in this runtime");return r.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function Gt(e){let t=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-e.length%4)%4),n=globalThis.Buffer;if(n)return n.from(t,"base64").toString("utf8");if(typeof atob=="function"){let r=atob(t),s=new Uint8Array(r.length);for(let o=0;o<r.length;o+=1)s[o]=r.charCodeAt(o);return new TextDecoder().decode(s)}throw new Error("No base64 decoder available in this runtime")}function b(e){return `${J}${Wt(JSON.stringify(e))}`}function B(e){if(!e.startsWith(J))throw new Error(`Invalid ref format (expected ${J}<base64url(json)>): ${e}`);let t;try{t=JSON.parse(Gt(e.slice(J.length)));}catch{throw new Error(`Invalid ref format (malformed base64url/json): ${e}`)}if(!t||typeof t!="object")throw new Error(`Invalid ref format (expected object payload): ${e}`);let n=t;if(typeof n.kind!="string"||typeof n.value!="string")throw new Error(`Invalid ref format (payload must contain string kind/value): ${e}`);return {kind:n.kind,value:n.value}}function E(e){e.registerFunction("fsPathRef",t=>b({kind:"fs-path",value:String(t)}),"<s:s>");}function ft(e,t,n){if(!e||typeof e!="object")return {};let r={};if(Array.isArray(e.cmdTemplate)){let s=[];for(let o of e.cmdTemplate)try{let a=x(o);E(a),s.push(String(a.evaluate(t)));}catch(a){let i=a instanceof Error?a.message:String(a);throw new Error(`[${n}] argsMassaging.cmdTemplate failed on "${o}": ${i}`)}r.cmdArgs=s;}if(typeof e.stdinTemplate=="string")try{let s=x(e.stdinTemplate);E(s),r.stdin=s.evaluate(t);}catch(s){let o=s instanceof Error?s.message:String(s);throw new Error(`[${n}] argsMassaging.stdinTemplate failed: ${o}`)}if(typeof e.urlTemplate=="string")try{let s=x(e.urlTemplate);E(s),r.url=String(s.evaluate(t));}catch(s){let o=s instanceof Error?s.message:String(s);throw new Error(`[${n}] argsMassaging.urlTemplate failed: ${o}`)}if(typeof e.headerTemplate=="string")try{let s=x(e.headerTemplate);E(s);let o=s.evaluate(t);if(typeof o!="object"||o===null)throw new Error(`headerTemplate must produce an object, got: ${JSON.stringify(o)}`);r.headers=o;}catch(s){let o=s instanceof Error?s.message:String(s);throw new Error(`[${n}] argsMassaging.headerTemplate failed: ${o}`)}if(typeof e.bodyTemplate=="string")try{let s=x(e.bodyTemplate);E(s),r.body=s.evaluate(t);}catch(s){let o=s instanceof Error?s.message:String(s);throw new Error(`[${n}] argsMassaging.bodyTemplate failed: ${o}`)}return r}function dt(e,t,n){if(!e||typeof e!="object")return t;let r={output:t},s=t.result,o=t.data,a=t.error;if(typeof e.resultExpr=="string")try{let i=x(e.resultExpr);E(i);let c=i.evaluate(r);if(typeof c!="string"||!c.trim())throw new Error(`resultExpr did not produce a non-empty string (got ${JSON.stringify(c)})`);s=c;}catch(i){let c=i instanceof Error?i.message:String(i);throw new Error(`[${n}] outputTransforms.resultExpr failed: ${c}`)}if(typeof e.dataTemplate=="string")try{let i=x(e.dataTemplate);E(i);let c=i.evaluate(r);if(!c||typeof c!="object"||Array.isArray(c))throw new Error(`dataTemplate did not produce an object (got ${JSON.stringify(c)})`);o=c;}catch(i){let c=i instanceof Error?i.message:String(i);throw new Error(`[${n}] outputTransforms.dataTemplate failed: ${c}`)}if(typeof e.errorExpr=="string")try{let i=x(e.errorExpr);E(i);let c=i.evaluate(r);a=c!=null?String(c):void 0;}catch(i){let c=i instanceof Error?i.message:String(i);throw new Error(`[${n}] outputTransforms.errorExpr failed: ${c}`)}return a!==void 0?{result:s,data:o,error:a}:{result:s,data:o}}function gt(e){return !!e&&typeof e=="object"&&e.type==="compute-jsonata"&&Array.isArray(e.expr)&&e.expr.length>0}function mt(e){if(!e||typeof e!="object")return false;let t=e;if(t.type!=="ref"||typeof t.howToRun!="string")return false;if(typeof t.whatToRun=="string")return true;if(t.whatToRun&&typeof t.whatToRun=="object"){let n=t.whatToRun;return typeof n.kind=="string"&&typeof n.value=="string"}return false}function Yt(e){if(typeof e=="string"){let t=e.indexOf("=");if(t<1)throw new Error(`[step-machine-public] Invalid compute expression (missing "="): "${e}"`);return {bindTo:e.slice(0,t).trim(),expr:e.slice(t+1).trim()}}if(e&&typeof e=="object"&&typeof e.bindTo=="string"&&typeof e.expr=="string")return e;throw new Error(`[step-machine-public] Invalid compute step: ${JSON.stringify(e)}`)}function Xt(e,t,n){let r=t.split("."),s=e;for(let o=0;o<r.length-1;o++){let a=r[o];(s[a]==null||typeof s[a]!="object")&&(s[a]={}),s=s[a];}s[r[r.length-1]]=n;}function ht(e,t,n){let r=e.expr.map(Yt);return async s=>{let o=s&&typeof s=="object"&&!Array.isArray(s)?{...s}:{},a={},i={expects_data:o,data:a,...n?{config:n}:{}},c,u;for(let f of r)try{let l=O(f.expr).evaluate(i);if(f.bindTo==="result")c=l!=null?String(l):"success";else if(f.bindTo==="error")u=l!=null?String(l):void 0;else if(f.bindTo.startsWith("data."))Xt(a,f.bindTo.slice(5),l);else return {result:"failure",data:{},error:`[${t}] invalid bindTo "${f.bindTo}": must be "result", "error", or start with "data."`}}catch(l){let g=l instanceof Error?l.message:String(l);return {result:"failure",data:{},error:`[${t}] compute "${f.bindTo}" failed: ${g}`}}return c===void 0?{result:"failure",data:{},error:`[${t}] compute-jsonata: no "result" binding declared \u2014 add '- result = "success"' to expr`}:u?{result:c,data:a,error:u}:{result:c,data:a}}}function yt(e,t,n,r){let{type:s,...o}=e,a={...o,whatToRun:typeof o.whatToRun=="object"?b(o.whatToRun):o.whatToRun};return async i=>{let c=i&&typeof i=="object"&&!Array.isArray(i)?{...i}:{};r&&(c.config=r);try{let u=await n(a,c);if(!e.outputTransforms)return u;try{return dt(e.outputTransforms,u,t)}catch(f){let l=f instanceof Error?f.message:String(f);return {result:"failure",data:{},error:l}}}catch(u){let f=u instanceof Error?u.message:String(u);return {result:"failure",data:{error:`[step-machine-public] step "${t}" invoke threw: ${f}`}}}}}function wt(){return async e=>({result:"success",data:e&&typeof e=="object"&&!Array.isArray(e)?e:{}})}function Zt(e,t,n){return async(r,s)=>{let o=r?.[t.items];if(!Array.isArray(o))return {result:"failure",data:{},error:`[${n}] forEach: "${t.items}" is not an array (got ${typeof o})`};let a=o,i=t.collectAs??`${t.items}_results`;if(a.length===0)return {result:"success",data:{[i]:[]}};let{[t.items]:c,...u}=r,f=Math.max(1,t.concurrency??1),l=new Array(a.length),g=0,y=0,R=0;return await new Promise(p=>{function d(){for(;g<f&&y<a.length;){let v=y++;g++;let C={...u,[t.as]:a[v]};e(C,s).then(m=>{l[v]=m;}).catch(m=>{let T=m instanceof Error?m.message:String(m);l[v]={result:"failure",data:{},error:T};}).finally(()=>{g--,l[v]?.result==="failure"&&R++,y>=a.length&&g===0?p():d();});}g===0&&y>=a.length&&p();}d();}),R>0?{result:"failure",data:{errors:l.filter(d=>d.result==="failure").map(d=>d.error)},error:`[${n}] forEach: ${R}/${a.length} items failed`}:{result:"success",data:{[i]:l.map(p=>p.data)}}}}function St(e,t,n){let r=Array.isArray(t?.produces_data)?t?.produces_data:void 0,s=Array.isArray(t?.input_validations)?t?.input_validations:void 0,o=t?.config??void 0,a=t?.handler,i;return gt(a)?i=ht(a,e,o):mt(a)?i=yt(a,e,n.invoke,o):i=wt(),t?.forEach&&(i=Zt(i,t.forEach,e)),Q(Z(i,r),s,e)}function D(e,t){let n={};for(let[r,s]of Object.entries(e.steps??{}))n[r]=St(r,s,t);return n}function ne(e){if(typeof e=="object"&&e!==null){let{command:n,args:r=[],...s}=e,o=xt(n,r);return {...s,command:o.command,args:o.args}}let t=kt(e);if(t.length===0)throw new Error(`Empty command spec: ${JSON.stringify(e)}`);return xt(t[0],t.slice(1))}function xt(e,t){return /^(node|node\.exe)$/i.test(e)?{command:process.execPath,args:t}:/\.m?js$/i.test(e)?{command:process.execPath,args:[e,...t]}:{command:e,args:t}}function kt(e){let t=[],n="",r=null;for(let s of e.trim()){if(r){s===r?r=null:n+=s;continue}if(s==='"'||s==="'"){r=s;continue}if(/\s/.test(s)){n&&(t.push(n),n="");continue}n+=s;}if(r)throw new Error(`Unterminated quote in command: ${e}`);return n&&t.push(n),t}function tt(e){return process.platform==="win32"&&/\.(cmd|bat)$/i.test(e)}function bt(e,t){let{command:n,args:r=[],cwd:s,env:o,timeoutMs:a}=e;return execFileSync(n,r,{shell:tt(n),timeout:a,encoding:t?.encoding??"utf-8",cwd:s,windowsHide:true,env:o?{...process.env,...o}:void 0,input:t?.input})}function re(e,t){let{command:n,args:r=[],cwd:s,env:o,timeoutMs:a=3e4}=e;execFile(n,r,{shell:tt(n),encoding:"utf8",windowsHide:true,timeout:a,maxBuffer:10*1024*1024,cwd:s,env:o?{...process.env,...o}:void 0},(i,c,u)=>t(i??null,c,u));}S.join(vt.tmpdir(),".board-live-cards-git-bash-cache.json");function Et(e){let{command:t,args:n=[]}=e;if(process.platform==="win32"){spawn(t,n,{detached:true,stdio:"ignore",windowsHide:true,shell:tt(t)}).unref();return}spawn(t,n,{detached:true,stdio:"ignore"}).unref();}function At(e,t,n){let r=S.join(e,"board-live-cards-cli.js");if(h.existsSync(r))return {cmd:process.execPath,args:[r,t,...n]};let s=S.join(e,"board-live-cards-cli.ts"),a=[S.join(e,"..","..","..","node_modules","tsx","dist","cli.mjs"),S.join(e,"..","..","node_modules","tsx","dist","cli.mjs"),S.join(e,"..","..","..","node_modules",".bin","tsx"),S.join(e,"..","..","node_modules",".bin","tsx")].find(c=>h.existsSync(c));return h.existsSync(s)&&h.existsSync(a)?{cmd:process.execPath,args:[a,s,t,...n]}:{cmd:process.platform==="win32"?"npx.cmd":"npx",args:["tsx",s,t,...n]}}function jt(){return {executeSync(e,t,n){return bt({command:e,args:t,cwd:n?.cwd,timeoutMs:n?.timeout,env:n?.env},{encoding:n?.encoding,input:n?.input})},executeAsync(e,t,n){re({command:e,args:t},n);},resolveInvocation(e,t){let n=ne({command:e,args:t});return {cmd:n.command,args:n.args??[]}},splitCommand:kt,spawnDetached(e,t){Et({command:e,args:t});}}}var oe=createRequire(import.meta.url);function ie(e){return typeof e=="object"?e:B(e)}function ae(e){let t=S.basename(String(e||"").trim());if(!t)throw new Error(`resolveYamlFlowCliPath: expected non-empty cli file name, got ${JSON.stringify(e)}`);let n=S.dirname(oe.resolve("yaml-flow/package.json")),r=S.join(n,"cli","node",t);if(!h.existsSync(r))throw new Error(`resolveYamlFlowCliPath: could not find ${t} under ${S.join(n,"cli","node")}`);return r}function K(e){let t=ie(e);return t.kind==="yaml-flow-cli"?ae(t.value):t.value}function ce(e,t){let n=K(e);switch(n){case "source-cli-task-executor":{let r=S.join(t,"source-cli-task-executor.js");if(h.existsSync(r))return {command:process.execPath,args:[r]};let s=S.join(t,"source-cli-task-executor.ts"),o=S.join(t,"..","..","node_modules","tsx","dist","cli.mjs"),a=S.join(t,"..","..","node_modules",".bin","tsx"),i=h.existsSync(o)?o:a;return h.existsSync(s)&&h.existsSync(i)?{command:process.execPath,args:[i,s]}:{command:process.execPath,args:[r]}}case "board-live-cards":{let{cmd:r,args:s}=At(t,"_",[]);return {command:r,args:s}}default:throw new Error(`resolveBuiltIn: unknown built-in name "${n}". Supported: source-cli-task-executor, board-live-cards`)}}function ue(e,t){if(e.howToRun==="built-in"){let{command:r,args:s}=ce(e.whatToRun,t);return {command:r,baseArgs:s}}let n=(typeof e.whatToRun=="object",K(e.whatToRun));switch(e.howToRun){case "local-node":return {command:process.execPath,baseArgs:[n]};case "local-python":return {command:process.platform==="win32"?"python":"python3",baseArgs:[n]};case "local-process":return {command:n,baseArgs:[]};default:throw new Error(`resolveBaseInvocation: howToRun "${e.howToRun}" is not a local transport`)}}function le(e,t){return ue(e,t)}function pe(e){let t=e.trim();if(!t)throw new Error("empty stdout");try{return JSON.parse(t)}catch{let n=t.split(/\r?\n/).filter(Boolean),r=n[n.length-1];return JSON.parse(r)}}function fe(e,t){return {...t,whatToRun:K(e.whatToRun),...e.extra?{extra:e.extra}:{}}}function de(e,t,n="invokeExecutionRef"){return ft(e,t,n)}function ge(e){return e&&typeof e=="object"&&!Array.isArray(e)&&typeof e.result=="string"&&e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e:{result:"success",data:e&&typeof e=="object"&&!Array.isArray(e)?e:{stdout:e}}}function L(e){return {result:"failure",data:{error:e}}}function N(e,t,n){let r=n?.label??"invokeExecutionRefSync",s=n?.cliDir??n?.cwd??process.cwd(),o;try{o=de(e.argsMassaging,fe(e,t),r);}catch(l){let g=l instanceof Error?l.message:String(l);return L(g)}let a;try{a=le(e,s);}catch(l){let g=l instanceof Error?l.message:String(l);return L(`[${r}] ref resolution failed: ${g}`)}let i=[...a.baseArgs,...o.cmdArgs??[]],c=JSON.stringify(o.stdin??t),u=jt(),f;try{f=u.executeSync(a.command,i,{timeout:n?.timeoutMs??3e4,encoding:"utf-8",cwd:n?.cwd,input:c});}catch(l){let g=l,y=(g.stderr?String(g.stderr):"").trim(),R=typeof g.status=="number"?g.status:"unknown",p=y||g.message;return L(`[${r}] ref exited with status ${R}${p?`: ${p}`:""}`)}try{return ge(pe(f))}catch{return {result:"success",data:{stdout:f.trim()}}}}var me={"local-node":N,"local-python":N,"local-process":N,"built-in":N};function he(e,t,n){let r=n?.syncTransports?.[e.howToRun]??me[e.howToRun];return r?r(e,t,n):L(`[${n?.label??"invokeExecutionRefSync"}] unsupported sync howToRun: ${e.howToRun}`)}function Ft(e,t,n){return he(e,t,n)}function we(e,t){if(process.platform!=="win32"){h.renameSync(e,t);return}let n=[10,20,40,80,160];for(let r=0;r<=n.length;r++)try{h.renameSync(e,t);return}catch(s){let o=s.code;if((o==="EPERM"||o==="EBUSY")&&r<n.length){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,n[r]);continue}throw s}}function Ct(e){function t(r){return S.join(e,...r.split("/"))+".json"}function n(r,s,o,a){if(h.existsSync(r))for(let i of h.readdirSync(r,{withFileTypes:true})){let c=s?`${s}/${i.name}`:i.name;if(i.isDirectory()){n(S.join(r,i.name),c,o,a);continue}if(!i.isFile()||!i.name.endsWith(".json"))continue;let u=c.replace(/\.json$/,"");(!o||u.startsWith(o))&&a.push(u);}}return {read(r){let s=t(r);if(!h.existsSync(s))return null;try{return JSON.parse(h.readFileSync(s,"utf-8"))}catch{return null}},write(r,s){let o=t(r),a=`${o}.${process.pid}.${randomUUID()}.tmp`;h.mkdirSync(S.dirname(o),{recursive:true}),h.writeFileSync(a,JSON.stringify(s,null,2),"utf-8"),we(a,o);},delete(r){let s=t(r);try{h.existsSync(s)&&h.unlinkSync(s);}catch{}},listKeys(r){let s=[];return n(e,"",r,s),s.sort()}}}var U=class extends Error{constructor(n,r){super(r);this.code=n;this.name="CliExitError";}code},Se=".pause";async function ir(e){let t=Re(e);if(t.help||e.length===0)throw Fe(),new U(e.length===0?1:0);let{flowArg:n,dataArg:r,persistRuntimeRefArg:s,resumeRequested:o,pauseRequested:a,statusRequested:i}=t;if((a||i)&&(r||o||n))throw new Error("[step-machine-cli] --pause and --status are store-level operations. Do not provide flow, data, or --resume.");if(o&&r)throw new Error("[step-machine-cli] --initial-data cannot be combined with --resume.");let c=xe(s);if(i){await be(c);return}if(a){await ve(c);return}if(!n)throw new Error("[step-machine-cli] Flow path is required for run/resume operations.");let u=Mt(n),f=S.dirname(u),l=Ee(r),{store:g}=c,y=await H(u),R=je(y,f);Tt(c);let p=new AbortController,d=false,v=P(y,R,{store:g,signal:p.signal,onStep:()=>{!d&&nt(c)&&(d=true,p.abort());}}),C;if(o){if(C=await $t(c),!C){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"&&!l&&(C=await $t(c));let m=C?await v.resume(C):await v.run(l);if(d&&m.status==="cancelled"){let T=await ke(g,m.runId);Tt(c),console.log(JSON.stringify({runId:m.runId,status:"paused",currentStep:T?.currentStep,pausedAt:T?.pausedAt,stepHistory:m.stepHistory,data:m.data},null,2));return}if(m.status!=="completed"){let T=m.error?.message??m.intent??m.status;throw console.error(`[step-machine-cli] Run failed: ${T}`),new U(1)}console.log(JSON.stringify({runId:m.runId,status:m.status,intent:m.intent,finalStep:m.finalStep,stepHistory:m.stepHistory,data:m.data},null,2));}function Re(e){let t=new Set(["--initial-data","--persist-runtime-ref"]),n={},r=[],s=false,o=false,a=false,i=false;for(let c=0;c<e.length;c++){let u=e[c];if(u==="-h"||u==="--help"){s=true;continue}if(u==="--resume"){o=true;continue}if(u==="--pause"){a=true;continue}if(u==="--status"){i=true;continue}if(t.has(u)){let f=e[c+1];if(!f||f.startsWith("--"))throw new Error(`[step-machine-cli] Missing value for ${u}.`);n[u]=f,c++;continue}if(u.startsWith("--"))throw new Error(`[step-machine-cli] Unknown flag: ${u}`);r.push(u);}if([o,a,i].filter(Boolean).length>1)throw new Error("[step-machine-cli] Use only one of --resume, --pause, or --status at a time.");return {help:s,flowArg:r[0],dataArg:n["--initial-data"],persistRuntimeRefArg:n["--persist-runtime-ref"],resumeRequested:o,pauseRequested:a,statusRequested:i}}function Mt(e){return S.isAbsolute(e)?e:S.resolve(process.cwd(),e)}function xe(e){if(!e)return {storeType:"memory",storeDir:void 0,pauseFilePath:void 0,persistRuntimeRef:void 0,store:new k};let t=B(e);if(t.kind!=="fs-path")throw new Error(`[step-machine-cli] --persist-runtime-ref must be an fs-path ref. Received kind "${t.kind}".`);let n=Mt(t.value),r=b({kind:"fs-path",value:n});return {storeType:"file",storeDir:n,pauseFilePath:S.join(n,Se),persistRuntimeRef:r,store:new $(Ct(n))}}async function et(e){if(!e.listRuns)return [];let t=await e.listRuns(),n=[];for(let r of t){let s=await e.loadRunState(r);s&&n.push(s);}return n.sort((r,s)=>(s.updatedAt??s.startedAt??0)-(r.updatedAt??r.startedAt??0)),n}function nt(e){return e.storeType!=="file"||!e.pauseFilePath?false:h.existsSync(e.pauseFilePath)}function Tt(e){nt(e)&&h.unlinkSync(e.pauseFilePath);}async function ve(e){if(e.storeType!=="file"||!e.pauseFilePath)throw new Error("[step-machine-cli] --pause requires --persist-runtime-ref <ref>.");let t=await et(e.store);if(t.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(!t.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}h.mkdirSync(e.storeDir,{recursive:true}),h.writeFileSync(e.pauseFilePath,JSON.stringify({requestedAt:Date.now()}),"utf-8"),console.log(JSON.stringify({status:"pause-requested",persistRuntimeRef:e.persistRuntimeRef},null,2));}async function $t(e){let n=(await et(e.store)).filter(r=>r.status==="paused");if(n.length!==0)return n.length>1&&console.warn("[step-machine-cli] Multiple paused runs found; resuming the most recently updated run."),n[0].runId}async function ke(e,t){let n=await e.loadRunState(t);if(!n)return null;let r={...n,status:"paused",pausedAt:Date.now(),updatedAt:Date.now()};return await e.saveRunState(t,r),r}async function be(e){if(e.storeType!=="file")throw new Error("[step-machine-cli] --status requires --persist-runtime-ref <ref>.");let t=await et(e.store),n={store:"file",persistRuntimeRef:e.persistRuntimeRef,pauseRequested:nt(e),totalRuns:t.length,runs:t.map(r=>({runId:r.runId,status:r.status,currentStep:r.currentStep,startedAt:r.startedAt,updatedAt:r.updatedAt,pausedAt:r.pausedAt}))};console.log(JSON.stringify(n,null,2));}function Ee(e){if(e)try{let t=JSON.parse(e);if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Initial data must be a JSON object.");return t}catch(t){let n=t instanceof Error?t.message:String(t);throw new Error(`[step-machine-cli] Invalid --initial-data value: ${n}`)}}function Ae(e){if(!e||typeof e!="object")return e;let t=e;if(typeof t.whatToRun!="string"||!t.whatToRun.startsWith("b64:"))return e;try{let n=t.whatToRun.slice(4),r=n+"=".repeat((4-n.length%4)%4),s=Buffer.from(r.replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8"),o=JSON.parse(s);return !o||typeof o!="object"||typeof o.value!="string"?e:{...t,whatToRun:o}}catch{return e}}function je(e,t){return D(e,{invoke:(r,s)=>Ft(Ae(r),s,{cliDir:t,cwd:t})})}function Fe(){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");}
|
|
4
|
-
export{U as CliExitError,
|
|
3
|
+
- `)}`);return t}function X(e){return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function st(e){return atob(e.replace(/-/g,"+").replace(/_/g,"/"))}var $=class{constructor(t){this.kv=t;}kv;stateKey(t){return `state_${X(t)}`}dataPrefix(t){return `data_${X(t)}_`}dataKey(t,n){return `${this.dataPrefix(t)}${X(n)}`}async saveRunState(t,n){this.kv.write(this.stateKey(t),n);}async loadRunState(t){let n=this.kv.read(this.stateKey(t));return n!=null&&typeof n=="object"?n:null}async deleteRunState(t){this.kv.delete(this.stateKey(t));for(let n of this.kv.listKeys(this.dataPrefix(t)))this.kv.delete(n);}async setData(t,n,r){this.kv.write(this.dataKey(t,n),r);}async getData(t,n){return this.kv.read(this.dataKey(t,n))}async getAllData(t){let n=this.dataPrefix(t),r={};for(let s of this.kv.listKeys(n))r[st(s.slice(n.length))]=this.kv.read(s);return r}async clearData(t){for(let n of this.kv.listKeys(this.dataPrefix(t)))this.kv.delete(n);}async listRuns(){return this.kv.listKeys("state_").map(t=>st(t.slice(6)))}};var it=dirname(fileURLToPath(import.meta.url)),Dt=createRequire(import.meta.url);function Nt(){let e=resolve(it,"./jsonata-sync.cjs");return existsSync(e)?e:resolve(it,"../card-compute/jsonata-sync.cjs")}var O=Dt(Nt());function at(e,t){if(!e||typeof e!="object")throw new Error(`[step-machine-public] Step "${t}" returned a non-object result.`);let n=e,r=n.result??n.status;if(typeof r=="string"&&r.trim().length>0){let s=n.data&&typeof n.data=="object"&&!Array.isArray(n.data)?{...n.data}:{},o=typeof n.error=="string"?n.error:void 0;return o&&!("error"in s)&&(s.error=o),{result:r,data:s,...o?{error:o}:{}}}return {result:"success",data:{...n}}}function ct(e,t){if(!t||t.length===0)return e;let n={};for(let r of t)Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function Z(e,t){return async(n,r)=>{let s=await e(n,r),o=at(s,r?.stepName??"unknown");return {result:o.result,data:ct(o.data,t),...o.error?{error:o.error}:{}}}}function ut(e,t,n){if(!t||t.length===0)return null;for(let r of t)try{if(!O(r).evaluate(e))return {result:"failure",data:{error:`[${n}] input validation failed: ${r}`}}}catch(s){let o=s instanceof Error?s.message:String(s);return {result:"failure",data:{error:`[${n}] input validation error on "${r}": ${o}`}}}return null}function Q(e,t,n){return !t||t.length===0?e:async(r,s)=>{let o=ut(r,t,n);return o||e(r,s)}}var pt=dirname(fileURLToPath(import.meta.url)),zt=createRequire(import.meta.url);function qt(){let e=resolve(pt,"./jsonata-sync.cjs");return existsSync(e)?e:resolve(pt,"../../card-compute/jsonata-sync.cjs")}var x=zt(qt());var J="b64:";function Wt(e){let t=new TextEncoder().encode(e),n=globalThis.Buffer,r;if(n)r=n.from(t).toString("base64");else if(typeof btoa=="function"){let s="";for(let o of t)s+=String.fromCharCode(o);r=btoa(s);}else throw new Error("No base64 encoder available in this runtime");return r.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function Gt(e){let t=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-e.length%4)%4),n=globalThis.Buffer;if(n)return n.from(t,"base64").toString("utf8");if(typeof atob=="function"){let r=atob(t),s=new Uint8Array(r.length);for(let o=0;o<r.length;o+=1)s[o]=r.charCodeAt(o);return new TextDecoder().decode(s)}throw new Error("No base64 decoder available in this runtime")}function b(e){return `${J}${Wt(JSON.stringify(e))}`}function B(e){if(!e.startsWith(J))throw new Error(`Invalid ref format (expected ${J}<base64url(json)>): ${e}`);let t;try{t=JSON.parse(Gt(e.slice(J.length)));}catch{throw new Error(`Invalid ref format (malformed base64url/json): ${e}`)}if(!t||typeof t!="object")throw new Error(`Invalid ref format (expected object payload): ${e}`);let n=t;if(typeof n.kind!="string"||typeof n.value!="string")throw new Error(`Invalid ref format (payload must contain string kind/value): ${e}`);return {kind:n.kind,value:n.value}}function E(e){e.registerFunction("fsPathRef",t=>b({kind:"fs-path",value:String(t)}),"<s:s>");}function ft(e,t,n){if(!e||typeof e!="object")return {};let r={};if(Array.isArray(e.cmdTemplate)){let s=[];for(let o of e.cmdTemplate)try{let a=x(o);E(a),s.push(String(a.evaluate(t)));}catch(a){let i=a instanceof Error?a.message:String(a);throw new Error(`[${n}] argsMassaging.cmdTemplate failed on "${o}": ${i}`)}r.cmdArgs=s;}if(typeof e.stdinTemplate=="string")try{let s=x(e.stdinTemplate);E(s),r.stdin=s.evaluate(t);}catch(s){let o=s instanceof Error?s.message:String(s);throw new Error(`[${n}] argsMassaging.stdinTemplate failed: ${o}`)}if(typeof e.urlTemplate=="string")try{let s=x(e.urlTemplate);E(s),r.url=String(s.evaluate(t));}catch(s){let o=s instanceof Error?s.message:String(s);throw new Error(`[${n}] argsMassaging.urlTemplate failed: ${o}`)}if(typeof e.headerTemplate=="string")try{let s=x(e.headerTemplate);E(s);let o=s.evaluate(t);if(typeof o!="object"||o===null)throw new Error(`headerTemplate must produce an object, got: ${JSON.stringify(o)}`);r.headers=o;}catch(s){let o=s instanceof Error?s.message:String(s);throw new Error(`[${n}] argsMassaging.headerTemplate failed: ${o}`)}if(typeof e.bodyTemplate=="string")try{let s=x(e.bodyTemplate);E(s),r.body=s.evaluate(t);}catch(s){let o=s instanceof Error?s.message:String(s);throw new Error(`[${n}] argsMassaging.bodyTemplate failed: ${o}`)}return r}function dt(e,t,n){if(!e||typeof e!="object")return t;let r={output:t},s=t.result,o=t.data,a=t.error;if(typeof e.resultExpr=="string")try{let i=x(e.resultExpr);E(i);let c=i.evaluate(r);if(typeof c!="string"||!c.trim())throw new Error(`resultExpr did not produce a non-empty string (got ${JSON.stringify(c)})`);s=c;}catch(i){let c=i instanceof Error?i.message:String(i);throw new Error(`[${n}] outputTransforms.resultExpr failed: ${c}`)}if(typeof e.dataTemplate=="string")try{let i=x(e.dataTemplate);E(i);let c=i.evaluate(r);if(!c||typeof c!="object"||Array.isArray(c))throw new Error(`dataTemplate did not produce an object (got ${JSON.stringify(c)})`);o=c;}catch(i){let c=i instanceof Error?i.message:String(i);throw new Error(`[${n}] outputTransforms.dataTemplate failed: ${c}`)}if(typeof e.errorExpr=="string")try{let i=x(e.errorExpr);E(i);let c=i.evaluate(r);a=c!=null?String(c):void 0;}catch(i){let c=i instanceof Error?i.message:String(i);throw new Error(`[${n}] outputTransforms.errorExpr failed: ${c}`)}return a!==void 0?{result:s,data:o,error:a}:{result:s,data:o}}function gt(e){return !!e&&typeof e=="object"&&e.type==="compute-jsonata"&&Array.isArray(e.expr)&&e.expr.length>0}function mt(e){if(!e||typeof e!="object")return false;let t=e;if(t.type!=="ref"||typeof t.howToRun!="string")return false;if(typeof t.whatToRun=="string")return true;if(t.whatToRun&&typeof t.whatToRun=="object"){let n=t.whatToRun;return typeof n.kind=="string"&&typeof n.value=="string"}return false}function Yt(e){if(typeof e=="string"){let t=e.indexOf("=");if(t<1)throw new Error(`[step-machine-public] Invalid compute expression (missing "="): "${e}"`);return {bindTo:e.slice(0,t).trim(),expr:e.slice(t+1).trim()}}if(e&&typeof e=="object"&&typeof e.bindTo=="string"&&typeof e.expr=="string")return e;throw new Error(`[step-machine-public] Invalid compute step: ${JSON.stringify(e)}`)}function Xt(e,t,n){let r=t.split("."),s=e;for(let o=0;o<r.length-1;o++){let a=r[o];(s[a]==null||typeof s[a]!="object")&&(s[a]={}),s=s[a];}s[r[r.length-1]]=n;}function ht(e,t,n){let r=e.expr.map(Yt);return async s=>{let o=s&&typeof s=="object"&&!Array.isArray(s)?{...s}:{},a={},i={expects_data:o,data:a,...n?{config:n}:{}},c,u;for(let f of r)try{let l=O(f.expr).evaluate(i);if(f.bindTo==="result")c=l!=null?String(l):"success";else if(f.bindTo==="error")u=l!=null?String(l):void 0;else if(f.bindTo.startsWith("data."))Xt(a,f.bindTo.slice(5),l);else return {result:"failure",data:{},error:`[${t}] invalid bindTo "${f.bindTo}": must be "result", "error", or start with "data."`}}catch(l){let g=l instanceof Error?l.message:String(l);return {result:"failure",data:{},error:`[${t}] compute "${f.bindTo}" failed: ${g}`}}return c===void 0?{result:"failure",data:{},error:`[${t}] compute-jsonata: no "result" binding declared \u2014 add '- result = "success"' to expr`}:u?{result:c,data:a,error:u}:{result:c,data:a}}}function yt(e,t,n,r){let{type:s,...o}=e,a={...o,whatToRun:typeof o.whatToRun=="object"?b(o.whatToRun):o.whatToRun};return async i=>{let c=i&&typeof i=="object"&&!Array.isArray(i)?{...i}:{};r&&(c.config=r);try{let u=await n(a,c);if(!e.outputTransforms)return u;try{return dt(e.outputTransforms,u,t)}catch(f){let l=f instanceof Error?f.message:String(f);return {result:"failure",data:{},error:l}}}catch(u){let f=u instanceof Error?u.message:String(u);return {result:"failure",data:{error:`[step-machine-public] step "${t}" invoke threw: ${f}`}}}}}function wt(){return async e=>({result:"success",data:e&&typeof e=="object"&&!Array.isArray(e)?e:{}})}function Zt(e,t,n){return async(r,s)=>{let o=r?.[t.items];if(!Array.isArray(o))return {result:"failure",data:{},error:`[${n}] forEach: "${t.items}" is not an array (got ${typeof o})`};let a=o,i=t.collectAs??`${t.items}_results`;if(a.length===0)return {result:"success",data:{[i]:[]}};let{[t.items]:c,...u}=r,f=Math.max(1,t.concurrency??1),l=new Array(a.length),g=0,y=0,R=0;return await new Promise(p=>{function d(){for(;g<f&&y<a.length;){let v=y++;g++;let T={...u,[t.as]:a[v]};e(T,s).then(m=>{l[v]=m;}).catch(m=>{let C=m instanceof Error?m.message:String(m);l[v]={result:"failure",data:{},error:C};}).finally(()=>{g--,l[v]?.result==="failure"&&R++,y>=a.length&&g===0?p():d();});}g===0&&y>=a.length&&p();}d();}),R>0?{result:"failure",data:{errors:l.filter(d=>d.result==="failure").map(d=>d.error)},error:`[${n}] forEach: ${R}/${a.length} items failed`}:{result:"success",data:{[i]:l.map(p=>p.data)}}}}function St(e,t,n){let r=Array.isArray(t?.produces_data)?t?.produces_data:void 0,s=Array.isArray(t?.input_validations)?t?.input_validations:void 0,o=t?.config??void 0,a=t?.handler,i;return gt(a)?i=ht(a,e,o):mt(a)?i=yt(a,e,n.invoke,o):i=wt(),t?.forEach&&(i=Zt(i,t.forEach,e)),Q(Z(i,r),s,e)}function D(e,t){let n={};for(let[r,s]of Object.entries(e.steps??{}))n[r]=St(r,s,t);return n}function ne(e){if(typeof e=="object"&&e!==null){let{command:n,args:r=[],...s}=e,o=xt(n,r);return {...s,command:o.command,args:o.args}}let t=kt(e);if(t.length===0)throw new Error(`Empty command spec: ${JSON.stringify(e)}`);return xt(t[0],t.slice(1))}function xt(e,t){return /^(node|node\.exe)$/i.test(e)?{command:process.execPath,args:t}:/\.m?js$/i.test(e)?{command:process.execPath,args:[e,...t]}:{command:e,args:t}}function kt(e){let t=[],n="",r=null;for(let s of e.trim()){if(r){s===r?r=null:n+=s;continue}if(s==='"'||s==="'"){r=s;continue}if(/\s/.test(s)){n&&(t.push(n),n="");continue}n+=s;}if(r)throw new Error(`Unterminated quote in command: ${e}`);return n&&t.push(n),t}function tt(e){return process.platform==="win32"&&/\.(cmd|bat)$/i.test(e)}function bt(e,t){let{command:n,args:r=[],cwd:s,env:o,timeoutMs:a}=e;return execFileSync(n,r,{shell:tt(n),timeout:a,encoding:t?.encoding??"utf-8",cwd:s,windowsHide:true,env:o?{...process.env,...o}:void 0,input:t?.input})}function re(e,t){let{command:n,args:r=[],cwd:s,env:o,timeoutMs:a=3e4}=e;execFile(n,r,{shell:tt(n),encoding:"utf8",windowsHide:true,timeout:a,maxBuffer:10*1024*1024,cwd:s,env:o?{...process.env,...o}:void 0},(i,c,u)=>t(i??null,c,u));}S.join(vt.tmpdir(),".board-live-cards-git-bash-cache.json");function Et(e){let{command:t,args:n=[]}=e;if(process.platform==="win32"){spawn(t,n,{detached:true,stdio:"ignore",windowsHide:true,shell:tt(t)}).unref();return}spawn(t,n,{detached:true,stdio:"ignore"}).unref();}function At(e,t,n){let r=S.join(e,"board-live-cards-cli.js");if(h.existsSync(r))return {cmd:process.execPath,args:[r,t,...n]};let s=S.join(e,"board-live-cards-cli.ts"),a=[S.join(e,"..","..","..","node_modules","tsx","dist","cli.mjs"),S.join(e,"..","..","node_modules","tsx","dist","cli.mjs"),S.join(e,"..","..","..","node_modules",".bin","tsx"),S.join(e,"..","..","node_modules",".bin","tsx")].find(c=>h.existsSync(c));return h.existsSync(s)&&h.existsSync(a)?{cmd:process.execPath,args:[a,s,t,...n]}:{cmd:process.platform==="win32"?"npx.cmd":"npx",args:["tsx",s,t,...n]}}function jt(){return {executeSync(e,t,n){return bt({command:e,args:t,cwd:n?.cwd,timeoutMs:n?.timeout,env:n?.env},{encoding:n?.encoding,input:n?.input})},executeAsync(e,t,n){re({command:e,args:t},n);},resolveInvocation(e,t){let n=ne({command:e,args:t});return {cmd:n.command,args:n.args??[]}},splitCommand:kt,spawnDetached(e,t){Et({command:e,args:t});}}}var oe=createRequire(import.meta.url);function ie(e){return typeof e=="object"?e:B(e)}function ae(e){let t=S.basename(String(e||"").trim());if(!t)throw new Error(`resolveYamlFlowCliPath: expected non-empty cli file name, got ${JSON.stringify(e)}`);let n=S.dirname(oe.resolve("yaml-flow/package.json")),r=S.join(n,"cli","node",t);if(!h.existsSync(r))throw new Error(`resolveYamlFlowCliPath: could not find ${t} under ${S.join(n,"cli","node")}`);return r}function K(e){let t=ie(e);return t.kind==="yaml-flow-cli"?ae(t.value):t.value}function ce(e,t){let n=K(e);switch(n){case "source-cli-task-executor":{let r=S.join(t,"source-cli-task-executor.js");if(h.existsSync(r))return {command:process.execPath,args:[r]};let s=S.join(t,"source-cli-task-executor.ts"),o=S.join(t,"..","..","node_modules","tsx","dist","cli.mjs"),a=S.join(t,"..","..","node_modules",".bin","tsx"),i=h.existsSync(o)?o:a;return h.existsSync(s)&&h.existsSync(i)?{command:process.execPath,args:[i,s]}:{command:process.execPath,args:[r]}}case "board-live-cards":{let{cmd:r,args:s}=At(t,"_",[]);return {command:r,args:s}}default:throw new Error(`resolveBuiltIn: unknown built-in name "${n}". Supported: source-cli-task-executor, board-live-cards`)}}function ue(e,t){if(e.howToRun==="built-in"){let{command:r,args:s}=ce(e.whatToRun,t);return {command:r,baseArgs:s}}let n=(typeof e.whatToRun=="object",K(e.whatToRun));switch(e.howToRun){case "local-node":return {command:process.execPath,baseArgs:[n]};case "local-python":return {command:process.platform==="win32"?"python":"python3",baseArgs:[n]};case "local-process":return {command:n,baseArgs:[]};default:throw new Error(`resolveBaseInvocation: howToRun "${e.howToRun}" is not a local transport`)}}function le(e,t){return ue(e,t)}function pe(e){let t=e.trim();if(!t)throw new Error("empty stdout");try{return JSON.parse(t)}catch{let n=t.split(/\r?\n/).filter(Boolean),r=n[n.length-1];return JSON.parse(r)}}function fe(e,t){return {...t,whatToRun:K(e.whatToRun),...e.extra?{extra:e.extra}:{}}}function de(e,t,n="invokeExecutionRef"){return ft(e,t,n)}function ge(e){return e&&typeof e=="object"&&!Array.isArray(e)&&typeof e.result=="string"&&e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e:{result:"success",data:e&&typeof e=="object"&&!Array.isArray(e)?e:{stdout:e}}}function L(e){return {result:"failure",data:{error:e}}}function N(e,t,n){let r=n?.label??"invokeExecutionRefSync",s=n?.cliDir??n?.cwd??process.cwd(),o;try{o=de(e.argsMassaging,fe(e,t),r);}catch(l){let g=l instanceof Error?l.message:String(l);return L(g)}let a;try{a=le(e,s);}catch(l){let g=l instanceof Error?l.message:String(l);return L(`[${r}] ref resolution failed: ${g}`)}let i=[...a.baseArgs,...o.cmdArgs??[]],c=JSON.stringify(o.stdin??t),u=jt(),f;try{f=u.executeSync(a.command,i,{timeout:n?.timeoutMs??3e4,encoding:"utf-8",cwd:n?.cwd,input:c});}catch(l){let g=l,y=(g.stderr?String(g.stderr):"").trim(),R=typeof g.status=="number"?g.status:"unknown",p=y||g.message;return L(`[${r}] ref exited with status ${R}${p?`: ${p}`:""}`)}try{return ge(pe(f))}catch{return {result:"success",data:{stdout:f.trim()}}}}var me={"local-node":N,"local-python":N,"local-process":N,"built-in":N};function he(e,t,n){let r=n?.syncTransports?.[e.howToRun]??me[e.howToRun];return r?r(e,t,n):L(`[${n?.label??"invokeExecutionRefSync"}] unsupported sync howToRun: ${e.howToRun}`)}function Ft(e,t,n){return he(e,t,n)}function we(e,t){if(process.platform!=="win32"){h.renameSync(e,t);return}let n=[10,20,40,80,160];for(let r=0;r<=n.length;r++)try{h.renameSync(e,t);return}catch(s){let o=s.code;if((o==="EPERM"||o==="EBUSY")&&r<n.length){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,n[r]);continue}throw s}}function Tt(e){function t(r){return S.join(e,...r.split("/"))+".json"}function n(r,s,o,a){if(h.existsSync(r))for(let i of h.readdirSync(r,{withFileTypes:true})){let c=s?`${s}/${i.name}`:i.name;if(i.isDirectory()){n(S.join(r,i.name),c,o,a);continue}if(!i.isFile()||!i.name.endsWith(".json"))continue;let u=c.replace(/\.json$/,"");(!o||u.startsWith(o))&&a.push(u);}}return {read(r){let s=t(r);if(!h.existsSync(s))return null;try{return JSON.parse(h.readFileSync(s,"utf-8"))}catch{return null}},write(r,s){let o=t(r),a=`${o}.${process.pid}.${randomUUID()}.tmp`;h.mkdirSync(S.dirname(o),{recursive:true}),h.writeFileSync(a,JSON.stringify(s,null,2),"utf-8"),we(a,o);},delete(r){let s=t(r);try{h.existsSync(s)&&h.unlinkSync(s);}catch{}},listKeys(r){let s=[];return n(e,"",r,s),s.sort()}}}var U=class extends Error{constructor(n,r){super(r);this.code=n;this.name="CliExitError";}code},Se=".pause",Re=3e5,xe="YAML_FLOW_STEP_INVOKE_TIMEOUT_MS";async function ur(e){let t=ve(e);if(t.help||e.length===0)throw $e(),new U(e.length===0?1:0);let{flowArg:n,dataArg:r,persistRuntimeRefArg:s,resumeRequested:o,pauseRequested:a,statusRequested:i}=t;if((a||i)&&(r||o||n))throw new Error("[step-machine-cli] --pause and --status are store-level operations. Do not provide flow, data, or --resume.");if(o&&r)throw new Error("[step-machine-cli] --initial-data cannot be combined with --resume.");let c=ke(s);if(i){await Ae(c);return}if(a){await be(c);return}if(!n)throw new Error("[step-machine-cli] Flow path is required for run/resume operations.");let u=Mt(n),f=S.dirname(u),l=je(r),{store:g}=c,y=await H(u),R=Ce(y,f);Ct(c);let p=new AbortController,d=false,v=P(y,R,{store:g,signal:p.signal,onStep:()=>{!d&&nt(c)&&(d=true,p.abort());}}),T;if(o){if(T=await $t(c),!T){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"&&!l&&(T=await $t(c));let m=T?await v.resume(T):await v.run(l);if(d&&m.status==="cancelled"){let C=await Ee(g,m.runId);Ct(c),console.log(JSON.stringify({runId:m.runId,status:"paused",currentStep:C?.currentStep,pausedAt:C?.pausedAt,stepHistory:m.stepHistory,data:m.data},null,2));return}if(m.status!=="completed"){let C=m.error?.message??m.intent??m.status;throw console.error(`[step-machine-cli] Run failed: ${C}`),new U(1)}console.log(JSON.stringify({runId:m.runId,status:m.status,intent:m.intent,finalStep:m.finalStep,stepHistory:m.stepHistory,data:m.data},null,2));}function ve(e){let t=new Set(["--initial-data","--persist-runtime-ref"]),n={},r=[],s=false,o=false,a=false,i=false;for(let c=0;c<e.length;c++){let u=e[c];if(u==="-h"||u==="--help"){s=true;continue}if(u==="--resume"){o=true;continue}if(u==="--pause"){a=true;continue}if(u==="--status"){i=true;continue}if(t.has(u)){let f=e[c+1];if(!f||f.startsWith("--"))throw new Error(`[step-machine-cli] Missing value for ${u}.`);n[u]=f,c++;continue}if(u.startsWith("--"))throw new Error(`[step-machine-cli] Unknown flag: ${u}`);r.push(u);}if([o,a,i].filter(Boolean).length>1)throw new Error("[step-machine-cli] Use only one of --resume, --pause, or --status at a time.");return {help:s,flowArg:r[0],dataArg:n["--initial-data"],persistRuntimeRefArg:n["--persist-runtime-ref"],resumeRequested:o,pauseRequested:a,statusRequested:i}}function Mt(e){return S.isAbsolute(e)?e:S.resolve(process.cwd(),e)}function ke(e){if(!e)return {storeType:"memory",storeDir:void 0,pauseFilePath:void 0,persistRuntimeRef:void 0,store:new k};let t=B(e);if(t.kind!=="fs-path")throw new Error(`[step-machine-cli] --persist-runtime-ref must be an fs-path ref. Received kind "${t.kind}".`);let n=Mt(t.value),r=b({kind:"fs-path",value:n});return {storeType:"file",storeDir:n,pauseFilePath:S.join(n,Se),persistRuntimeRef:r,store:new $(Tt(n))}}async function et(e){if(!e.listRuns)return [];let t=await e.listRuns(),n=[];for(let r of t){let s=await e.loadRunState(r);s&&n.push(s);}return n.sort((r,s)=>(s.updatedAt??s.startedAt??0)-(r.updatedAt??r.startedAt??0)),n}function nt(e){return e.storeType!=="file"||!e.pauseFilePath?false:h.existsSync(e.pauseFilePath)}function Ct(e){nt(e)&&h.unlinkSync(e.pauseFilePath);}async function be(e){if(e.storeType!=="file"||!e.pauseFilePath)throw new Error("[step-machine-cli] --pause requires --persist-runtime-ref <ref>.");let t=await et(e.store);if(t.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(!t.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}h.mkdirSync(e.storeDir,{recursive:true}),h.writeFileSync(e.pauseFilePath,JSON.stringify({requestedAt:Date.now()}),"utf-8"),console.log(JSON.stringify({status:"pause-requested",persistRuntimeRef:e.persistRuntimeRef},null,2));}async function $t(e){let n=(await et(e.store)).filter(r=>r.status==="paused");if(n.length!==0)return n.length>1&&console.warn("[step-machine-cli] Multiple paused runs found; resuming the most recently updated run."),n[0].runId}async function Ee(e,t){let n=await e.loadRunState(t);if(!n)return null;let r={...n,status:"paused",pausedAt:Date.now(),updatedAt:Date.now()};return await e.saveRunState(t,r),r}async function Ae(e){if(e.storeType!=="file")throw new Error("[step-machine-cli] --status requires --persist-runtime-ref <ref>.");let t=await et(e.store),n={store:"file",persistRuntimeRef:e.persistRuntimeRef,pauseRequested:nt(e),totalRuns:t.length,runs:t.map(r=>({runId:r.runId,status:r.status,currentStep:r.currentStep,startedAt:r.startedAt,updatedAt:r.updatedAt,pausedAt:r.pausedAt}))};console.log(JSON.stringify(n,null,2));}function je(e){if(e)try{let t=JSON.parse(e);if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Initial data must be a JSON object.");return t}catch(t){let n=t instanceof Error?t.message:String(t);throw new Error(`[step-machine-cli] Invalid --initial-data value: ${n}`)}}function Fe(e){if(!e||typeof e!="object")return e;let t=e;if(typeof t.whatToRun!="string"||!t.whatToRun.startsWith("b64:"))return e;try{let n=t.whatToRun.slice(4),r=n+"=".repeat((4-n.length%4)%4),s=Buffer.from(r.replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8"),o=JSON.parse(s);return !o||typeof o!="object"||typeof o.value!="string"?e:{...t,whatToRun:o}}catch{return e}}function Te(e){let t=e.settings?.invoke_timeout_ms;if(typeof t=="number"&&Number.isFinite(t)&&t>=0)return Math.trunc(t);let n=process.env[xe];if(n){let r=Number(n);if(Number.isFinite(r)&&r>=0)return Math.trunc(r)}return Re}function Ce(e,t){let n=Te(e);return D(e,{invoke:(s,o)=>Ft(Fe(s),o,{cliDir:t,cwd:t,timeoutMs:n})})}function $e(){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");}
|
|
4
|
+
export{U as CliExitError,ur as cli,Te as resolveStepInvokeTimeoutMs};//# sourceMappingURL=step-machine-cli.js.map
|
|
5
5
|
//# sourceMappingURL=step-machine-cli.js.map
|
|
@@ -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.
|
|
23
|
-
<script src="https://cdn.jsdelivr.net/npm/yaml-flow@8.4.
|
|
22
|
+
<script src="https://cdn.jsdelivr.net/npm/yaml-flow@8.4.8/browser/live-cards.js"></script>
|
|
23
|
+
<script src="https://cdn.jsdelivr.net/npm/yaml-flow@8.4.8/browser/board-livecards-client.js"></script>
|
|
24
24
|
</head>
|
|
25
25
|
<body class="bg-light">
|
|
26
26
|
<div class="container-fluid py-3">
|
package/examples/board/doc.html
CHANGED
|
@@ -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.
|
|
41
|
-
<script src="https://cdn.jsdelivr.net/npm/yaml-flow@8.4.
|
|
40
|
+
<script src="https://cdn.jsdelivr.net/npm/yaml-flow@8.4.8/browser/live-cards.js"></script>
|
|
41
|
+
<script src="https://cdn.jsdelivr.net/npm/yaml-flow@8.4.8/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.
|
|
9
|
+
<script src="https://cdn.jsdelivr.net/npm/yaml-flow@8.4.8/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.
|
|
15
|
-
<script src="https://cdn.jsdelivr.net/npm/yaml-flow@8.4.
|
|
14
|
+
<script src="https://cdn.jsdelivr.net/npm/yaml-flow@8.4.8/browser/live-cards.js"></script>
|
|
15
|
+
<script src="https://cdn.jsdelivr.net/npm/yaml-flow@8.4.8/browser/board-livecards-localstorage.js"></script>
|
|
16
16
|
</head>
|
|
17
17
|
<body class="bg-light">
|
|
18
18
|
<div class="container-fluid py-3">
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { C as CommandInput, a as CommandResult } from './board-live-cards-public-CU8VVw3v.cjs';
|
|
2
|
-
import { A as ArtifactInfo, a as ArtifactsStore } from './artifacts-store-lib-
|
|
2
|
+
import { A as ArtifactInfo, a as ArtifactsStore } from './artifacts-store-lib-WdoKNAF0.cjs';
|
|
3
3
|
import './storage-interface-B-7pDHwD.cjs';
|
|
4
4
|
import './execution-refs.cjs';
|
|
5
5
|
import './types-BBhqYGhE.cjs';
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { C as CommandInput, a as CommandResult } from './board-live-cards-public-Crjm8KWn.js';
|
|
2
|
-
import { A as ArtifactInfo, a as ArtifactsStore } from './artifacts-store-lib-
|
|
2
|
+
import { A as ArtifactInfo, a as ArtifactsStore } from './artifacts-store-lib-CXgRA5J7.js';
|
|
3
3
|
import './storage-interface-B-7pDHwD.js';
|
|
4
4
|
import './execution-refs.js';
|
|
5
5
|
import './types-BBhqYGhE.js';
|