yaml-flow 8.4.3 → 8.4.5
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 +5 -5
- package/cli/{board-live-cards-lib-tjYsPt5U.d.ts → board-live-cards-lib-COi4bSpk.d.ts} +1 -0
- package/cli/browser-api/board-live-cards-browser-adapter.d.ts +2 -2
- package/cli/browser-api/card-store-browser-api.d.ts +1 -1
- package/cli/browser-api/card-store-browser-api.js +1 -1
- package/cli/node/artifacts-store-cli.js +2 -2
- package/cli/node/batch-runner-cli.js +1 -1
- package/cli/node/board-live-cards-cli.js +10 -10
- package/cli/node/card-store-cli.js +2 -2
- package/cli/node/chat-store-cli.d.ts +9 -9
- package/cli/node/chat-store-cli.js +7 -7
- package/cli/node/execution-adapter.js +2 -2
- package/cli/node/fs-board-adapter.d.ts +4 -4
- package/cli/node/fs-board-adapter.js +10 -10
- package/cli/node/step-machine-cli.js +3 -3
- package/cli/{types-Dc2VRMUw.d.ts → types-BkJvnXVD.d.ts} +1 -1
- package/examples/board/demo-shell-with-server.html +2 -2
- package/examples/board/doc.html +2 -2
- package/examples/board/server/chat-flow/flow-steps.json +8 -4
- package/examples/board-local/demo-shell-localstorage.html +3 -3
- 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 +10 -10
- 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 +10 -10
- package/lib/{board-live-cards-public-BM6jCEIa.d.cts → board-live-cards-public-CU8VVw3v.d.cts} +1 -0
- package/lib/{board-live-cards-public-Bz07XKRK.d.ts → board-live-cards-public-Crjm8KWn.d.ts} +1 -0
- package/lib/board-live-cards-public.cjs +2 -2
- package/lib/board-live-cards-public.d.cts +1 -1
- package/lib/board-live-cards-public.d.ts +1 -1
- package/lib/board-live-cards-public.js +2 -2
- 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/card-store-public.d.cts +1 -1
- package/lib/card-store-public.d.ts +1 -1
- package/lib/chat-store-public.d.cts +2 -2
- package/lib/chat-store-public.d.ts +2 -2
- 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-public/index.cjs +3 -3
- package/lib/step-machine-public/index.js +3 -3
- package/lib/{types-Cn0b8G-i.d.ts → types-BC8ZnA6i.d.ts} +1 -1
- package/lib/{types-Dszjwfud.d.cts → types-DX8wXuZ0.d.cts} +1 -1
- package/package.json +1 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import'ajv-formats';import {createRequire}from'module';import {fileURLToPath}from'url';import {dirname,resolve}from'path';import {existsSync}from'fs';function b(r,t,e,n){let s=r.steps[e];if(!s)throw new Error(`Step "${e}" not found in flow configuration`);if(n.result==="failure"&&s.retry){let a=t.retryCounts[e]??0;if(a<s.retry.max_attempts)return {newState:{...t,retryCounts:{...t.retryCounts,[e]:a+1},updatedAt:Date.now()},nextStep:e,isTerminal:false,isCircuitBroken:false,shouldRetry:true}}let o=s.failure_transitions?.[n.result]??s.transitions[n.result];if(!o)throw new Error(`No transition defined for result "${n.result}" in step "${e}"`);let i=!!r.terminal_states[o];return {newState:{...t,currentStep:o,stepHistory:[...t.stepHistory,e],retryCounts:{...t.retryCounts,[e]:0},updatedAt:Date.now()},nextStep:o,isTerminal:i,isCircuitBroken:false,shouldRetry:false}}function j(r,t,e){let n=r.steps[e];if(!n?.circuit_breaker)return {broken:false,newState:{...t,iterationCounts:{...t.iterationCounts,[e]:(t.iterationCounts[e]??0)+1},updatedAt:Date.now()}};let s=t.iterationCounts[e]??0;return s>=n.circuit_breaker.max_iterations?{broken:true,redirectStep:n.circuit_breaker.on_open,newState:{...t,currentStep:n.circuit_breaker.on_open,updatedAt:Date.now()}}:{broken:false,newState:{...t,iterationCounts:{...t.iterationCounts,[e]:s+1},updatedAt:Date.now()}}}function F(r,t,e){let n=r.steps[t];if(!n)throw new Error(`Step "${t}" not found`);if(n.expects_data){let s={};for(let o of n.expects_data)s[o]=e[o];return s}return {...e}}function C(r,t){if(r===false||r===void 0)return {};if(typeof r=="string")return {[r]:t[r]};if(Array.isArray(r)){let e={};for(let n of r)e[n]=t[n];return e}return {}}function E(r,t){let e=Date.now();return {runId:t,flowId:r.id??"unnamed",currentStep:r.settings.start_step,status:"running",stepHistory:[],iterationCounts:{},retryCounts:{},startedAt:e,updatedAt:e}}var h=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,n){this.data.has(t)||this.data.set(t,{});let s=this.data.get(t);s[e]=n;}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 et(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let t=Math.random()*16|0;return (r==="x"?t:t&3|8).toString(16)})}var x=class{flow;handlers;store;components;options;listeners=new Map;aborted=false;constructor(t,e,n={}){this.flow=t,this.handlers=new Map(Object.entries(e)),this.store=n.store??new h,this.components=n.components??{},this.options=n,n.signal&&n.signal.addEventListener("abort",()=>{this.aborted=true;}),this.validateFlow();}validateFlow(){let{settings:t,steps:e,terminal_states:n}=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(!n||Object.keys(n).length===0)throw new Error("Flow must have at least one terminal_state defined");if(!e[t.start_step]&&!n[t.start_step])throw new Error(`Start step "${t.start_step}" not found`);for(let[s,o]of Object.entries(e)){for(let[i,a]of Object.entries(o.transitions))if(!e[a]&&!n[a])throw new Error(`Step "${s}" transition "${i}" points to unknown step "${a}"`);if(o.failure_transitions){for(let[i,a]of Object.entries(o.failure_transitions))if(!e[a]&&!n[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 n of e)try{n(t);}catch{}}sleep(t){return new Promise(e=>setTimeout(e,t))}async run(t){let e=et(),n=E(this.flow,e);if(await this.store.saveRunState(e,n),t)for(let[s,o]of Object.entries(t))await this.store.setData(e,s,o);this.emit({type:"flow:start",runId:e,timestamp:n.startedAt,data:{initialData:t??{}}});try{return await this.executeLoop(e,n)}catch(s){let o=s instanceof Error?s:new Error(String(s));return this.emit({type:"flow:error",runId:e,timestamp:Date.now(),data:{error:o.message}}),this.options.onError?.(o),n={...n,status:"failed",updatedAt:Date.now()},await this.store.saveRunState(e,n),{runId:e,status:"failed",data:await this.store.getAllData(e),finalStep:n.currentStep,stepHistory:n.stepHistory,durationMs:Date.now()-n.startedAt,error:o}}}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 n={...e,status:"running",pausedAt:void 0,updatedAt:Date.now()};return await this.store.saveRunState(t,n),this.emit({type:"flow:resumed",runId:t,timestamp:Date.now(),data:{currentStep:n.currentStep}}),this.executeLoop(t,n)}async pause(t){let e=await this.store.loadRunState(t);if(!e)throw new Error(`No run found with ID: ${t}`);let n={...e,status:"paused",pausedAt:Date.now(),updatedAt:Date.now()};await this.store.saveRunState(t,n),this.emit({type:"flow:paused",runId:t,timestamp:Date.now(),data:{currentStep:n.currentStep}});}async executeLoop(t,e){let n=this.flow.settings.max_total_steps??100,s=this.flow.settings.timeout_ms,o=e,i=0;for(;i<n;){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 a=o.currentStep,c=this.flow.terminal_states[a];if(c){o={...o,status:"completed",updatedAt:Date.now()},await this.store.saveRunState(t,o);let p=await this.store.getAllData(t),l={runId:t,status:"completed",intent:c.return_intent,data:C(c.return_artifacts,p),finalStep:a,stepHistory:o.stepHistory,durationMs:Date.now()-o.startedAt};return this.emit({type:"flow:complete",runId:t,timestamp:Date.now(),data:{...l}}),this.options.onComplete?.(l),l}let d=j(this.flow,o,a);if(d.broken){o=d.newState,await this.store.saveRunState(t,o),i++;continue}o=d.newState;let f=await this.store.getAllData(t),u=F(this.flow,a,f),m={runId:t,stepName:a,components:this.components,store:this.store,signal:this.options.signal,emit:(p,l)=>{this.emit({type:"step:complete",runId:t,timestamp:Date.now(),data:{event:p,payload:l}});}};this.emit({type:"step:start",runId:t,timestamp:Date.now(),data:{step:a,input:u}});let g;try{let p=this.handlers.get(a);if(!p)throw new Error(`No handler registered for step "${a}"`);g=await p(u,m);}catch(p){let l=p instanceof Error?p:new Error(String(p));this.emit({type:"step:error",runId:t,timestamp:Date.now(),data:{step:a,error:l.message}}),g={result:"failure",data:{error:l.message}};}if(g.data)for(let[p,l]of Object.entries(g.data))await this.store.setData(t,p,l);this.emit({type:"step:complete",runId:t,timestamp:Date.now(),data:{step:a,result:g.result}}),this.options.onStep?.(a,g);let w=b(this.flow,o,a,g);if(o=w.newState,w.shouldRetry){await this.store.saveRunState(t,o);let p=this.flow.steps[a];if(p.retry?.delay_ms){let l=o.retryCounts[a]??0,S=p.retry.backoff_multiplier?p.retry.delay_ms*Math.pow(p.retry.backoff_multiplier,l-1):p.retry.delay_ms;await this.sleep(S);}i++;continue}await this.store.saveRunState(t,o),this.emit({type:"transition",runId:t,timestamp:Date.now(),data:{from:a,to:o.currentStep,result:g.result}}),this.options.onTransition?.(a,o.currentStep),i++;}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 v(r,t,e){return new x(r,t,e)}async function $(r){return (await import('yaml')).parse(r)}async function rt(r){let t=await fetch(r);if(!t.ok)throw new Error(`Failed to load flow from ${r}: ${t.statusText}`);let e=t.headers.get("content-type")??"",n=await t.text();return e.includes("json")||r.endsWith(".json")?JSON.parse(n):$(n)}async function nt(r){let e=await(await import('fs/promises')).readFile(r,"utf-8");return r.endsWith(".json")?JSON.parse(e):$(e)}function D(r){let t=[];if(!r||typeof r!="object")return ["Flow must be an object"];let e=r;if(!e.settings||typeof e.settings!="object"?t.push('Flow must have a "settings" object'):typeof e.settings.start_step!="string"&&t.push("settings.start_step must be a string"),!e.steps||typeof e.steps!="object")t.push('Flow must have a "steps" object');else {let n=e.steps;for(let[s,o]of Object.entries(n)){if(!o||typeof o!="object"){t.push(`Step "${s}" must be an object`);continue}let i=o;(!i.transitions||typeof i.transitions!="object")&&t.push(`Step "${s}" must have a "transitions" object`),i.failure_transitions!==void 0&&typeof i.failure_transitions!="object"&&t.push(`Step "${s}" failure_transitions must be an object when provided`);}}if(!e.terminal_states||typeof e.terminal_states!="object")t.push('Flow must have a "terminal_states" object');else {let n=e.terminal_states;for(let[s,o]of Object.entries(n)){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 P(r){let t;typeof r=="string"?r.startsWith("http://")||r.startsWith("https://")?t=await rt(r):r.includes("{")?t=JSON.parse(r):t=await nt(r):t=r;let e=D(t);if(e.length>0)throw new Error(`Invalid step flow configuration:
|
|
1
|
+
import'ajv-formats';import {createRequire}from'module';import {fileURLToPath}from'url';import {dirname,resolve}from'path';import {existsSync}from'fs';function j(r,t,e,n){let s=r.steps[e];if(!s)throw new Error(`Step "${e}" not found in flow configuration`);if(n.result==="failure"&&s.retry){let a=t.retryCounts[e]??0;if(a<s.retry.max_attempts)return {newState:{...t,retryCounts:{...t.retryCounts,[e]:a+1},updatedAt:Date.now()},nextStep:e,isTerminal:false,isCircuitBroken:false,shouldRetry:true}}let o=s.failure_transitions?.[n.result]??s.transitions[n.result];if(!o)throw new Error(`No transition defined for result "${n.result}" in step "${e}"`);let i=!!r.terminal_states[o];return {newState:{...t,currentStep:o,stepHistory:[...t.stepHistory,e],retryCounts:{...t.retryCounts,[e]:0},updatedAt:Date.now()},nextStep:o,isTerminal:i,isCircuitBroken:false,shouldRetry:false}}function F(r,t,e){let n=r.steps[e];if(!n?.circuit_breaker)return {broken:false,newState:{...t,iterationCounts:{...t.iterationCounts,[e]:(t.iterationCounts[e]??0)+1},updatedAt:Date.now()}};let s=t.iterationCounts[e]??0;return s>=n.circuit_breaker.max_iterations?{broken:true,redirectStep:n.circuit_breaker.on_open,newState:{...t,currentStep:n.circuit_breaker.on_open,updatedAt:Date.now()}}:{broken:false,newState:{...t,iterationCounts:{...t.iterationCounts,[e]:s+1},updatedAt:Date.now()}}}function C(r,t,e){let n=r.steps[t];if(!n)throw new Error(`Step "${t}" not found`);if(n.expects_data){let s={};for(let o of n.expects_data)s[o]=e[o];return s}return {...e}}function E(r,t){if(r===false||r===void 0)return {};if(typeof r=="string")return {[r]:t[r]};if(Array.isArray(r)){let e={};for(let n of r)e[n]=t[n];return e}return {}}function _(r,t){let e=Date.now();return {runId:t,flowId:r.id??"unnamed",currentStep:r.settings.start_step,status:"running",stepHistory:[],iterationCounts:{},retryCounts:{},startedAt:e,updatedAt:e}}var h=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,n){this.data.has(t)||this.data.set(t,{});let s=this.data.get(t);s[e]=n;}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 rt(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let t=Math.random()*16|0;return (r==="x"?t:t&3|8).toString(16)})}var v=class{flow;handlers;store;components;options;listeners=new Map;aborted=false;constructor(t,e,n={}){this.flow=t,this.handlers=new Map(Object.entries(e)),this.store=n.store??new h,this.components=n.components??{},this.options=n,n.signal&&n.signal.addEventListener("abort",()=>{this.aborted=true;}),this.validateFlow();}validateFlow(){let{settings:t,steps:e,terminal_states:n}=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(!n||Object.keys(n).length===0)throw new Error("Flow must have at least one terminal_state defined");if(!e[t.start_step]&&!n[t.start_step])throw new Error(`Start step "${t.start_step}" not found`);for(let[s,o]of Object.entries(e)){for(let[i,a]of Object.entries(o.transitions))if(!e[a]&&!n[a])throw new Error(`Step "${s}" transition "${i}" points to unknown step "${a}"`);if(o.failure_transitions){for(let[i,a]of Object.entries(o.failure_transitions))if(!e[a]&&!n[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 n of e)try{n(t);}catch{}}sleep(t){return new Promise(e=>setTimeout(e,t))}async run(t){let e=rt(),n=_(this.flow,e);if(await this.store.saveRunState(e,n),t)for(let[s,o]of Object.entries(t))await this.store.setData(e,s,o);this.emit({type:"flow:start",runId:e,timestamp:n.startedAt,data:{initialData:t??{}}});try{return await this.executeLoop(e,n)}catch(s){let o=s instanceof Error?s:new Error(String(s));return this.emit({type:"flow:error",runId:e,timestamp:Date.now(),data:{error:o.message}}),this.options.onError?.(o),n={...n,status:"failed",updatedAt:Date.now()},await this.store.saveRunState(e,n),{runId:e,status:"failed",data:await this.store.getAllData(e),finalStep:n.currentStep,stepHistory:n.stepHistory,durationMs:Date.now()-n.startedAt,error:o}}}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 n={...e,status:"running",pausedAt:void 0,updatedAt:Date.now()};return await this.store.saveRunState(t,n),this.emit({type:"flow:resumed",runId:t,timestamp:Date.now(),data:{currentStep:n.currentStep}}),this.executeLoop(t,n)}async pause(t){let e=await this.store.loadRunState(t);if(!e)throw new Error(`No run found with ID: ${t}`);let n={...e,status:"paused",pausedAt:Date.now(),updatedAt:Date.now()};await this.store.saveRunState(t,n),this.emit({type:"flow:paused",runId:t,timestamp:Date.now(),data:{currentStep:n.currentStep}});}async executeLoop(t,e){let n=this.flow.settings.max_total_steps??100,s=this.flow.settings.timeout_ms,o=e,i=0;for(;i<n;){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 a=o.currentStep,p=this.flow.terminal_states[a];if(p){o={...o,status:"completed",updatedAt:Date.now()},await this.store.saveRunState(t,o);let u=await this.store.getAllData(t),c={runId:t,status:"completed",intent:p.return_intent,data:E(p.return_artifacts,u),finalStep:a,stepHistory:o.stepHistory,durationMs:Date.now()-o.startedAt};return this.emit({type:"flow:complete",runId:t,timestamp:Date.now(),data:{...c}}),this.options.onComplete?.(c),c}let d=F(this.flow,o,a);if(d.broken){o=d.newState,await this.store.saveRunState(t,o),i++;continue}o=d.newState;let f=await this.store.getAllData(t),l=C(this.flow,a,f),m={runId:t,stepName:a,components:this.components,store:this.store,signal:this.options.signal,emit:(u,c)=>{this.emit({type:"step:complete",runId:t,timestamp:Date.now(),data:{event:u,payload:c}});}};this.emit({type:"step:start",runId:t,timestamp:Date.now(),data:{step:a,input:l}});let g;try{let u=this.handlers.get(a);if(!u)throw new Error(`No handler registered for step "${a}"`);g=await u(l,m);}catch(u){let c=u instanceof Error?u:new Error(String(u));this.emit({type:"step:error",runId:t,timestamp:Date.now(),data:{step:a,error:c.message}}),g={result:"failure",data:{error:c.message}};}if(g.data)for(let[u,c]of Object.entries(g.data))await this.store.setData(t,u,c);this.emit({type:"step:complete",runId:t,timestamp:Date.now(),data:{step:a,result:g.result}}),this.options.onStep?.(a,g);let w=j(this.flow,o,a,g);if(o=w.newState,w.shouldRetry){await this.store.saveRunState(t,o);let u=this.flow.steps[a];if(u.retry?.delay_ms){let c=o.retryCounts[a]??0,S=u.retry.backoff_multiplier?u.retry.delay_ms*Math.pow(u.retry.backoff_multiplier,c-1):u.retry.delay_ms;await this.sleep(S);}i++;continue}await this.store.saveRunState(t,o),this.emit({type:"transition",runId:t,timestamp:Date.now(),data:{from:a,to:o.currentStep,result:g.result}}),this.options.onTransition?.(a,o.currentStep),i++;}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 x(r,t,e){return new v(r,t,e)}async function $(r){return (await import('yaml')).parse(r)}async function nt(r){let t=await fetch(r);if(!t.ok)throw new Error(`Failed to load flow from ${r}: ${t.statusText}`);let e=t.headers.get("content-type")??"",n=await t.text();return e.includes("json")||r.endsWith(".json")?JSON.parse(n):$(n)}async function ot(r){let e=await(await import('fs/promises')).readFile(r,"utf-8");return r.endsWith(".json")?JSON.parse(e):$(e)}function O(r){let t=[];if(!r||typeof r!="object")return ["Flow must be an object"];let e=r;if(!e.settings||typeof e.settings!="object"?t.push('Flow must have a "settings" object'):typeof e.settings.start_step!="string"&&t.push("settings.start_step must be a string"),!e.steps||typeof e.steps!="object")t.push('Flow must have a "steps" object');else {let n=e.steps;for(let[s,o]of Object.entries(n)){if(!o||typeof o!="object"){t.push(`Step "${s}" must be an object`);continue}let i=o;(!i.transitions||typeof i.transitions!="object")&&t.push(`Step "${s}" must have a "transitions" object`),i.failure_transitions!==void 0&&typeof i.failure_transitions!="object"&&t.push(`Step "${s}" failure_transitions must be an object when provided`);}}if(!e.terminal_states||typeof e.terminal_states!="object")t.push('Flow must have a "terminal_states" object');else {let n=e.terminal_states;for(let[s,o]of Object.entries(n)){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 J(r){let t;typeof r=="string"?r.startsWith("http://")||r.startsWith("https://")?t=await nt(r):r.includes("{")?t=JSON.parse(r):t=await ot(r):t=r;let e=O(t);if(e.length>0)throw new Error(`Invalid step flow configuration:
|
|
2
2
|
- ${e.join(`
|
|
3
|
-
- `)}`);return t}function A(r){return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function
|
|
4
|
-
export{M as KVStorageStore,h as MemoryStore,
|
|
3
|
+
- `)}`);return t}function A(r){return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function B(r){return atob(r.replace(/-/g,"+").replace(/_/g,"/"))}var M=class{constructor(t){this.kv=t;}kv;stateKey(t){return `state_${A(t)}`}dataPrefix(t){return `data_${A(t)}_`}dataKey(t,e){return `${this.dataPrefix(t)}${A(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,n){this.kv.write(this.dataKey(t,e),n);}async getData(t,e){return this.kv.read(this.dataKey(t,e))}async getAllData(t){let e=this.dataPrefix(t),n={};for(let s of this.kv.listKeys(e))n[B(s.slice(e.length))]=this.kv.read(s);return n}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=>B(t.slice(6)))}};var z=dirname(fileURLToPath(import.meta.url)),ut=createRequire(import.meta.url);function lt(){let r=resolve(z,"./jsonata-sync.cjs");return existsSync(r)?r:resolve(z,"../card-compute/jsonata-sync.cjs")}var k=ut(lt());function V(r,t){if(!r||typeof r!="object")throw new Error(`[step-machine-public] Step "${t}" returned a non-object result.`);let e=r,n=e.result??e.status;if(typeof n=="string"&&n.trim().length>0){let s=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?{...e.data}:{},o=typeof e.error=="string"?e.error:void 0;return o&&!("error"in s)&&(s.error=o),{result:n,data:s,...o?{error:o}:{}}}return {result:"success",data:{...e}}}function L(r,t){if(!t||t.length===0)return r;let e={};for(let n of t)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n]);return e}function T(r,t){return async(e,n)=>{let s=await r(e,n),o=V(s,n?.stepName??"unknown");return {result:o.result,data:L(o.data,t),...o.error?{error:o.error}:{}}}}function N(r,t,e){if(!t||t.length===0)return null;for(let n of t)try{if(!k(n).evaluate(r))return {result:"failure",data:{error:`[${e}] input validation failed: ${n}`}}}catch(s){let o=s instanceof Error?s.message:String(s);return {result:"failure",data:{error:`[${e}] input validation error on "${n}": ${o}`}}}return null}function H(r,t,e){return !t||t.length===0?r:async(n,s)=>{let o=N(n,t,e);return o||r(n,s)}}var W=dirname(fileURLToPath(import.meta.url)),mt=createRequire(import.meta.url);function ht(){let r=resolve(W,"./jsonata-sync.cjs");return existsSync(r)?r:resolve(W,"../../card-compute/jsonata-sync.cjs")}var R=mt(ht());var wt="b64:";function St(r){let t=new TextEncoder().encode(r),e=globalThis.Buffer,n;if(e)n=e.from(t).toString("base64");else if(typeof btoa=="function"){let s="";for(let o of t)s+=String.fromCharCode(o);n=btoa(s);}else throw new Error("No base64 encoder available in this runtime");return n.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function b(r){return `${wt}${St(JSON.stringify(r))}`}function D(r){r.registerFunction("fsPathRef",t=>b({kind:"fs-path",value:String(t)}),"<s:s>");}function q(r,t,e){if(!r||typeof r!="object")return t;let n={output:t},s=t.result,o=t.data,i=t.error;if(typeof r.resultExpr=="string")try{let a=R(r.resultExpr);D(a);let p=a.evaluate(n);if(typeof p!="string"||!p.trim())throw new Error(`resultExpr did not produce a non-empty string (got ${JSON.stringify(p)})`);s=p;}catch(a){let p=a instanceof Error?a.message:String(a);throw new Error(`[${e}] outputTransforms.resultExpr failed: ${p}`)}if(typeof r.dataTemplate=="string")try{let a=R(r.dataTemplate);D(a);let p=a.evaluate(n);if(!p||typeof p!="object"||Array.isArray(p))throw new Error(`dataTemplate did not produce an object (got ${JSON.stringify(p)})`);o=p;}catch(a){let p=a instanceof Error?a.message:String(a);throw new Error(`[${e}] outputTransforms.dataTemplate failed: ${p}`)}if(typeof r.errorExpr=="string")try{let a=R(r.errorExpr);D(a);let p=a.evaluate(n);i=p!=null?String(p):void 0;}catch(a){let p=a instanceof Error?a.message:String(a);throw new Error(`[${e}] outputTransforms.errorExpr failed: ${p}`)}return i!==void 0?{result:s,data:o,error:i}:{result:s,data:o}}function I(r){return !!r&&typeof r=="object"&&r.type==="compute-jsonata"&&Array.isArray(r.expr)&&r.expr.length>0}function Y(r){if(!r||typeof r!="object")return false;let t=r;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 e=t.whatToRun;return typeof e.kind=="string"&&typeof e.value=="string"}return false}function yt(r){if(typeof r=="string"){let t=r.indexOf("=");if(t<1)throw new Error(`[step-machine-public] Invalid compute expression (missing "="): "${r}"`);return {bindTo:r.slice(0,t).trim(),expr:r.slice(t+1).trim()}}if(r&&typeof r=="object"&&typeof r.bindTo=="string"&&typeof r.expr=="string")return r;throw new Error(`[step-machine-public] Invalid compute step: ${JSON.stringify(r)}`)}function kt(r,t,e){let n=t.split("."),s=r;for(let o=0;o<n.length-1;o++){let i=n[o];(s[i]==null||typeof s[i]!="object")&&(s[i]={}),s=s[i];}s[n[n.length-1]]=e;}function X(r,t,e){let n=r.expr.map(yt);return async s=>{let o=s&&typeof s=="object"&&!Array.isArray(s)?{...s}:{},i={},a={expects_data:o,data:i,...e?{config:e}:{}},p,d;for(let f of n)try{let l=k(f.expr).evaluate(a);if(f.bindTo==="result")p=l!=null?String(l):"success";else if(f.bindTo==="error")d=l!=null?String(l):void 0;else if(f.bindTo.startsWith("data."))kt(i,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 m=l instanceof Error?l.message:String(l);return {result:"failure",data:{},error:`[${t}] compute "${f.bindTo}" failed: ${m}`}}return p===void 0?{result:"failure",data:{},error:`[${t}] compute-jsonata: no "result" binding declared \u2014 add '- result = "success"' to expr`}:d?{result:p,data:i,error:d}:{result:p,data:i}}}function G(r,t,e,n){let{type:s,...o}=r,i={...o,whatToRun:typeof o.whatToRun=="object"?b(o.whatToRun):o.whatToRun};return async a=>{let p=a&&typeof a=="object"&&!Array.isArray(a)?{...a}:{};n&&(p.config=n);try{let d=await e(i,p);if(!r.outputTransforms)return d;try{return q(r.outputTransforms,d,t)}catch(f){let l=f instanceof Error?f.message:String(f);return {result:"failure",data:{},error:l}}}catch(d){let f=d instanceof Error?d.message:String(d);return {result:"failure",data:{error:`[step-machine-public] step "${t}" invoke threw: ${f}`}}}}}function Q(){return async r=>({result:"success",data:r&&typeof r=="object"&&!Array.isArray(r)?r:{}})}function vt(r,t,e){return async(n,s)=>{let o=n?.[t.items];if(!Array.isArray(o))return {result:"failure",data:{},error:`[${e}] forEach: "${t.items}" is not an array (got ${typeof o})`};let i=o,a=t.collectAs??`${t.items}_results`;if(i.length===0)return {result:"success",data:{[a]:[]}};let{[t.items]:p,...d}=n,f=Math.max(1,t.concurrency??1),l=new Array(i.length),m=0,g=0,w=0;return await new Promise(u=>{function c(){for(;m<f&&g<i.length;){let S=g++;m++;let tt={...d,[t.as]:i[S]};r(tt,s).then(y=>{l[S]=y;}).catch(y=>{let et=y instanceof Error?y.message:String(y);l[S]={result:"failure",data:{},error:et};}).finally(()=>{m--,l[S]?.result==="failure"&&w++,g>=i.length&&m===0?u():c();});}m===0&&g>=i.length&&u();}c();}),w>0?{result:"failure",data:{errors:l.filter(c=>c.result==="failure").map(c=>c.error)},error:`[${e}] forEach: ${w}/${i.length} items failed`}:{result:"success",data:{[a]:l.map(u=>u.data)}}}}function Z(r,t,e){let n=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,i=t?.handler,a;return I(i)?a=X(i,r,o):Y(i)?a=G(i,r,e.invoke,o):a=Q(),t?.forEach&&(a=vt(a,t.forEach,r)),H(T(a,n),s,r)}function P(r,t){let e={};for(let[n,s]of Object.entries(r.steps??{}))e[n]=Z(n,s,t);return e}function xt(r){let t=r.storeFactory||(()=>new h);return {async run(e,n){try{let s=P(e,{invoke:r.invokeRef}),i=await x(e,s,{store:t()}).run(n);return i.status!=="completed"?{dispatched:!1,error:i.error?.message||i.status}:{dispatched:!0}}catch(s){return {dispatched:false,error:s instanceof Error?s.message:String(s)}}}}}
|
|
4
|
+
export{M as KVStorageStore,h as MemoryStore,P as buildStepHandlersForFlow,X as createComputeJsonataHandler,Q as createPassthroughHandler,G as createRefStepHandler,x as createStepMachine,xt as createStepMachineChatFlowRunner,L as filterProducedData,I as isComputeJsonataSpec,Y as isRefSpec,k as jsonata,J as loadStepFlow,V as normalizeHandlerResult,Z as resolveStepHandler,N as runInputValidations,H as wrapWithInputValidations,T as wrapWithOutputFiltering};//# sourceMappingURL=index.js.map
|
|
5
5
|
//# sourceMappingURL=index.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { a as ArtifactsStore } from './artifacts-store-lib-454TAuov.js';
|
|
2
|
-
import { d as BoardPlatformAdapter, a as CommandResult } from './board-live-cards-public-
|
|
2
|
+
import { d as BoardPlatformAdapter, a as CommandResult } from './board-live-cards-public-Crjm8KWn.js';
|
|
3
3
|
import { ExecutionRef } from './execution-refs.js';
|
|
4
4
|
import { a as KindValueRef } from './storage-interface-B-7pDHwD.js';
|
|
5
5
|
import { c as ChatStorage } from './chat-storage-lib-DGaKrjVe.js';
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { a as ArtifactsStore } from './artifacts-store-lib-zsGFbBV8.cjs';
|
|
2
|
-
import { d as BoardPlatformAdapter, a as CommandResult } from './board-live-cards-public-
|
|
2
|
+
import { d as BoardPlatformAdapter, a as CommandResult } from './board-live-cards-public-CU8VVw3v.cjs';
|
|
3
3
|
import { ExecutionRef } from './execution-refs.cjs';
|
|
4
4
|
import { a as KindValueRef } from './storage-interface-B-7pDHwD.cjs';
|
|
5
5
|
import { c as ChatStorage } from './chat-storage-lib-OX0Q_Ttf.cjs';
|