yaml-flow 8.4.18 → 8.4.21
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 +7 -7
- package/cli/browser-api/board-live-cards-browser-adapter.d.ts +2 -2
- package/cli/browser-api/board-live-cards-browser-adapter.js +3 -3
- package/cli/browser-api/card-store-browser-api.js +1 -1
- package/cli/bundled/artifacts-store-cli.mjs +9 -9
- package/cli/bundled/board-live-cards-cli.mjs +19 -19
- package/cli/{execution-interface-BCIhu1gO.d.ts → execution-interface-_BN4kSuA.d.ts} +7 -1
- package/cli/{types-juH2nFpz.d.ts → types-CaQhDvWD.d.ts} +8 -1
- 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-D-k-E8Vy.d.ts → artifacts-store-lib-CODxnrXD.d.ts} +1 -1
- package/lib/{artifacts-store-lib-CVgtQrNZ.d.cts → artifacts-store-lib-DuatIrVb.d.cts} +1 -1
- package/lib/artifacts-store-public.d.cts +3 -3
- package/lib/artifacts-store-public.d.ts +3 -3
- package/lib/board-live-cards-node.cjs +10 -10
- package/lib/board-live-cards-node.d.cts +10 -10
- package/lib/board-live-cards-node.d.ts +10 -10
- package/lib/board-live-cards-node.js +10 -10
- package/lib/{board-live-cards-public-B4RcYPC_.d.cts → board-live-cards-public-DTuWGcCs.d.cts} +8 -1
- package/lib/{board-live-cards-public-ydXuA4zh.d.ts → board-live-cards-public-KyDR96Rf.d.ts} +8 -1
- package/lib/board-live-cards-public.cjs +2 -2
- package/lib/board-live-cards-public.d.cts +2 -2
- package/lib/board-live-cards-public.d.ts +2 -2
- 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 +5 -5
- package/lib/board-live-cards-server-runtime.d.ts +5 -5
- package/lib/board-live-cards-server-runtime.js +3 -3
- package/lib/card-store-public.d.cts +2 -2
- package/lib/card-store-public.d.ts +2 -2
- package/lib/{chat-storage-lib-DsF4kPon.d.ts → chat-storage-lib-DFUsokwy.d.ts} +1 -1
- package/lib/{chat-storage-lib-B1wU27y3.d.cts → chat-storage-lib-DxyFlJVt.d.cts} +1 -1
- package/lib/chat-store-public.d.cts +3 -3
- package/lib/chat-store-public.d.ts +3 -3
- package/lib/execution-refs.cjs +2 -2
- package/lib/execution-refs.js +2 -2
- package/lib/index.d.cts +1 -1
- package/lib/index.d.ts +1 -1
- package/lib/server-runtime/index.cjs +3 -3
- package/lib/server-runtime/index.d.cts +6 -6
- package/lib/server-runtime/index.d.ts +6 -6
- package/lib/server-runtime/index.js +3 -3
- package/lib/step-machine-public/index.cjs +3 -3
- package/lib/step-machine-public/index.d.cts +1 -1
- package/lib/step-machine-public/index.d.ts +1 -1
- package/lib/step-machine-public/index.js +3 -3
- package/lib/{storage-interface-B2WD9D5n.d.cts → storage-interface-D4Ny0Men.d.cts} +7 -1
- package/lib/{storage-interface-B2WD9D5n.d.ts → storage-interface-D4Ny0Men.d.ts} +7 -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/{types-1L1D33mr.d.ts → types-Bep-vtP0.d.ts} +4 -4
- package/lib/{types-D501gMQt.d.cts → types-DbvoDam4.d.cts} +4 -4
- package/package.json +1 -1
|
@@ -3,7 +3,7 @@ import { l as StepMachineStore } from '../types-DjlwALZC.cjs';
|
|
|
3
3
|
export { MemoryStore } from '../stores/memory.cjs';
|
|
4
4
|
export { KVStorageStore } from '../stores/kv.cjs';
|
|
5
5
|
import { ExecutionRef } from '../execution-refs.cjs';
|
|
6
|
-
import '../storage-interface-
|
|
6
|
+
import '../storage-interface-D4Ny0Men.cjs';
|
|
7
7
|
|
|
8
8
|
/**
|
|
9
9
|
* The single normalized shape the engine consumes.
|
|
@@ -3,7 +3,7 @@ import { l as StepMachineStore } from '../types-DjlwALZC.js';
|
|
|
3
3
|
export { MemoryStore } from '../stores/memory.js';
|
|
4
4
|
export { KVStorageStore } from '../stores/kv.js';
|
|
5
5
|
import { ExecutionRef } from '../execution-refs.js';
|
|
6
|
-
import '../storage-interface-
|
|
6
|
+
import '../storage-interface-D4Ny0Men.js';
|
|
7
7
|
|
|
8
8
|
/**
|
|
9
9
|
* The single normalized shape the engine consumes.
|
|
@@ -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 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 R=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??1e6,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 v(r,t,e){return new R(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:
|
|
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 E(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 $(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 R=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??1e6,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),l={runId:t,status:"completed",intent:p.return_intent,data:C(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:{...l}}),this.options.onComplete?.(l),l}let d=E(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),c=F(this.flow,a,f),m={runId:t,stepName:a,components:this.components,store:this.store,signal:this.options.signal,emit:(u,l)=>{this.emit({type:"step:complete",runId:t,timestamp:Date.now(),data:{event:u,payload:l}});}};this.emit({type:"step:start",runId:t,timestamp:Date.now(),data:{step:a,input:c}});let g;try{let u=this.handlers.get(a);if(!u)throw new Error(`No handler registered for step "${a}"`);g=await u(c,m);}catch(u){let l=u instanceof Error?u:new Error(String(u));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[u,l]of Object.entries(g.data))await this.store.setData(t,u,l);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 l=o.retryCounts[a]??0,y=u.retry.backoff_multiplier?u.retry.delay_ms*Math.pow(u.retry.backoff_multiplier,l-1):u.retry.delay_ms;await this.sleep(y);}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 R(r,t,e)}async function A(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):A(n)}async function ot(r){let e=await(await import('fs/promises')).readFile(r,"utf-8");return r.endsWith(".json")?JSON.parse(e):A(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
|
|
4
|
-
export{M as KVStorageStore,h as MemoryStore,P as buildStepHandlersForFlow,X as createComputeJsonataHandler,Q as createPassthroughHandler,G as createRefStepHandler,v as createStepMachine,vt as createStepMachineChatFlowRunner,
|
|
3
|
+
- `)}`);return t}function _(r){return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function K(r){return atob(r.replace(/-/g,"+").replace(/_/g,"/"))}var M=class{constructor(t){this.kv=t;}kv;stateKey(t){return `state_${_(t)}`}dataPrefix(t){return `data_${_(t)}_`}dataKey(t,e){return `${this.dataPrefix(t)}${_(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[K(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=>K(t.slice(6)))}};var z=dirname(fileURLToPath(import.meta.url)),ut=createRequire(import.meta.url);function ct(){let r=resolve(z,"./jsonata-sync.cjs");return existsSync(r)?r:resolve(z,"../card-compute/jsonata-sync.cjs")}var k=ut(ct());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 N(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:N(o.data,t),...o.error?{error:o.error}:{}}}}function L(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=L(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 x=mt(ht());var wt="b64:";function yt(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}${yt(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=x(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=x(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=x(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 St(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(St);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 c=k(f.expr).evaluate(a);if(f.bindTo==="result")p=c!=null?String(c):"success";else if(f.bindTo==="error")d=c!=null?String(c):void 0;else if(f.bindTo.startsWith("data."))kt(i,f.bindTo.slice(5),c);else return {result:"failure",data:{},error:`[${t}] invalid bindTo "${f.bindTo}": must be "result", "error", or start with "data."`}}catch(c){let m=c instanceof Error?c.message:String(c);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 c=f instanceof Error?f.message:String(f);return {result:"failure",data:{},error:c}}}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 Rt(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),c=new Array(i.length),m=0,g=0,w=0;return await new Promise(u=>{function l(){for(;m<f&&g<i.length;){let y=g++;m++;let tt={...d,[t.as]:i[y]};r(tt,s).then(S=>{c[y]=S;}).catch(S=>{let et=S instanceof Error?S.message:String(S);c[y]={result:"failure",data:{},error:et};}).finally(()=>{m--,c[y]?.result==="failure"&&w++,g>=i.length&&m===0?u():l();});}m===0&&g>=i.length&&u();}l();}),w>0?{result:"failure",data:{errors:c.filter(l=>l.result==="failure").map(l=>l.error)},error:`[${e}] forEach: ${w}/${i.length} items failed`}:{result:"success",data:{[a]:c.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=Rt(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 vt(r){let t=r.storeFactory||(()=>new h);return {async run(e,n){try{let s=P(e,{invoke:r.invokeRef}),i=await v(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,v as createStepMachine,vt as createStepMachineChatFlowRunner,N as filterProducedData,I as isComputeJsonataSpec,Y as isRefSpec,k as jsonata,J as loadStepFlow,V as normalizeHandlerResult,Z as resolveStepHandler,L as runInputValidations,H as wrapWithInputValidations,T as wrapWithOutputFiltering};//# sourceMappingURL=index.js.map
|
|
5
5
|
//# sourceMappingURL=index.js.map
|
|
@@ -62,10 +62,16 @@ interface KindValueRef {
|
|
|
62
62
|
readonly kind: string;
|
|
63
63
|
readonly value: string;
|
|
64
64
|
}
|
|
65
|
+
interface ArtifactsStoreEntryRef {
|
|
66
|
+
readonly storeRef: string;
|
|
67
|
+
readonly key: string;
|
|
68
|
+
}
|
|
65
69
|
/** Serialize a KindValueRef to the wire format: b64:<base64url(json)> */
|
|
66
70
|
declare function serializeRef(ref: KindValueRef): string;
|
|
67
71
|
/** Parse a wire-format ref string (b64:<base64url(json)>) into a KindValueRef. */
|
|
68
72
|
declare function parseRef(s: string): KindValueRef;
|
|
73
|
+
declare function serializeArtifactsStoreEntryRef(ref: ArtifactsStoreEntryRef): string;
|
|
74
|
+
declare function parseArtifactsStoreEntryRef(s: string): ArtifactsStoreEntryRef;
|
|
69
75
|
interface JournalEntry {
|
|
70
76
|
id: string;
|
|
71
77
|
payload: unknown;
|
|
@@ -145,4 +151,4 @@ interface AtomicRelayLock {
|
|
|
145
151
|
tryAcquire(): (() => void) | null;
|
|
146
152
|
}
|
|
147
153
|
|
|
148
|
-
export { type ArchiveFactory as A, type BlobStorage as B, type JournalStorage as J, type KVStorage as K, type ScratchStorage as S, type KindValueRef as a, type AtomicRelayLock as b, parseRef as
|
|
154
|
+
export { type ArchiveFactory as A, type BlobStorage as B, type JournalStorage as J, type KVStorage as K, type ScratchStorage as S, type KindValueRef as a, type AtomicRelayLock as b, parseRef as c, serializeRef as d, parseArtifactsStoreEntryRef as p, serializeArtifactsStoreEntryRef as s };
|
|
@@ -62,10 +62,16 @@ interface KindValueRef {
|
|
|
62
62
|
readonly kind: string;
|
|
63
63
|
readonly value: string;
|
|
64
64
|
}
|
|
65
|
+
interface ArtifactsStoreEntryRef {
|
|
66
|
+
readonly storeRef: string;
|
|
67
|
+
readonly key: string;
|
|
68
|
+
}
|
|
65
69
|
/** Serialize a KindValueRef to the wire format: b64:<base64url(json)> */
|
|
66
70
|
declare function serializeRef(ref: KindValueRef): string;
|
|
67
71
|
/** Parse a wire-format ref string (b64:<base64url(json)>) into a KindValueRef. */
|
|
68
72
|
declare function parseRef(s: string): KindValueRef;
|
|
73
|
+
declare function serializeArtifactsStoreEntryRef(ref: ArtifactsStoreEntryRef): string;
|
|
74
|
+
declare function parseArtifactsStoreEntryRef(s: string): ArtifactsStoreEntryRef;
|
|
69
75
|
interface JournalEntry {
|
|
70
76
|
id: string;
|
|
71
77
|
payload: unknown;
|
|
@@ -145,4 +151,4 @@ interface AtomicRelayLock {
|
|
|
145
151
|
tryAcquire(): (() => void) | null;
|
|
146
152
|
}
|
|
147
153
|
|
|
148
|
-
export { type ArchiveFactory as A, type BlobStorage as B, type JournalStorage as J, type KVStorage as K, type ScratchStorage as S, type KindValueRef as a, type AtomicRelayLock as b, parseRef as
|
|
154
|
+
export { type ArchiveFactory as A, type BlobStorage as B, type JournalStorage as J, type KVStorage as K, type ScratchStorage as S, type KindValueRef as a, type AtomicRelayLock as b, parseRef as c, serializeRef as d, parseArtifactsStoreEntryRef as p, serializeArtifactsStoreEntryRef as s };
|
package/lib/stores/index.d.cts
CHANGED
package/lib/stores/index.d.ts
CHANGED
package/lib/stores/kv.d.cts
CHANGED
package/lib/stores/kv.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { a as ArtifactsStore } from './artifacts-store-lib-
|
|
2
|
-
import { d as BoardPlatformAdapter, a as CommandResult } from './board-live-cards-public-
|
|
1
|
+
import { a as ArtifactsStore } from './artifacts-store-lib-CODxnrXD.js';
|
|
2
|
+
import { d as BoardPlatformAdapter, a as CommandResult } from './board-live-cards-public-KyDR96Rf.js';
|
|
3
3
|
import { ExecutionRef } from './execution-refs.js';
|
|
4
|
-
import { a as KindValueRef } from './storage-interface-
|
|
5
|
-
import { c as ChatStorage } from './chat-storage-lib-
|
|
4
|
+
import { a as KindValueRef } from './storage-interface-D4Ny0Men.js';
|
|
5
|
+
import { c as ChatStorage } from './chat-storage-lib-DFUsokwy.js';
|
|
6
6
|
|
|
7
7
|
interface InvocationAdapter {
|
|
8
8
|
/**
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { a as ArtifactsStore } from './artifacts-store-lib-
|
|
2
|
-
import { d as BoardPlatformAdapter, a as CommandResult } from './board-live-cards-public-
|
|
1
|
+
import { a as ArtifactsStore } from './artifacts-store-lib-DuatIrVb.cjs';
|
|
2
|
+
import { d as BoardPlatformAdapter, a as CommandResult } from './board-live-cards-public-DTuWGcCs.cjs';
|
|
3
3
|
import { ExecutionRef } from './execution-refs.cjs';
|
|
4
|
-
import { a as KindValueRef } from './storage-interface-
|
|
5
|
-
import { c as ChatStorage } from './chat-storage-lib-
|
|
4
|
+
import { a as KindValueRef } from './storage-interface-D4Ny0Men.cjs';
|
|
5
|
+
import { c as ChatStorage } from './chat-storage-lib-DxyFlJVt.cjs';
|
|
6
6
|
|
|
7
7
|
interface InvocationAdapter {
|
|
8
8
|
/**
|