yaml-flow 8.1.1 → 8.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/browser/asset-integrity.json +3 -3
- package/browser/board-livecards-client.js +1 -1
- package/browser/board-livecards-localstorage.js +4 -6
- package/cli/{board-live-cards-lib-tjYsPt5U.d.ts → board-live-cards-lib-Iq_XAC09.d.ts} +1 -1
- package/cli/browser-api/board-live-cards-browser-adapter.d.ts +4 -3
- package/cli/browser-api/board-live-cards-browser-adapter.js +2 -2
- package/cli/browser-api/card-store-browser-api.d.ts +1 -1
- package/cli/node/artifacts-store-cli.js +8 -8
- package/cli/node/board-live-cards-cli.js +8 -8
- package/cli/node/card-store-cli.js +4 -4
- package/cli/node/fs-board-adapter.d.ts +6 -33
- package/cli/node/fs-board-adapter.js +10 -8
- package/cli/node/step-machine-cli.js +3 -3
- package/cli/{types-D2XnLbBj.d.ts → types--rXGWbSR.d.ts} +77 -5
- package/examples/board/.board-ws/cards/store/_index.json +17 -0
- package/examples/board/.board-ws/cards/store/card-market-prices.json +80 -0
- package/examples/board/.board-ws/cards/store/card-portfolio-value.json +90 -0
- package/examples/board/.board-ws/cards/store/card-portfolio.json +78 -0
- package/examples/board/cards/cardT-market-prices.json +6 -4
- package/examples/board/cards/cardT-portfolio-value.json +10 -38
- package/examples/board/cards/cardT-portfolio.json +9 -4
- package/examples/board/demo-shell-with-server.html +3 -3
- package/examples/board/server/board-server.js +593 -0
- package/examples/board/server/board-worker/source-def-flows/mock-handler/mock-db.js +13 -0
- package/examples/board/server/board-worker/source-def-flows/sqlite-handler/.retain/compliance.db +0 -0
- package/examples/board/server/board-worker/source-def-flows/sqlite-handler/.retain/optimus.db +0 -0
- package/examples/board/server/board-worker/source-def-flows/sqlite-handler/query.cjs +51 -0
- package/examples/board/server/board-worker/source-def-flows/sqlite-handler/seed-cpm.cjs +197 -0
- package/examples/board/server/board-worker/source-def-flows/sqlite-handler/seed-cpmV2.cjs +128 -0
- package/examples/board/server/board-worker/source-def-flows/sqlite-handler/seed-optimus.cjs +352 -0
- package/examples/board/server/board-worker/source-def-flows/sqlite-handler/sqlite-config.json +3 -0
- package/examples/board/server/board-worker/source-def-flows/sqlite-handler/sqlite-handler.js +84 -0
- package/examples/board/{source-def-flows/url.flow.json → server/board-worker/source-def-flows/sqlite.flow.json} +7 -7
- package/examples/board/{source-def-handlers → server/board-worker/source-def-flows/url-handler}/http-source-handler.js +29 -21
- package/examples/board/server/board-worker/source-def-flows/url.flow.json +73 -0
- package/examples/board/{source_def_flows.json → server/board-worker/source_def_flows.json} +61 -115
- package/examples/board/server/board-worker/task-executor.js +475 -0
- package/examples/board/server/chat-flow/chat-clear-processing.js +41 -0
- package/examples/board/server/chat-flow/chat-open-turn.js +144 -0
- package/examples/board/server/chat-flow/chat-write-assistant.js +44 -0
- package/examples/board/server/chat-flow/copilot-chat/assistant.js +253 -0
- package/examples/board/server/chat-flow/echo-probe/assistant.js +28 -0
- package/examples/board/server/chat-flow/flow-steps.json +167 -0
- package/examples/board/server-config.json +22 -0
- package/examples/board/test/server-http-test.js +707 -0
- package/examples/board/test/{portfolio-tracker-sse-worker.js → sse-worker.js} +9 -8
- package/examples/board-local/demo-shell-localstorage.html +3 -3
- package/lib/{artifacts-store-lib-public-DBICnGL6.d.cts → artifacts-store-lib-public-C5UL5tyG.d.cts} +3 -31
- package/lib/{artifacts-store-lib-public-BWC3YuLa.d.ts → artifacts-store-lib-public-GD4H-fFp.d.ts} +3 -31
- 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 -8
- package/lib/board-live-cards-node.d.cts +9 -8
- package/lib/board-live-cards-node.d.ts +9 -8
- package/lib/board-live-cards-node.js +10 -8
- package/lib/{board-live-cards-public-BF9FP0mL.d.cts → board-live-cards-public-BLXbcBNk.d.cts} +2 -2
- package/lib/{board-live-cards-public-dJAl5IL-.d.ts → board-live-cards-public-BZaNb2mi.d.ts} +2 -2
- 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 +4 -6
- package/lib/board-live-cards-server-runtime.d.cts +3 -3
- package/lib/board-live-cards-server-runtime.d.ts +3 -3
- package/lib/board-live-cards-server-runtime.js +4 -6
- package/lib/board-livegraph-runtime/index.cjs +2 -2
- package/lib/board-livegraph-runtime/index.js +2 -2
- package/lib/card-store-public.d.cts +2 -2
- package/lib/card-store-public.d.ts +2 -2
- package/lib/execution-refs.cjs +1 -1
- package/lib/execution-refs.js +1 -1
- package/lib/index.cjs +1 -1
- package/lib/index.d.cts +1 -1
- package/lib/index.d.ts +1 -1
- package/lib/index.js +1 -1
- package/lib/server-runtime/index.cjs +4 -6
- package/lib/server-runtime/index.d.cts +4 -4
- package/lib/server-runtime/index.d.ts +4 -4
- package/lib/server-runtime/index.js +4 -6
- package/lib/step-machine-public/index.cjs +3 -3
- package/lib/step-machine-public/index.d.cts +27 -10
- package/lib/step-machine-public/index.d.ts +27 -10
- package/lib/step-machine-public/index.js +3 -3
- package/lib/{storage-interface-BhAON-gW.d.ts → storage-interface-B6ecOulj.d.cts} +25 -3
- package/lib/{storage-interface-BhAON-gW.d.cts → storage-interface-B6ecOulj.d.ts} +25 -3
- 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-CXBzvC0s.d.cts → types-Bztd1KoK.d.cts} +75 -3
- package/lib/{types-D48hpnTR.d.ts → types-D-xVWPdY.d.ts} +75 -3
- package/package.json +1 -1
- package/examples/board/demo-chat-handler.js +0 -169
- package/examples/board/demo-server-config.json +0 -10
- package/examples/board/demo-server.js +0 -580
- package/examples/board/demo-task-executor.js +0 -721
- package/examples/board/gandalf-cards/card-source-kinds.json +0 -36
- package/examples/board/gandalf-cards/cards/_index.json +0 -7
- package/examples/board/gandalf-cards/cards/card-source-kinds.json +0 -64
- package/examples/board/scripts/copilot_wrapper.bat +0 -157
- package/examples/board/scripts/copilot_wrapper_helper.ps1 +0 -190
- package/examples/board/scripts/workiq_wrapper.mjs +0 -66
- package/examples/board/source-def-flows/copilot.flow.json +0 -33
- package/examples/board/source-def-flows/url-list.flow.json +0 -33
- package/examples/board/source-def-flows/workiq.flow.json +0 -34
- package/examples/board/source-def-handlers/copilot-source-handler.js +0 -141
- package/examples/board/test/demo-http-test.js +0 -317
- /package/examples/board/{source-def-flows → server/board-worker/source-def-flows}/mock.flow.json +0 -0
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import*as m from'fs';import {existsSync}from'fs';import*as v 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 Rt from'os';import'net';import {randomUUID}from'crypto';import'proper-lockfile';function K(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 U(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 z(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 V(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 Pt(){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 O=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=Pt(),r=V(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,u=this.flow.terminal_states[i];if(u){o={...o,status:"completed",updatedAt:Date.now()},await this.store.saveRunState(t,o);let p=await this.store.getAllData(t),g={runId:t,status:"completed",intent:u.return_intent,data:z(u.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:{...g}}),this.options.onComplete?.(g),g}let c=U(this.flow,o,i);if(c.broken){o=c.newState,await this.store.saveRunState(t,o),a++;continue}o=c.newState;let d=await this.store.getAllData(t),l=q(this.flow,i,d),f={runId:t,stepName:i,components:this.components,store:this.store,signal:this.options.signal,emit:(p,g)=>{this.emit({type:"step:complete",runId:t,timestamp:Date.now(),data:{event:p,payload:g}});}};this.emit({type:"step:start",runId:t,timestamp:Date.now(),data:{step:i,input:l}});let h;try{let p=this.handlers.get(i);if(!p)throw new Error(`No handler registered for step "${i}"`);h=await p(l,f);}catch(p){let g=p instanceof Error?p:new Error(String(p));this.emit({type:"step:error",runId:t,timestamp:Date.now(),data:{step:i,error:g.message}}),h={result:"failure",data:{error:g.message}};}if(h.data)for(let[p,g]of Object.entries(h.data))await this.store.setData(t,p,g);this.emit({type:"step:complete",runId:t,timestamp:Date.now(),data:{step:i,result:h.result}}),this.options.onStep?.(i,h);let w=K(this.flow,o,i,h);if(o=w.newState,w.shouldRetry){await this.store.saveRunState(t,o);let p=this.flow.steps[i];if(p.retry?.delay_ms){let g=o.retryCounts[i]??0,x=p.retry.backoff_multiplier?p.retry.delay_ms*Math.pow(p.retry.backoff_multiplier,g-1):p.retry.delay_ms;await this.sleep(x);}a++;continue}await this.store.saveRunState(t,o),this.emit({type:"transition",runId:t,timestamp:Date.now(),data:{from:i,to:o.currentStep,result:h.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 H(e,t,n){return new O(e,t,n)}async function W(e){return (await import('yaml')).parse(e)}async function Mt(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):W(r)}async function Ot(e){let n=await(await import('fs/promises')).readFile(e,"utf-8");return e.endsWith(".json")?JSON.parse(n):W(n)}function nt(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 I(e){let t;typeof e=="string"?e.startsWith("http://")||e.startsWith("https://")?t=await Mt(e):e.includes("{")?t=JSON.parse(e):t=await Ot(e):t=e;let n=nt(t);if(n.length>0)throw new Error(`Invalid step flow configuration:
|
|
1
|
+
import*as m from'fs';import {existsSync}from'fs';import*as k 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 xt from'os';import'net';import {randomUUID}from'crypto';import'proper-lockfile';function U(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 q(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 z(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 V(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 W(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 v=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 Mt(){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 v,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=Mt(),r=W(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,u=this.flow.terminal_states[i];if(u){o={...o,status:"completed",updatedAt:Date.now()},await this.store.saveRunState(t,o);let p=await this.store.getAllData(t),g={runId:t,status:"completed",intent:u.return_intent,data:V(u.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:{...g}}),this.options.onComplete?.(g),g}let c=q(this.flow,o,i);if(c.broken){o=c.newState,await this.store.saveRunState(t,o),a++;continue}o=c.newState;let d=await this.store.getAllData(t),l=z(this.flow,i,d),f={runId:t,stepName:i,components:this.components,store:this.store,signal:this.options.signal,emit:(p,g)=>{this.emit({type:"step:complete",runId:t,timestamp:Date.now(),data:{event:p,payload:g}});}};this.emit({type:"step:start",runId:t,timestamp:Date.now(),data:{step:i,input:l}});let h;try{let p=this.handlers.get(i);if(!p)throw new Error(`No handler registered for step "${i}"`);h=await p(l,f);}catch(p){let g=p instanceof Error?p:new Error(String(p));this.emit({type:"step:error",runId:t,timestamp:Date.now(),data:{step:i,error:g.message}}),h={result:"failure",data:{error:g.message}};}if(h.data)for(let[p,g]of Object.entries(h.data))await this.store.setData(t,p,g);this.emit({type:"step:complete",runId:t,timestamp:Date.now(),data:{step:i,result:h.result}}),this.options.onStep?.(i,h);let w=U(this.flow,o,i,h);if(o=w.newState,w.shouldRetry){await this.store.saveRunState(t,o);let p=this.flow.steps[i];if(p.retry?.delay_ms){let g=o.retryCounts[i]??0,R=p.retry.backoff_multiplier?p.retry.delay_ms*Math.pow(p.retry.backoff_multiplier,g-1):p.retry.delay_ms;await this.sleep(R);}a++;continue}await this.store.saveRunState(t,o),this.emit({type:"transition",runId:t,timestamp:Date.now(),data:{from:i,to:o.currentStep,result:h.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 T(e,t,n){return new I(e,t,n)}async function G(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):G(r)}async function Ot(e){let n=await(await import('fs/promises')).readFile(e,"utf-8");return e.endsWith(".json")?JSON.parse(n):G(n)}function nt(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=nt(t);if(n.length>0)throw new Error(`Invalid step flow configuration:
|
|
2
2
|
- ${n.join(`
|
|
3
|
-
- `)}`);return t}function G(e){return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function rt(e){return atob(e.replace(/-/g,"+").replace(/_/g,"/"))}var j=class{constructor(t){this.kv=t;}kv;stateKey(t){return `state_${G(t)}`}dataPrefix(t){return `data_${G(t)}_`}dataKey(t,n){return `${this.dataPrefix(t)}${G(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[rt(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=>rt(t.slice(6)))}};var ot=dirname(fileURLToPath(import.meta.url)),Dt=createRequire(import.meta.url);function Bt(){let e=resolve(ot,"./jsonata-sync.cjs");return existsSync(e)?e:resolve(ot,"../card-compute/jsonata-sync.cjs")}var $=Dt(Bt());function it(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 at(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 X(e,t){return async(n,r)=>{let s=await e(n,r),o=it(s,r?.stepName??"unknown");return {result:o.result,data:at(o.data,t),...o.error?{error:o.error}:{}}}}function ct(e,t,n){if(!t||t.length===0)return null;for(let r of t)try{if(!$(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 Y(e,t,n){return !t||t.length===0?e:async(r,s)=>{let o=ct(r,t,n);return o||e(r,s)}}var lt=dirname(fileURLToPath(import.meta.url)),qt=createRequire(import.meta.url);function zt(){let e=resolve(lt,"./jsonata-sync.cjs");return existsSync(e)?e:resolve(lt,"../../card-compute/jsonata-sync.cjs")}var R=qt(zt());function pt(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{s.push(String(R(o).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{r.stdin=R(e.stdinTemplate).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{r.url=String(R(e.urlTemplate).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=R(e.headerTemplate).evaluate(t);if(typeof s!="object"||s===null)throw new Error(`headerTemplate must produce an object, got: ${JSON.stringify(s)}`);r.headers=s;}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{r.body=R(e.bodyTemplate).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=R(e.resultExpr).evaluate(r);if(typeof i!="string"||!i.trim())throw new Error(`resultExpr did not produce a non-empty string (got ${JSON.stringify(i)})`);s=i;}catch(i){let u=i instanceof Error?i.message:String(i);throw new Error(`[${n}] outputTransforms.resultExpr failed: ${u}`)}if(typeof e.dataTemplate=="string")try{let i=R(e.dataTemplate).evaluate(r);if(!i||typeof i!="object"||Array.isArray(i))throw new Error(`dataTemplate did not produce an object (got ${JSON.stringify(i)})`);o=i;}catch(i){let u=i instanceof Error?i.message:String(i);throw new Error(`[${n}] outputTransforms.dataTemplate failed: ${u}`)}if(typeof e.errorExpr=="string")try{let i=R(e.errorExpr).evaluate(r);a=i!=null?String(i):void 0;}catch(i){let u=i instanceof Error?i.message:String(i);throw new Error(`[${n}] outputTransforms.errorExpr failed: ${u}`)}return a!==void 0?{result:s,data:o,error:a}:{result:s,data:o}}var _="b64:";function Vt(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 Wt(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 J(e){return `${_}${Vt(JSON.stringify(e))}`}function D(e){if(!e.startsWith(_))throw new Error(`Invalid ref format (expected ${_}<base64url(json)>): ${e}`);let t;try{t=JSON.parse(Wt(e.slice(_.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 ft(e){return !!e&&typeof e=="object"&&e.type==="compute-jsonata"&&Array.isArray(e.expr)&&e.expr.length>0}function gt(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 Gt(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 mt(e,t,n){let r=e.expr.map(Gt);return async s=>{let o=s&&typeof s=="object"&&!Array.isArray(s)?{...s}:{},a={},i={expects_data:o,data:a,...n?{config:n}:{}},u,c;for(let d of r)try{let l=$(d.expr).evaluate(i);if(d.bindTo==="result")u=l!=null?String(l):"success";else if(d.bindTo==="error")c=l!=null?String(l):void 0;else if(d.bindTo.startsWith("data."))Xt(a,d.bindTo.slice(5),l);else return {result:"failure",data:{},error:`[${t}] invalid bindTo "${d.bindTo}": must be "result", "error", or start with "data."`}}catch(l){let f=l instanceof Error?l.message:String(l);return {result:"failure",data:{},error:`[${t}] compute "${d.bindTo}" failed: ${f}`}}return u===void 0?{result:"failure",data:{},error:`[${t}] compute-jsonata: no "result" binding declared \u2014 add '- result = "success"' to expr`}:c?{result:u,data:a,error:c}:{result:u,data:a}}}function ht(e,t,n,r){let{type:s,...o}=e,a={...o,whatToRun:typeof o.whatToRun=="object"?J(o.whatToRun):o.whatToRun};return async i=>{let u=i&&typeof i=="object"&&!Array.isArray(i)?{...i}:{};r&&(u.config=r);try{let c=await n(a,u);if(!e.outputTransforms)return c;try{return dt(e.outputTransforms,c,t)}catch(d){let l=d instanceof Error?d.message:String(d);return {result:"failure",data:{},error:l}}}catch(c){let d=c instanceof Error?c.message:String(c);return {result:"failure",data:{error:`[step-machine-public] step "${t}" invoke threw: ${d}`}}}}}function yt(){return async e=>({result:"success",data:e&&typeof e=="object"&&!Array.isArray(e)?e:{}})}function Yt(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]:u,...c}=r,d=Math.max(1,t.concurrency??1),l=new Array(a.length),f=0,h=0,w=0;return await new Promise(p=>{function g(){for(;f<d&&h<a.length;){let x=h++;f++;let P={...c,[t.as]:a[x]};e(P,s).then(S=>{l[x]=S;}).catch(S=>{let y=S instanceof Error?S.message:String(S);l[x]={result:"failure",data:{},error:y};}).finally(()=>{f--,l[x]?.result==="failure"&&w++,h>=a.length&&f===0?p():g();});}f===0&&h>=a.length&&p();}g();}),w>0?{result:"failure",data:{errors:l.filter(g=>g.result==="failure").map(g=>g.error)},error:`[${n}] forEach: ${w}/${a.length} items failed`}:{result:"success",data:{[i]:l.map(p=>p.data)}}}}function wt(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 ft(a)?i=mt(a,e,o):gt(a)?i=ht(a,e,n.invoke,o):i=yt(),t?.forEach&&(i=Yt(i,t.forEach,e)),Y(X(i,r),s,e)}function Q(e,t){let n={};for(let[r,s]of Object.entries(e.steps??{}))n[r]=wt(r,s,t);return n}function ee(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=vt(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 vt(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 Z(e){return process.platform==="win32"&&/\.(cmd|bat)$/i.test(e)}function kt(e,t){let{command:n,args:r=[],cwd:s,env:o,timeoutMs:a}=e;return execFileSync(n,r,{shell:Z(n),timeout:a,encoding:t?.encoding??"utf-8",cwd:s,windowsHide:true,env:o?{...process.env,...o}:void 0,input:t?.input})}function ne(e,t){let{command:n,args:r=[],cwd:s,env:o,timeoutMs:a=3e4}=e;execFile(n,r,{shell:Z(n),encoding:"utf8",windowsHide:true,timeout:a,maxBuffer:10*1024*1024,cwd:s,env:o?{...process.env,...o}:void 0},(i,u,c)=>t(i??null,u,c));}v.join(Rt.tmpdir(),".board-live-cards-git-bash-cache.json");function bt(e){let{command:t,args:n=[]}=e;if(process.platform==="win32"){spawn(t,n,{detached:true,stdio:"ignore",windowsHide:true,shell:Z(t)}).unref();return}spawn(t,n,{detached:true,stdio:"ignore"}).unref();}function Et(e,t,n){let r=v.join(e,"board-live-cards-cli.js");if(m.existsSync(r))return {cmd:process.execPath,args:[r,t,...n]};let s=v.join(e,"board-live-cards-cli.ts"),o=v.join(e,"..","..","node_modules","tsx","dist","cli.mjs"),a=v.join(e,"..","..","node_modules",".bin","tsx"),i=m.existsSync(o)?o:a;return m.existsSync(s)&&m.existsSync(i)?{cmd:process.execPath,args:[i,s,t,...n]}:{cmd:process.platform==="win32"?"npx.cmd":"npx",args:["tsx",s,t,...n]}}function At(){return {executeSync(e,t,n){return kt({command:e,args:t,cwd:n?.cwd,timeoutMs:n?.timeout,env:n?.env},{encoding:n?.encoding,input:n?.input})},executeAsync(e,t,n){ne({command:e,args:t},n);},resolveInvocation(e,t){let n=ee({command:e,args:t});return {cmd:n.command,args:n.args??[]}},splitCommand:vt,spawnDetached(e,t){bt({command:e,args:t});}}}function re(e,t){let n=typeof e=="object"?e.value:D(e).value;switch(n){case "source-cli-task-executor":{let r=v.join(t,"source-cli-task-executor.js");if(m.existsSync(r))return {command:process.execPath,args:[r]};let s=v.join(t,"source-cli-task-executor.ts"),o=v.join(t,"..","..","node_modules","tsx","dist","cli.mjs"),a=v.join(t,"..","..","node_modules",".bin","tsx"),i=m.existsSync(o)?o:a;return m.existsSync(s)&&m.existsSync(i)?{command:process.execPath,args:[i,s]}:{command:process.execPath,args:[r]}}case "board-live-cards":{let{cmd:r,args:s}=Et(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 se(e,t){if(e.howToRun==="built-in"){let{command:r,args:s}=re(e.whatToRun,t);return {command:r,baseArgs:s}}let n=typeof e.whatToRun=="object"?e.whatToRun.value:D(e.whatToRun).value;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 oe(e,t){return se(e,t)}function ie(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 ae(e){let t=e.whatToRun;return typeof t=="object"?t.value:D(t).value}function ce(e,t){return {...t,whatToRun:ae(e),...e.extra?{extra:e.extra}:{}}}function ue(e,t,n="invokeExecutionRef"){return pt(e,t,n)}function le(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 N(e){return {result:"failure",data:{error:e}}}function B(e,t,n){let r=n?.label??"invokeExecutionRefSync",s=n?.cliDir??n?.cwd??process.cwd(),o;try{o=ue(e.argsMassaging,ce(e,t),r);}catch(l){let f=l instanceof Error?l.message:String(l);return N(f)}let a;try{a=oe(e,s);}catch(l){let f=l instanceof Error?l.message:String(l);return N(`[${r}] ref resolution failed: ${f}`)}let i=[...a.baseArgs,...o.cmdArgs??[]],u=JSON.stringify(o.stdin??t),c=At(),d;try{d=c.executeSync(a.command,i,{timeout:n?.timeoutMs??3e4,encoding:"utf-8",cwd:n?.cwd,input:u});}catch(l){let f=l,h=(f.stderr?String(f.stderr):"").trim(),w=typeof f.status=="number"?f.status:"unknown",p=h||f.message;return N(`[${r}] ref exited with status ${w}${p?`: ${p}`:""}`)}try{return le(ie(d))}catch{return {result:"success",data:{stdout:d.trim()}}}}var pe={"local-node":B,"local-python":B,"local-process":B,"built-in":B};function de(e,t,n){let r=n?.syncTransports?.[e.howToRun]??pe[e.howToRun];return r?r(e,t,n):N(`[${n?.label??"invokeExecutionRefSync"}] unsupported sync howToRun: ${e.howToRun}`)}function jt(e,t,n){return de(e,t,n)}function ge(e,t){if(process.platform!=="win32"){m.renameSync(e,t);return}let n=[10,20,40,80,160];for(let r=0;r<=n.length;r++)try{m.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 v.join(e,...r.split("/"))+".json"}function n(r,s,o,a){if(m.existsSync(r))for(let i of m.readdirSync(r,{withFileTypes:true})){let u=s?`${s}/${i.name}`:i.name;if(i.isDirectory()){n(v.join(r,i.name),u,o,a);continue}if(!i.isFile()||!i.name.endsWith(".json"))continue;let c=u.replace(/\.json$/,"");(!o||c.startsWith(o))&&a.push(c);}}return {read(r){let s=t(r);if(!m.existsSync(s))return null;try{return JSON.parse(m.readFileSync(s,"utf-8"))}catch{return null}},write(r,s){let o=t(r),a=`${o}.${process.pid}.${randomUUID()}.tmp`;m.mkdirSync(v.dirname(o),{recursive:true}),m.writeFileSync(a,JSON.stringify(s,null,2),"utf-8"),ge(a,o);},delete(r){let s=t(r);try{m.existsSync(s)&&m.unlinkSync(s);}catch{}},listKeys(r){let s=[];return n(e,"",r,s),s.sort()}}}var L=class extends Error{constructor(n,r){super(r);this.code=n;this.name="CliExitError";}code},me=".pause";async function qn(e){let t=he(e);if(t.help||e.length===0)throw be(),new L(e.length===0?1:0);let{flowArg:n,dataArg:r,storeArg:s,storeDirArg:o,resumeRequested:a,pauseRequested:i,statusRequested:u}=t;if((i||u)&&(r||a||n))throw new Error("[step-machine-cli] --pause and --status are store-level operations. Do not provide flow, data, or --resume.");if(a&&r)throw new Error("[step-machine-cli] --initial-data cannot be combined with --resume.");let c=ye(s,o);if(u){await xe(c);return}if(i){await we(c);return}if(!n)throw new Error("[step-machine-cli] Flow path is required for run/resume operations.");let d=Ft(n),l=v.dirname(d),f=Re(r),{store:h}=c,w=await I(d),p=ke(w,l);$t(c);let g=new AbortController,x=false,P=H(w,p,{store:h,signal:g.signal,onStep:()=>{!x&&et(c)&&(x=true,g.abort());}}),S;if(a){if(S=await Ct(c),!S){console.warn("[step-machine-cli] No paused run found in store directory."),console.log(JSON.stringify({status:"noop",reason:"no-paused-run"},null,2));return}}else c.storeType==="file"&&!f&&(S=await Ct(c));let y=S?await P.resume(S):await P.run(f);if(x&&y.status==="cancelled"){let M=await Se(h,y.runId);$t(c),console.log(JSON.stringify({runId:y.runId,status:"paused",currentStep:M?.currentStep,pausedAt:M?.pausedAt,stepHistory:y.stepHistory,data:y.data},null,2));return}if(y.status!=="completed"){let M=y.error?.message??y.intent??y.status;throw console.error(`[step-machine-cli] Run failed: ${M}`),new L(1)}console.log(JSON.stringify({runId:y.runId,status:y.status,intent:y.intent,finalStep:y.finalStep,stepHistory:y.stepHistory,data:y.data},null,2));}function he(e){let t=new Set(["--initial-data","--store","--store-dir"]),n={},r=[],s=false,o=false,a=false,i=false;for(let u=0;u<e.length;u++){let c=e[u];if(c==="-h"||c==="--help"){s=true;continue}if(c==="--resume"){o=true;continue}if(c==="--pause"){a=true;continue}if(c==="--status"){i=true;continue}if(t.has(c)){let d=e[u+1];if(!d||d.startsWith("--"))throw new Error(`[step-machine-cli] Missing value for ${c}.`);n[c]=d,u++;continue}if(c.startsWith("--"))throw new Error(`[step-machine-cli] Unknown flag: ${c}`);r.push(c);}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"],storeArg:String(n["--store"]??"memory").toLowerCase(),storeDirArg:n["--store-dir"],resumeRequested:o,pauseRequested:a,statusRequested:i}}function Ft(e){return v.isAbsolute(e)?e:v.resolve(process.cwd(),e)}function ye(e,t){if(e!=="memory"&&e!=="file")throw new Error(`[step-machine-cli] Invalid --store value "${e}". Expected "memory" or "file".`);if(e==="memory")return {storeType:e,storeDir:void 0,pauseFilePath:void 0,store:new k};if(!t||t.trim().length===0)throw new Error("[step-machine-cli] --store file requires --store-dir <directory>.");let n=Ft(t);return {storeType:e,storeDir:n,pauseFilePath:v.join(n,me),store:new j(Tt(n))}}async function tt(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 et(e){return e.storeType!=="file"||!e.pauseFilePath?false:m.existsSync(e.pauseFilePath)}function $t(e){et(e)&&m.unlinkSync(e.pauseFilePath);}async function we(e){if(e.storeType!=="file"||!e.pauseFilePath)throw new Error("[step-machine-cli] --pause requires --store file --store-dir <directory>.");let t=await tt(e.store);if(t.length===0){console.warn("[step-machine-cli] No runs found in store directory. 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}m.mkdirSync(e.storeDir,{recursive:true}),m.writeFileSync(e.pauseFilePath,JSON.stringify({requestedAt:Date.now()}),"utf-8"),console.log(JSON.stringify({status:"pause-requested",storeDir:e.storeDir},null,2));}async function Ct(e){let n=(await tt(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 Se(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 xe(e){if(e.storeType!=="file")throw new Error("[step-machine-cli] --status requires --store file --store-dir <directory>.");let t=await tt(e.store),n={store:"file",storeDir:e.storeDir,pauseRequested:et(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 Re(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 ve(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 ke(e,t){return Q(e,{invoke:(r,s)=>jt(ve(r),s,{cliDir:t,cwd:t})})}function be(){console.error("Usage: step-machine-cli <step-flow.yaml> [--initial-data <json>] [--store <memory|file>] [--store-dir <directory>] [--resume]"),console.error(" step-machine-cli --store file --store-dir <directory> --pause"),console.error(" step-machine-cli --store file --store-dir <directory> --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 --store file --store-dir ./.runs"),console.error(" step-machine-cli ./flow.yaml --store file --store-dir ./.runs --resume"),console.error(" step-machine-cli --store file --store-dir ./.runs --pause"),console.error(" step-machine-cli --store file --store-dir ./.runs --status");}
|
|
4
|
-
export{
|
|
3
|
+
- `)}`);return t}function X(e){return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function rt(e){return atob(e.replace(/-/g,"+").replace(/_/g,"/"))}var j=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[rt(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=>rt(t.slice(6)))}};var ot=dirname(fileURLToPath(import.meta.url)),Dt=createRequire(import.meta.url);function Bt(){let e=resolve(ot,"./jsonata-sync.cjs");return existsSync(e)?e:resolve(ot,"../card-compute/jsonata-sync.cjs")}var F=Dt(Bt());function it(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 at(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 Y(e,t){return async(n,r)=>{let s=await e(n,r),o=it(s,r?.stepName??"unknown");return {result:o.result,data:at(o.data,t),...o.error?{error:o.error}:{}}}}function ct(e,t,n){if(!t||t.length===0)return null;for(let r of t)try{if(!F(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=ct(r,t,n);return o||e(r,s)}}var lt=dirname(fileURLToPath(import.meta.url)),qt=createRequire(import.meta.url);function zt(){let e=resolve(lt,"./jsonata-sync.cjs");return existsSync(e)?e:resolve(lt,"../../card-compute/jsonata-sync.cjs")}var x=qt(zt());function pt(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{s.push(String(x(o).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{r.stdin=x(e.stdinTemplate).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{r.url=String(x(e.urlTemplate).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).evaluate(t);if(typeof s!="object"||s===null)throw new Error(`headerTemplate must produce an object, got: ${JSON.stringify(s)}`);r.headers=s;}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{r.body=x(e.bodyTemplate).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).evaluate(r);if(typeof i!="string"||!i.trim())throw new Error(`resultExpr did not produce a non-empty string (got ${JSON.stringify(i)})`);s=i;}catch(i){let u=i instanceof Error?i.message:String(i);throw new Error(`[${n}] outputTransforms.resultExpr failed: ${u}`)}if(typeof e.dataTemplate=="string")try{let i=x(e.dataTemplate).evaluate(r);if(!i||typeof i!="object"||Array.isArray(i))throw new Error(`dataTemplate did not produce an object (got ${JSON.stringify(i)})`);o=i;}catch(i){let u=i instanceof Error?i.message:String(i);throw new Error(`[${n}] outputTransforms.dataTemplate failed: ${u}`)}if(typeof e.errorExpr=="string")try{let i=x(e.errorExpr).evaluate(r);a=i!=null?String(i):void 0;}catch(i){let u=i instanceof Error?i.message:String(i);throw new Error(`[${n}] outputTransforms.errorExpr failed: ${u}`)}return a!==void 0?{result:s,data:o,error:a}:{result:s,data:o}}var _="b64:";function Vt(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 Wt(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 J(e){return `${_}${Vt(JSON.stringify(e))}`}function D(e){if(!e.startsWith(_))throw new Error(`Invalid ref format (expected ${_}<base64url(json)>): ${e}`);let t;try{t=JSON.parse(Wt(e.slice(_.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 ft(e){return !!e&&typeof e=="object"&&e.type==="compute-jsonata"&&Array.isArray(e.expr)&&e.expr.length>0}function gt(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 Gt(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 mt(e,t,n){let r=e.expr.map(Gt);return async s=>{let o=s&&typeof s=="object"&&!Array.isArray(s)?{...s}:{},a={},i={expects_data:o,data:a,...n?{config:n}:{}},u,c;for(let d of r)try{let l=F(d.expr).evaluate(i);if(d.bindTo==="result")u=l!=null?String(l):"success";else if(d.bindTo==="error")c=l!=null?String(l):void 0;else if(d.bindTo.startsWith("data."))Xt(a,d.bindTo.slice(5),l);else return {result:"failure",data:{},error:`[${t}] invalid bindTo "${d.bindTo}": must be "result", "error", or start with "data."`}}catch(l){let f=l instanceof Error?l.message:String(l);return {result:"failure",data:{},error:`[${t}] compute "${d.bindTo}" failed: ${f}`}}return u===void 0?{result:"failure",data:{},error:`[${t}] compute-jsonata: no "result" binding declared \u2014 add '- result = "success"' to expr`}:c?{result:u,data:a,error:c}:{result:u,data:a}}}function ht(e,t,n,r){let{type:s,...o}=e,a={...o,whatToRun:typeof o.whatToRun=="object"?J(o.whatToRun):o.whatToRun};return async i=>{let u=i&&typeof i=="object"&&!Array.isArray(i)?{...i}:{};r&&(u.config=r);try{let c=await n(a,u);if(!e.outputTransforms)return c;try{return dt(e.outputTransforms,c,t)}catch(d){let l=d instanceof Error?d.message:String(d);return {result:"failure",data:{},error:l}}}catch(c){let d=c instanceof Error?c.message:String(c);return {result:"failure",data:{error:`[step-machine-public] step "${t}" invoke threw: ${d}`}}}}}function yt(){return async e=>({result:"success",data:e&&typeof e=="object"&&!Array.isArray(e)?e:{}})}function Yt(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]:u,...c}=r,d=Math.max(1,t.concurrency??1),l=new Array(a.length),f=0,h=0,w=0;return await new Promise(p=>{function g(){for(;f<d&&h<a.length;){let R=h++;f++;let P={...c,[t.as]:a[R]};e(P,s).then(S=>{l[R]=S;}).catch(S=>{let y=S instanceof Error?S.message:String(S);l[R]={result:"failure",data:{},error:y};}).finally(()=>{f--,l[R]?.result==="failure"&&w++,h>=a.length&&f===0?p():g();});}f===0&&h>=a.length&&p();}g();}),w>0?{result:"failure",data:{errors:l.filter(g=>g.result==="failure").map(g=>g.error)},error:`[${n}] forEach: ${w}/${a.length} items failed`}:{result:"success",data:{[i]:l.map(p=>p.data)}}}}function wt(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 ft(a)?i=mt(a,e,o):gt(a)?i=ht(a,e,n.invoke,o):i=yt(),t?.forEach&&(i=Yt(i,t.forEach,e)),Q(Y(i,r),s,e)}function B(e,t){let n={};for(let[r,s]of Object.entries(e.steps??{}))n[r]=wt(r,s,t);return n}function ee(e){if(typeof e=="object"&&e!==null){let{command:n,args:r=[],...s}=e,o=Rt(n,r);return {...s,command:o.command,args:o.args}}let t=vt(e);if(t.length===0)throw new Error(`Empty command spec: ${JSON.stringify(e)}`);return Rt(t[0],t.slice(1))}function Rt(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 vt(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 Z(e){return process.platform==="win32"&&/\.(cmd|bat)$/i.test(e)}function kt(e,t){let{command:n,args:r=[],cwd:s,env:o,timeoutMs:a}=e;return execFileSync(n,r,{shell:Z(n),timeout:a,encoding:t?.encoding??"utf-8",cwd:s,windowsHide:true,env:o?{...process.env,...o}:void 0,input:t?.input})}function ne(e,t){let{command:n,args:r=[],cwd:s,env:o,timeoutMs:a=3e4}=e;execFile(n,r,{shell:Z(n),encoding:"utf8",windowsHide:true,timeout:a,maxBuffer:10*1024*1024,cwd:s,env:o?{...process.env,...o}:void 0},(i,u,c)=>t(i??null,u,c));}k.join(xt.tmpdir(),".board-live-cards-git-bash-cache.json");function bt(e){let{command:t,args:n=[]}=e;if(process.platform==="win32"){spawn(t,n,{detached:true,stdio:"ignore",windowsHide:true,shell:Z(t)}).unref();return}spawn(t,n,{detached:true,stdio:"ignore"}).unref();}function Et(e,t,n){let r=k.join(e,"board-live-cards-cli.js");if(m.existsSync(r))return {cmd:process.execPath,args:[r,t,...n]};let s=k.join(e,"board-live-cards-cli.ts"),o=k.join(e,"..","..","node_modules","tsx","dist","cli.mjs"),a=k.join(e,"..","..","node_modules",".bin","tsx"),i=m.existsSync(o)?o:a;return m.existsSync(s)&&m.existsSync(i)?{cmd:process.execPath,args:[i,s,t,...n]}:{cmd:process.platform==="win32"?"npx.cmd":"npx",args:["tsx",s,t,...n]}}function At(){return {executeSync(e,t,n){return kt({command:e,args:t,cwd:n?.cwd,timeoutMs:n?.timeout,env:n?.env},{encoding:n?.encoding,input:n?.input})},executeAsync(e,t,n){ne({command:e,args:t},n);},resolveInvocation(e,t){let n=ee({command:e,args:t});return {cmd:n.command,args:n.args??[]}},splitCommand:vt,spawnDetached(e,t){bt({command:e,args:t});}}}function re(e,t){let n=typeof e=="object"?e.value:D(e).value;switch(n){case "source-cli-task-executor":{let r=k.join(t,"source-cli-task-executor.js");if(m.existsSync(r))return {command:process.execPath,args:[r]};let s=k.join(t,"source-cli-task-executor.ts"),o=k.join(t,"..","..","node_modules","tsx","dist","cli.mjs"),a=k.join(t,"..","..","node_modules",".bin","tsx"),i=m.existsSync(o)?o:a;return m.existsSync(s)&&m.existsSync(i)?{command:process.execPath,args:[i,s]}:{command:process.execPath,args:[r]}}case "board-live-cards":{let{cmd:r,args:s}=Et(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 se(e,t){if(e.howToRun==="built-in"){let{command:r,args:s}=re(e.whatToRun,t);return {command:r,baseArgs:s}}let n=typeof e.whatToRun=="object"?e.whatToRun.value:D(e.whatToRun).value;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 oe(e,t){return se(e,t)}function ie(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 ae(e){let t=e.whatToRun;return typeof t=="object"?t.value:D(t).value}function ce(e,t){return {...t,whatToRun:ae(e),...e.extra?{extra:e.extra}:{}}}function ue(e,t,n="invokeExecutionRef"){return pt(e,t,n)}function le(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=ue(e.argsMassaging,ce(e,t),r);}catch(l){let f=l instanceof Error?l.message:String(l);return L(f)}let a;try{a=oe(e,s);}catch(l){let f=l instanceof Error?l.message:String(l);return L(`[${r}] ref resolution failed: ${f}`)}let i=[...a.baseArgs,...o.cmdArgs??[]],u=JSON.stringify(o.stdin??t),c=At(),d;try{d=c.executeSync(a.command,i,{timeout:n?.timeoutMs??3e4,encoding:"utf-8",cwd:n?.cwd,input:u});}catch(l){let f=l,h=(f.stderr?String(f.stderr):"").trim(),w=typeof f.status=="number"?f.status:"unknown",p=h||f.message;return L(`[${r}] ref exited with status ${w}${p?`: ${p}`:""}`)}try{return le(ie(d))}catch{return {result:"success",data:{stdout:d.trim()}}}}var pe={"local-node":N,"local-python":N,"local-process":N,"built-in":N};function de(e,t,n){let r=n?.syncTransports?.[e.howToRun]??pe[e.howToRun];return r?r(e,t,n):L(`[${n?.label??"invokeExecutionRefSync"}] unsupported sync howToRun: ${e.howToRun}`)}function jt(e,t,n){return de(e,t,n)}function ge(e,t){if(process.platform!=="win32"){m.renameSync(e,t);return}let n=[10,20,40,80,160];for(let r=0;r<=n.length;r++)try{m.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 k.join(e,...r.split("/"))+".json"}function n(r,s,o,a){if(m.existsSync(r))for(let i of m.readdirSync(r,{withFileTypes:true})){let u=s?`${s}/${i.name}`:i.name;if(i.isDirectory()){n(k.join(r,i.name),u,o,a);continue}if(!i.isFile()||!i.name.endsWith(".json"))continue;let c=u.replace(/\.json$/,"");(!o||c.startsWith(o))&&a.push(c);}}return {read(r){let s=t(r);if(!m.existsSync(s))return null;try{return JSON.parse(m.readFileSync(s,"utf-8"))}catch{return null}},write(r,s){let o=t(r),a=`${o}.${process.pid}.${randomUUID()}.tmp`;m.mkdirSync(k.dirname(o),{recursive:true}),m.writeFileSync(a,JSON.stringify(s,null,2),"utf-8"),ge(a,o);},delete(r){let s=t(r);try{m.existsSync(s)&&m.unlinkSync(s);}catch{}},listKeys(r){let s=[];return n(e,"",r,s),s.sort()}}}var K=class extends Error{constructor(n,r){super(r);this.code=n;this.name="CliExitError";}code},me=".pause";async function Yn(e){let t=he(e);if(t.help||e.length===0)throw be(),new K(e.length===0?1:0);let{flowArg:n,dataArg:r,storeArg:s,storeDirArg:o,resumeRequested:a,pauseRequested:i,statusRequested:u}=t;if((i||u)&&(r||a||n))throw new Error("[step-machine-cli] --pause and --status are store-level operations. Do not provide flow, data, or --resume.");if(a&&r)throw new Error("[step-machine-cli] --initial-data cannot be combined with --resume.");let c=ye(s,o);if(u){await Re(c);return}if(i){await we(c);return}if(!n)throw new Error("[step-machine-cli] Flow path is required for run/resume operations.");let d=$t(n),l=k.dirname(d),f=xe(r),{store:h}=c,w=await H(d),p=ke(w,l);Tt(c);let g=new AbortController,R=false,P=T(w,p,{store:h,signal:g.signal,onStep:()=>{!R&&et(c)&&(R=true,g.abort());}}),S;if(a){if(S=await Ft(c),!S){console.warn("[step-machine-cli] No paused run found in store directory."),console.log(JSON.stringify({status:"noop",reason:"no-paused-run"},null,2));return}}else c.storeType==="file"&&!f&&(S=await Ft(c));let y=S?await P.resume(S):await P.run(f);if(R&&y.status==="cancelled"){let O=await Se(h,y.runId);Tt(c),console.log(JSON.stringify({runId:y.runId,status:"paused",currentStep:O?.currentStep,pausedAt:O?.pausedAt,stepHistory:y.stepHistory,data:y.data},null,2));return}if(y.status!=="completed"){let O=y.error?.message??y.intent??y.status;throw console.error(`[step-machine-cli] Run failed: ${O}`),new K(1)}console.log(JSON.stringify({runId:y.runId,status:y.status,intent:y.intent,finalStep:y.finalStep,stepHistory:y.stepHistory,data:y.data},null,2));}function he(e){let t=new Set(["--initial-data","--store","--store-dir"]),n={},r=[],s=false,o=false,a=false,i=false;for(let u=0;u<e.length;u++){let c=e[u];if(c==="-h"||c==="--help"){s=true;continue}if(c==="--resume"){o=true;continue}if(c==="--pause"){a=true;continue}if(c==="--status"){i=true;continue}if(t.has(c)){let d=e[u+1];if(!d||d.startsWith("--"))throw new Error(`[step-machine-cli] Missing value for ${c}.`);n[c]=d,u++;continue}if(c.startsWith("--"))throw new Error(`[step-machine-cli] Unknown flag: ${c}`);r.push(c);}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"],storeArg:String(n["--store"]??"memory").toLowerCase(),storeDirArg:n["--store-dir"],resumeRequested:o,pauseRequested:a,statusRequested:i}}function $t(e){return k.isAbsolute(e)?e:k.resolve(process.cwd(),e)}function ye(e,t){if(e!=="memory"&&e!=="file")throw new Error(`[step-machine-cli] Invalid --store value "${e}". Expected "memory" or "file".`);if(e==="memory")return {storeType:e,storeDir:void 0,pauseFilePath:void 0,store:new v};if(!t||t.trim().length===0)throw new Error("[step-machine-cli] --store file requires --store-dir <directory>.");let n=$t(t);return {storeType:e,storeDir:n,pauseFilePath:k.join(n,me),store:new j(Ct(n))}}async function tt(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 et(e){return e.storeType!=="file"||!e.pauseFilePath?false:m.existsSync(e.pauseFilePath)}function Tt(e){et(e)&&m.unlinkSync(e.pauseFilePath);}async function we(e){if(e.storeType!=="file"||!e.pauseFilePath)throw new Error("[step-machine-cli] --pause requires --store file --store-dir <directory>.");let t=await tt(e.store);if(t.length===0){console.warn("[step-machine-cli] No runs found in store directory. 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}m.mkdirSync(e.storeDir,{recursive:true}),m.writeFileSync(e.pauseFilePath,JSON.stringify({requestedAt:Date.now()}),"utf-8"),console.log(JSON.stringify({status:"pause-requested",storeDir:e.storeDir},null,2));}async function Ft(e){let n=(await tt(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 Se(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 Re(e){if(e.storeType!=="file")throw new Error("[step-machine-cli] --status requires --store file --store-dir <directory>.");let t=await tt(e.store),n={store:"file",storeDir:e.storeDir,pauseRequested:et(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 xe(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 ve(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 ke(e,t){return B(e,{invoke:(r,s)=>jt(ve(r),s,{cliDir:t,cwd:t})})}function be(){console.error("Usage: step-machine-cli <step-flow.yaml> [--initial-data <json>] [--store <memory|file>] [--store-dir <directory>] [--resume]"),console.error(" step-machine-cli --store file --store-dir <directory> --pause"),console.error(" step-machine-cli --store file --store-dir <directory> --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 --store file --store-dir ./.runs"),console.error(" step-machine-cli ./flow.yaml --store file --store-dir ./.runs --resume"),console.error(" step-machine-cli --store file --store-dir ./.runs --pause"),console.error(" step-machine-cli --store file --store-dir ./.runs --status");}
|
|
4
|
+
export{K as CliExitError,Yn as cli};//# sourceMappingURL=step-machine-cli.js.map
|
|
5
5
|
//# sourceMappingURL=step-machine-cli.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { E as ExecutionRef } from './execution-interface-ftO1W7Po.js';
|
|
2
|
-
import { L as LiveCard,
|
|
2
|
+
import { L as LiveCard, a as BoardStatusObject, J as JournalStorageAdapter, O as OutputStoreEvent } from './board-live-cards-lib-Iq_XAC09.js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* storage-interface.ts
|
|
@@ -49,8 +49,8 @@ interface BlobStorage {
|
|
|
49
49
|
readBytes?(key: string): Uint8Array | null;
|
|
50
50
|
/** Optional binary write for file-like artifacts. */
|
|
51
51
|
writeBytes?(key: string, content: Uint8Array): void;
|
|
52
|
-
/**
|
|
53
|
-
listKeys
|
|
52
|
+
/** List all keys that start with the given prefix. */
|
|
53
|
+
listKeys(prefix?: string): string[];
|
|
54
54
|
/** Optional metadata lookup. */
|
|
55
55
|
stat?(key: string): BlobStat | null;
|
|
56
56
|
}
|
|
@@ -62,6 +62,28 @@ interface KindValueRef {
|
|
|
62
62
|
declare function serializeRef(ref: KindValueRef): string;
|
|
63
63
|
/** Parse a wire-format ref string (b64:<base64url(json)>) into a KindValueRef. */
|
|
64
64
|
declare function parseRef(s: string): KindValueRef;
|
|
65
|
+
interface JournalEntry {
|
|
66
|
+
id: string;
|
|
67
|
+
payload: unknown;
|
|
68
|
+
}
|
|
69
|
+
interface JournalReadResult {
|
|
70
|
+
entries: JournalEntry[];
|
|
71
|
+
/** The id of the last entry returned, suitable for use as the next cursor. */
|
|
72
|
+
newCursor: string | null;
|
|
73
|
+
}
|
|
74
|
+
interface JournalStorage {
|
|
75
|
+
/** Append an entry. The storage layer assigns the id. */
|
|
76
|
+
append(payload: unknown): JournalEntry;
|
|
77
|
+
/** Read ALL entries (for index rebuilds, full replay). */
|
|
78
|
+
readAll(): JournalEntry[];
|
|
79
|
+
/**
|
|
80
|
+
* Read entries appended after the given cursor id.
|
|
81
|
+
* If cursor is null/empty, returns all entries from the beginning.
|
|
82
|
+
*/
|
|
83
|
+
readAfter(cursor: string | null): JournalReadResult;
|
|
84
|
+
/** Truncate all entries. Optional — not all backends support it. */
|
|
85
|
+
clear?(): void;
|
|
86
|
+
}
|
|
65
87
|
interface KVStorage {
|
|
66
88
|
/** Returns the stored value, or null if the key does not exist. */
|
|
67
89
|
read(key: string): unknown | null;
|
|
@@ -138,7 +160,7 @@ interface BoardPlatformAdapter {
|
|
|
138
160
|
* KV storage factory — scoped by namespace.
|
|
139
161
|
* Namespaces used by the public layer:
|
|
140
162
|
* 'state-snapshot' — board graph snapshot (StateSnapshotStorageAdapter, built internally)
|
|
141
|
-
* 'config' — board configuration (.task-executor, .chat-handler, .card-store-ref)
|
|
163
|
+
* 'config' — board configuration (.task-executor, .chat-handler, .chat-handler-flow, .card-store-ref)
|
|
142
164
|
* 'card-upsert' — card upsert dedup index
|
|
143
165
|
* 'execution-requests' — queued execution requests (keyed by journalId)
|
|
144
166
|
* 'card-runtime' — card runtime state snapshots
|
|
@@ -344,6 +366,56 @@ interface BoardLiveCardsNonCorePublic {
|
|
|
344
366
|
}
|
|
345
367
|
declare function createBoardLiveCardsNonCorePublic(baseRef: KindValueRef, adapter: BoardNonCorePlatformAdapter): BoardLiveCardsNonCorePublic;
|
|
346
368
|
|
|
369
|
+
/**
|
|
370
|
+
* chat-storage-lib.ts
|
|
371
|
+
*
|
|
372
|
+
* ChatStorage interface + factories backed by JournalStorage (history) and
|
|
373
|
+
* KVStorage (processing state and config).
|
|
374
|
+
*
|
|
375
|
+
* Platform-free — no node:fs or node:crypto imports.
|
|
376
|
+
*/
|
|
377
|
+
|
|
378
|
+
interface ChatRecord {
|
|
379
|
+
/** Journal entry id — also used as SSE cursor. */
|
|
380
|
+
id: string;
|
|
381
|
+
role: string;
|
|
382
|
+
text: string;
|
|
383
|
+
files: unknown[];
|
|
384
|
+
updated_at: string;
|
|
385
|
+
}
|
|
386
|
+
interface ChatConfig {
|
|
387
|
+
systemPrompt?: string;
|
|
388
|
+
}
|
|
389
|
+
interface ChatReadAfterResult {
|
|
390
|
+
records: ChatRecord[];
|
|
391
|
+
/** Pass as cursor on the next call. Null when the journal is empty. */
|
|
392
|
+
cursor: string | null;
|
|
393
|
+
}
|
|
394
|
+
interface ChatStorage {
|
|
395
|
+
/** Append a message; returns the new entry id (usable as a cursor). */
|
|
396
|
+
append(cardId: string, role: string, text: string, files?: unknown[]): string;
|
|
397
|
+
/** Read all messages in insertion order. */
|
|
398
|
+
readAll(cardId: string): ChatRecord[];
|
|
399
|
+
/**
|
|
400
|
+
* Read messages appended after cursor.
|
|
401
|
+
* Pass null to read from the beginning.
|
|
402
|
+
*/
|
|
403
|
+
readAfter(cardId: string, cursor: string | null): ChatReadAfterResult;
|
|
404
|
+
/** Remove all messages for this card. */
|
|
405
|
+
clear(cardId: string): void;
|
|
406
|
+
setProcessing(cardId: string, active: boolean): void;
|
|
407
|
+
isProcessing(cardId: string): boolean;
|
|
408
|
+
getConfig(cardId: string): ChatConfig;
|
|
409
|
+
setConfig(cardId: string, patch: Partial<ChatConfig>): void;
|
|
410
|
+
}
|
|
411
|
+
/**
|
|
412
|
+
* Create a ChatStorage backed by:
|
|
413
|
+
* - journalFactory(cardId) → JournalStorage (one per-card journal for history)
|
|
414
|
+
* - kv → KVStorage (shared processing flags + config)
|
|
415
|
+
*/
|
|
416
|
+
declare function createChatStorage(journalFactory: (cardId: string) => JournalStorage, kv: KVStorage): ChatStorage;
|
|
417
|
+
declare function createInMemoryChatStorage(): ChatStorage;
|
|
418
|
+
|
|
347
419
|
/**
|
|
348
420
|
* server-runtime/types.ts
|
|
349
421
|
*
|
|
@@ -392,4 +464,4 @@ interface DescribeEnvelope {
|
|
|
392
464
|
supports?: string[];
|
|
393
465
|
}
|
|
394
466
|
|
|
395
|
-
export { type BoardPlatformAdapter as B, type
|
|
467
|
+
export { type BoardPlatformAdapter as B, type ChatStorage as C, type DescribeEnvelope as D, type InvocationAdapter as I, type KindValueRef as K, type NotificationTransport as N, type CommandInput as a, type CommandResult as b, type BlobStorage as c, type BoardNonCorePlatformAdapter as d, type BoardLiveCardsNonCorePublic as e, type BoardLiveCardsPublic as f, type ChatConfig as g, type ChatRecord as h, createBoardLiveCardsNonCorePublic as i, createBoardLiveCardsPublic as j, createChatStorage as k, createInMemoryChatStorage as l, parseRef as p, serializeRef as s };
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
{
|
|
2
|
+
"card-market-prices": {
|
|
3
|
+
"key": "card-market-prices",
|
|
4
|
+
"checksum": "card-market-prices",
|
|
5
|
+
"updatedAt": "2026-05-16T11:48:32.081Z"
|
|
6
|
+
},
|
|
7
|
+
"card-portfolio-value": {
|
|
8
|
+
"key": "card-portfolio-value",
|
|
9
|
+
"checksum": "card-portfolio-value",
|
|
10
|
+
"updatedAt": "2026-05-16T11:48:32.086Z"
|
|
11
|
+
},
|
|
12
|
+
"card-portfolio": {
|
|
13
|
+
"key": "card-portfolio",
|
|
14
|
+
"checksum": "card-portfolio",
|
|
15
|
+
"updatedAt": "2026-05-16T11:48:32.091Z"
|
|
16
|
+
}
|
|
17
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
{
|
|
2
|
+
"id": "card-market-prices",
|
|
3
|
+
"meta": {
|
|
4
|
+
"title": "Market Prices",
|
|
5
|
+
"tags": [
|
|
6
|
+
"prices",
|
|
7
|
+
"market"
|
|
8
|
+
],
|
|
9
|
+
"desc": "Fetches live prices for portfolio tickers. Publishes enriched quote data for downstream portfolio value calculations."
|
|
10
|
+
},
|
|
11
|
+
"requires": [
|
|
12
|
+
"holdings"
|
|
13
|
+
],
|
|
14
|
+
"source_defs": [
|
|
15
|
+
{
|
|
16
|
+
"bindTo": "quotes",
|
|
17
|
+
"outputFile": "market-prices-quotes.json",
|
|
18
|
+
"projections": {
|
|
19
|
+
"url_list": "requires.holdings.ticker.('https://query1.finance.yahoo.com/v8/finance/chart/' & $ & '?interval=1d&range=1d')"
|
|
20
|
+
},
|
|
21
|
+
"url-list": {
|
|
22
|
+
"headers": {
|
|
23
|
+
"User-Agent": "Mozilla/5.0 (compatible; portfolio-tracker-demo/1.0)"
|
|
24
|
+
},
|
|
25
|
+
"cacheTimeout": 3600
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
],
|
|
29
|
+
"compute": [
|
|
30
|
+
{
|
|
31
|
+
"bindTo": "normalizedQuotes",
|
|
32
|
+
"expr": "{ \"quoteResponse\": { \"result\": $map(fetched_sources.quotes, function($r) { ($m := $r.chart.result[0].meta; $price := $sum($m.regularMarketPrice); $prev := $sum($m.chartPreviousClose); $chg := $price - $prev; { \"symbol\": $join($m.symbol, \"\"), \"shortName\": ($join($m.shortName, \"\") != \"\" ? $join($m.shortName, \"\") : $join($m.longName, \"\")), \"regularMarketPrice\": $price, \"regularMarketChange\": $chg, \"regularMarketChangePercent\": $prev = 0 ? 0 : ($chg / $prev * 100) }) }), \"error\": null } }"
|
|
33
|
+
},
|
|
34
|
+
{
|
|
35
|
+
"bindTo": "prices",
|
|
36
|
+
"expr": "$map((computed_values.normalizedQuotes.quoteResponse.result ? computed_values.normalizedQuotes.quoteResponse.result : []), function($q) { {\"ticker\": $q.symbol, \"name\": $q.shortName, \"price\": $round($q.regularMarketPrice, 2), \"change\": $round($q.regularMarketChange, 2), \"chg_pct\": $round($q.regularMarketChangePercent, 2)} })"
|
|
37
|
+
}
|
|
38
|
+
],
|
|
39
|
+
"provides": [
|
|
40
|
+
{
|
|
41
|
+
"bindTo": "quotes",
|
|
42
|
+
"ref": "computed_values.normalizedQuotes"
|
|
43
|
+
}
|
|
44
|
+
],
|
|
45
|
+
"view": {
|
|
46
|
+
"elements": [
|
|
47
|
+
{
|
|
48
|
+
"kind": "table",
|
|
49
|
+
"label": "Prices",
|
|
50
|
+
"data": {
|
|
51
|
+
"bind": "computed_values.prices",
|
|
52
|
+
"columns": [
|
|
53
|
+
"ticker",
|
|
54
|
+
"name",
|
|
55
|
+
"price",
|
|
56
|
+
"change",
|
|
57
|
+
"chg_pct"
|
|
58
|
+
],
|
|
59
|
+
"sortable": true
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
],
|
|
63
|
+
"layout": {
|
|
64
|
+
"board": {
|
|
65
|
+
"col": 4,
|
|
66
|
+
"order": 2
|
|
67
|
+
},
|
|
68
|
+
"canvas": {
|
|
69
|
+
"x": 400,
|
|
70
|
+
"y": 50,
|
|
71
|
+
"w": 400,
|
|
72
|
+
"h": 340
|
|
73
|
+
}
|
|
74
|
+
},
|
|
75
|
+
"features": {
|
|
76
|
+
"refresh": true
|
|
77
|
+
}
|
|
78
|
+
},
|
|
79
|
+
"card_data": {}
|
|
80
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
{
|
|
2
|
+
"id": "card-portfolio-value",
|
|
3
|
+
"meta": {
|
|
4
|
+
"title": "Portfolio Value",
|
|
5
|
+
"tags": [
|
|
6
|
+
"portfolio",
|
|
7
|
+
"value"
|
|
8
|
+
],
|
|
9
|
+
"desc": "Computes total portfolio value, gainers/losers summary, and per-position P&L from holdings and live market quotes."
|
|
10
|
+
},
|
|
11
|
+
"requires": [
|
|
12
|
+
"holdings",
|
|
13
|
+
"quotes"
|
|
14
|
+
],
|
|
15
|
+
"provides": [
|
|
16
|
+
{
|
|
17
|
+
"bindTo": "positions",
|
|
18
|
+
"ref": "computed_values.positions"
|
|
19
|
+
}
|
|
20
|
+
],
|
|
21
|
+
"compute": [
|
|
22
|
+
{
|
|
23
|
+
"bindTo": "positions",
|
|
24
|
+
"expr": "($hMap := $merge(requires.holdings.{ticker: $}); $map(requires.quotes.quoteResponse.result, function($q) { ($h := $lookup($hMap, $q.symbol); $qty := $h.quantity; $cb := $h.cost_basis; $val := $round($q.regularMarketPrice * $qty, 2); $cost := $round($cb * $qty, 2); $chg := $round($q.regularMarketChange * $qty, 2); {\"ticker\": $q.symbol, \"quantity\": $qty, \"cost_basis\": $cb, \"price\": $round($q.regularMarketPrice, 2), \"value\": $val, \"gain_$\": $round($val - $cost, 2), \"gain_%\": $round(($val - $cost) / $cost * 100, 2), \"chg_$\": $chg, \"chg_pct\": $round($q.regularMarketChangePercent, 2)}) }))"
|
|
25
|
+
},
|
|
26
|
+
{
|
|
27
|
+
"bindTo": "totalValue",
|
|
28
|
+
"expr": "$round($sum(computed_values.positions.value), 2)"
|
|
29
|
+
},
|
|
30
|
+
{
|
|
31
|
+
"bindTo": "gainers",
|
|
32
|
+
"expr": "$count($filter(computed_values.positions, function($p){ $p.chg_pct > 0 }))"
|
|
33
|
+
},
|
|
34
|
+
{
|
|
35
|
+
"bindTo": "losers",
|
|
36
|
+
"expr": "$count($filter(computed_values.positions, function($p){ $p.chg_pct < 0 }))"
|
|
37
|
+
},
|
|
38
|
+
{
|
|
39
|
+
"bindTo": "gainersLosers",
|
|
40
|
+
"expr": "computed_values.gainers & ' up · ' & computed_values.losers & ' down'"
|
|
41
|
+
}
|
|
42
|
+
],
|
|
43
|
+
"view": {
|
|
44
|
+
"elements": [
|
|
45
|
+
{
|
|
46
|
+
"kind": "metric",
|
|
47
|
+
"label": "Portfolio Value ($)",
|
|
48
|
+
"data": {
|
|
49
|
+
"bind": "computed_values.totalValue"
|
|
50
|
+
}
|
|
51
|
+
},
|
|
52
|
+
{
|
|
53
|
+
"kind": "text",
|
|
54
|
+
"data": {
|
|
55
|
+
"bind": "computed_values.gainersLosers"
|
|
56
|
+
}
|
|
57
|
+
},
|
|
58
|
+
{
|
|
59
|
+
"kind": "table",
|
|
60
|
+
"label": "Positions",
|
|
61
|
+
"data": {
|
|
62
|
+
"bind": "computed_values.positions",
|
|
63
|
+
"columns": [
|
|
64
|
+
"ticker",
|
|
65
|
+
"value",
|
|
66
|
+
"gain_$",
|
|
67
|
+
"gain_%"
|
|
68
|
+
],
|
|
69
|
+
"sortable": true
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
],
|
|
73
|
+
"layout": {
|
|
74
|
+
"board": {
|
|
75
|
+
"col": 4,
|
|
76
|
+
"order": 3
|
|
77
|
+
},
|
|
78
|
+
"canvas": {
|
|
79
|
+
"x": 840,
|
|
80
|
+
"y": 50,
|
|
81
|
+
"w": 420,
|
|
82
|
+
"h": 380
|
|
83
|
+
}
|
|
84
|
+
},
|
|
85
|
+
"features": {
|
|
86
|
+
"chat": true
|
|
87
|
+
}
|
|
88
|
+
},
|
|
89
|
+
"card_data": {}
|
|
90
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
{
|
|
2
|
+
"id": "card-portfolio",
|
|
3
|
+
"meta": {
|
|
4
|
+
"title": "My Portfolio",
|
|
5
|
+
"tags": [
|
|
6
|
+
"portfolio"
|
|
7
|
+
],
|
|
8
|
+
"desc": "Manage your stock holdings — edit tickers and quantities inline, add or delete rows. Changes propagate downstream immediately."
|
|
9
|
+
},
|
|
10
|
+
"provides": [
|
|
11
|
+
{
|
|
12
|
+
"bindTo": "holdings",
|
|
13
|
+
"ref": "card_data.holdings"
|
|
14
|
+
}
|
|
15
|
+
],
|
|
16
|
+
"compute": [],
|
|
17
|
+
"view": {
|
|
18
|
+
"elements": [
|
|
19
|
+
{
|
|
20
|
+
"kind": "editable-table",
|
|
21
|
+
"label": "Holdings",
|
|
22
|
+
"data": {
|
|
23
|
+
"bind": "card_data.holdings",
|
|
24
|
+
"writeTo": "card_data.holdings",
|
|
25
|
+
"columns": [
|
|
26
|
+
"ticker",
|
|
27
|
+
"quantity",
|
|
28
|
+
"cost_basis"
|
|
29
|
+
],
|
|
30
|
+
"schema": {
|
|
31
|
+
"properties": {
|
|
32
|
+
"quantity": {
|
|
33
|
+
"type": "number"
|
|
34
|
+
},
|
|
35
|
+
"cost_basis": {
|
|
36
|
+
"type": "number"
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
],
|
|
43
|
+
"layout": {
|
|
44
|
+
"board": {
|
|
45
|
+
"col": 4,
|
|
46
|
+
"order": 1
|
|
47
|
+
},
|
|
48
|
+
"canvas": {
|
|
49
|
+
"x": 50,
|
|
50
|
+
"y": 50,
|
|
51
|
+
"w": 320,
|
|
52
|
+
"h": 340
|
|
53
|
+
}
|
|
54
|
+
},
|
|
55
|
+
"features": {
|
|
56
|
+
"chat": true
|
|
57
|
+
}
|
|
58
|
+
},
|
|
59
|
+
"card_data": {
|
|
60
|
+
"holdings": [
|
|
61
|
+
{
|
|
62
|
+
"ticker": "AAPL",
|
|
63
|
+
"quantity": 10,
|
|
64
|
+
"cost_basis": 150
|
|
65
|
+
},
|
|
66
|
+
{
|
|
67
|
+
"ticker": "NVDA",
|
|
68
|
+
"quantity": 5,
|
|
69
|
+
"cost_basis": 310
|
|
70
|
+
},
|
|
71
|
+
{
|
|
72
|
+
"ticker": "GOOG",
|
|
73
|
+
"quantity": 3,
|
|
74
|
+
"cost_basis": 33
|
|
75
|
+
}
|
|
76
|
+
]
|
|
77
|
+
}
|
|
78
|
+
}
|
|
@@ -16,9 +16,11 @@
|
|
|
16
16
|
"bindTo": "quotes",
|
|
17
17
|
"outputFile": "market-prices-quotes.json",
|
|
18
18
|
"projections": {
|
|
19
|
-
"
|
|
19
|
+
"quote_urls": "requires.holdings.ticker.('https://query1.finance.yahoo.com/v8/finance/chart/' & $ & '?interval=1d&range=1d')"
|
|
20
20
|
},
|
|
21
|
-
"
|
|
21
|
+
"urls": {
|
|
22
|
+
"url": "{{url}}",
|
|
23
|
+
"projectionList": "quote_urls",
|
|
22
24
|
"headers": {
|
|
23
25
|
"User-Agent": "Mozilla/5.0 (compatible; portfolio-tracker-demo/1.0)"
|
|
24
26
|
},
|
|
@@ -29,11 +31,11 @@
|
|
|
29
31
|
"compute": [
|
|
30
32
|
{
|
|
31
33
|
"bindTo": "normalizedQuotes",
|
|
32
|
-
"expr": "
|
|
34
|
+
"expr": "($raw := fetched_sources.quotes; $rows := $type($raw) = 'array' ? $raw : (($exists($raw.resultValue) and $type($raw.resultValue) = 'array') ? $raw.resultValue : [$raw]); $normalized := $filter($map($rows, function($row) { ($level1 := $exists($row.resultValue) ? $row.resultValue : $row; $level2 := $exists($level1.resultValue) ? $level1.resultValue : $level1; $meta := $level2.chart.result[0].meta; $exists($meta.symbol) ? { \"symbol\": $meta.symbol, \"shortName\": ($exists($meta.longName) ? $meta.longName : $meta.shortName), \"regularMarketPrice\": $meta.regularMarketPrice, \"regularMarketChange\": ($exists($meta.regularMarketChange) ? $meta.regularMarketChange : (($exists($meta.chartPreviousClose) and $exists($meta.regularMarketPrice)) ? ($meta.regularMarketPrice - $meta.chartPreviousClose) : null)), \"regularMarketChangePercent\": ($exists($meta.regularMarketChangePercent) ? $meta.regularMarketChangePercent : (($exists($meta.chartPreviousClose) and $meta.chartPreviousClose != 0 and $exists($meta.regularMarketPrice)) ? (($meta.regularMarketPrice - $meta.chartPreviousClose) / $meta.chartPreviousClose * 100) : null)) } : undefined) }), function($q) { $exists($q.symbol) }); { \"quoteResponse\": { \"result\": $normalized, \"error\": null } })"
|
|
33
35
|
},
|
|
34
36
|
{
|
|
35
37
|
"bindTo": "prices",
|
|
36
|
-
"expr": "$map(
|
|
38
|
+
"expr": "$map(computed_values.normalizedQuotes.quoteResponse.result, function($q) { {\"ticker\": $q.symbol, \"name\": $q.shortName, \"price\": ($exists($q.regularMarketPrice) ? $round($q.regularMarketPrice, 2) : null), \"change\": ($exists($q.regularMarketChange) ? $round($q.regularMarketChange, 2) : null), \"chg_pct\": ($exists($q.regularMarketChangePercent) ? $round($q.regularMarketChangePercent, 2) : null)} })"
|
|
37
39
|
}
|
|
38
40
|
],
|
|
39
41
|
"provides": [
|