yaml-flow 8.2.4 → 8.3.0

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.
Files changed (77) hide show
  1. package/browser/asset-integrity.json +3 -3
  2. package/browser/board-livecards-client.js +1 -1
  3. package/browser/board-livecards-localstorage.js +4 -4
  4. package/browser/live-cards.js +19 -19
  5. package/cli/{board-live-cards-lib-Iq_XAC09.d.ts → board-live-cards-lib-tjYsPt5U.d.ts} +1 -1
  6. package/cli/browser-api/board-live-cards-browser-adapter.d.ts +3 -3
  7. package/cli/browser-api/card-store-browser-api.d.ts +1 -1
  8. package/cli/browser-api/card-store-browser-api.js +1 -1
  9. package/cli/{execution-interface-ftO1W7Po.d.ts → execution-interface-CrG5gzAx.d.ts} +116 -2
  10. package/cli/node/batch-runner-cli.d.ts +3 -0
  11. package/cli/node/batch-runner-cli.js +2 -1
  12. package/cli/node/board-live-cards-cli.js +7 -7
  13. package/cli/node/card-store-cli.js +5 -5
  14. package/cli/node/chat-store-cli.d.ts +23 -0
  15. package/cli/node/chat-store-cli.js +8 -0
  16. package/cli/node/execution-adapter.d.ts +4 -2
  17. package/cli/node/execution-adapter.js +2 -2
  18. package/cli/node/fs-board-adapter.d.ts +7 -6
  19. package/cli/node/fs-board-adapter.js +8 -8
  20. package/cli/node/source-cli-task-executor.js +4 -4
  21. package/cli/node/step-machine-cli.js +3 -3
  22. package/cli/{types--rXGWbSR.d.ts → types-PUfPBxc_.d.ts} +4 -109
  23. package/examples/board/demo-shell-with-server.html +3 -3
  24. package/examples/board/doc.html +465 -0
  25. package/examples/board/server/board-server.js +20 -81
  26. package/examples/board/server/board-worker/source_def_flows.json +2 -2
  27. package/examples/board/server/chat-flow/copilot-chat/assistant.js +44 -185
  28. package/examples/board/server/chat-flow/copilot-chat/copilot_wrapper.bat +157 -0
  29. package/examples/board/server/chat-flow/copilot-chat/copilot_wrapper_helper.ps1 +190 -0
  30. package/examples/board/server/chat-flow/flow-steps.json +122 -56
  31. package/examples/board/test/server-http-test.js +252 -220
  32. package/examples/board-local/demo-shell-localstorage.html +3 -3
  33. package/lib/{artifacts-store-lib-public-C5UL5tyG.d.cts → artifacts-store-lib-public-Cz8-kdXG.d.cts} +1 -1
  34. package/lib/{artifacts-store-lib-public-GD4H-fFp.d.ts → artifacts-store-lib-public-ksGIExhc.d.ts} +1 -1
  35. package/lib/artifacts-store-public.d.cts +2 -2
  36. package/lib/artifacts-store-public.d.ts +2 -2
  37. package/lib/board-live-cards-node.cjs +8 -8
  38. package/lib/board-live-cards-node.d.cts +26 -6
  39. package/lib/board-live-cards-node.d.ts +26 -6
  40. package/lib/board-live-cards-node.js +8 -8
  41. package/lib/{board-live-cards-public-BLXbcBNk.d.cts → board-live-cards-public-BwZYGAsF.d.cts} +1 -1
  42. package/lib/{board-live-cards-public-BZaNb2mi.d.ts → board-live-cards-public-DWpZVDXN.d.ts} +1 -1
  43. package/lib/board-live-cards-public.cjs +2 -2
  44. package/lib/board-live-cards-public.d.cts +1 -1
  45. package/lib/board-live-cards-public.d.ts +1 -1
  46. package/lib/board-live-cards-public.js +2 -2
  47. package/lib/board-live-cards-server-runtime.cjs +3 -3
  48. package/lib/board-live-cards-server-runtime.d.cts +3 -2
  49. package/lib/board-live-cards-server-runtime.d.ts +3 -2
  50. package/lib/board-live-cards-server-runtime.js +3 -3
  51. package/lib/board-worker-adapter.cjs +2 -2
  52. package/lib/board-worker-adapter.js +2 -2
  53. package/lib/card-store-public.d.cts +1 -1
  54. package/lib/card-store-public.d.ts +1 -1
  55. package/lib/chat-storage-lib-BK5Njslc.d.ts +53 -0
  56. package/lib/chat-storage-lib-C5bQ7bGe.d.cts +53 -0
  57. package/lib/chat-store-public.cjs +2 -0
  58. package/lib/chat-store-public.d.cts +128 -0
  59. package/lib/chat-store-public.d.ts +128 -0
  60. package/lib/chat-store-public.js +2 -0
  61. package/lib/execution-refs.d.cts +10 -1
  62. package/lib/execution-refs.d.ts +10 -1
  63. package/lib/server-runtime/index.cjs +3 -3
  64. package/lib/server-runtime/index.d.cts +4 -3
  65. package/lib/server-runtime/index.d.ts +4 -3
  66. package/lib/server-runtime/index.js +3 -3
  67. package/lib/{types-Bztd1KoK.d.cts → types-D9B0Vrwg.d.cts} +4 -53
  68. package/lib/{types-D-xVWPdY.d.ts → types-DNYhCFNJ.d.ts} +4 -53
  69. package/package.json +8 -2
  70. package/examples/board/.board-ws/cards/store/_index.json +0 -17
  71. package/examples/board/.board-ws/cards/store/card-market-prices.json +0 -80
  72. package/examples/board/.board-ws/cards/store/card-portfolio-value.json +0 -90
  73. package/examples/board/.board-ws/cards/store/card-portfolio.json +0 -78
  74. package/examples/board/server/chat-flow/chat-clear-processing.js +0 -41
  75. package/examples/board/server/chat-flow/chat-open-turn.js +0 -144
  76. package/examples/board/server/chat-flow/chat-write-assistant.js +0 -44
  77. package/examples/board/server/chat-flow/echo-probe/assistant.js +0 -28
@@ -1,11 +1,11 @@
1
1
  #!/usr/bin/env node
2
- import*as l from'fs';import*as d from'path';import {execFileSync,spawnSync}from'child_process';function b(e){if(!e.startsWith("b64:"))throw new Error(`Invalid ref format (expected b64:<base64url(json)>): ${e}`);let n=e.slice(4),o=n.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-n.length%4)%4),t;try{t=JSON.parse(Buffer.from(o,"base64").toString("utf8"));}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 r=t;if(typeof r.kind!="string"||typeof r.value!="string")throw new Error(`Invalid ref format (payload must contain string kind/value): ${e}`);return {kind:r.kind,value:r.value}}function I(e){return `b64:${Buffer.from(JSON.stringify(e),"utf8").toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}`}function P(){return {read(e){if(!l.existsSync(e))return null;try{return l.readFileSync(e,"utf-8")}catch{return null}},write(e,n){l.mkdirSync(d.dirname(e),{recursive:true}),l.writeFileSync(e,n,"utf-8");}}}function x(e){if(e.kind==="fs-path")return P();throw new Error(`Unsupported storage kind: "${e.kind}". Supported kinds: fs-path`)}function y(e){return b(e).value}function _(e){let n=e.extra?.notifyChannel;return typeof n=="string"&&n.length>0?n:void 0}function O(e){if(!e.endsWith(".ts"))return {cmd:process.execPath,args:[e]};let n=d.dirname(e),o=[];for(let r=1;r<=5;r++){let s=d.join(n,...Array(r).fill(".."),"node_modules");o.push(d.join(s,"tsx","dist","cli.mjs")),o.push(d.join(s,".bin","tsx"));}let t=o.find(r=>l.existsSync(r));return t?{cmd:process.execPath,args:[t,e]}:{cmd:"npx",args:["tsx",e]}}function F(e,n){let{token:o,via:t}=e;if(t.howToRun==="local-node"||t.howToRun==="local-process"){let r=y(t.whatToRun),{cmd:s,args:p}=O(r),u=_(t),f=[...p,"source-data-fetched","--ref",I(n),"--token",o,...u?["--notify-channel",u]:[]],i=spawnSync(s,f,{encoding:"utf-8",windowsHide:true});if(i.status!==0)throw new Error(`reportComplete: board CLI exited ${i.status}: ${i.stderr?.trim()}`);return}if(t.howToRun==="http:post"){let r=y(t.whatToRun),s=JSON.stringify({status:"complete",ref:I(n),token:o});q(r,s);return}throw new Error(`reportComplete: unsupported via.howToRun "${t.howToRun}"`)}function j(e,n){let{token:o,via:t}=e;if(t.howToRun==="local-node"||t.howToRun==="local-process"){let r=y(t.whatToRun),{cmd:s,args:p}=O(r),u=_(t),f=[...p,"source-data-fetch-failure","--token",o,"--reason",n,...u?["--notify-channel",u]:[]],i=spawnSync(s,f,{encoding:"utf-8",windowsHide:true});if(i.status!==0)throw new Error(`reportFailed: board CLI exited ${i.status}: ${i.stderr?.trim()}`);return}if(t.howToRun==="http:post"){let r=y(t.whatToRun),s=JSON.stringify({status:"failed",reason:n,token:o});q(r,s);return}throw new Error(`reportFailed: unsupported via.howToRun "${t.howToRun}"`)}function q(e,n){let o=`
2
+ import*as l from'fs';import*as a from'path';import {execFileSync,spawnSync}from'child_process';import {createRequire}from'module';var U=createRequire(import.meta.url);function y(e){if(!e.startsWith("b64:"))throw new Error(`Invalid ref format (expected b64:<base64url(json)>): ${e}`);let r=e.slice(4),o=r.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-r.length%4)%4),t;try{t=JSON.parse(Buffer.from(o,"base64").toString("utf8"));}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 C(e){return `b64:${Buffer.from(JSON.stringify(e),"utf8").toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}`}function H(){return {read(e){if(!l.existsSync(e))return null;try{return l.readFileSync(e,"utf-8")}catch{return null}},write(e,r){l.mkdirSync(a.dirname(e),{recursive:true}),l.writeFileSync(e,r,"utf-8");}}}function x(e){if(e.kind==="fs-path")return H();throw new Error(`Unsupported storage kind: "${e.kind}". Supported kinds: fs-path`)}function b(e){let r=y(e);if(r.kind==="yaml-flow-cli"){let o=a.basename(r.value.trim());if(!o)throw new Error(`Invalid yaml-flow-cli ref: expected non-empty cli file name, got ${JSON.stringify(r.value)}`);let t=a.dirname(U.resolve("yaml-flow/package.json")),n=a.join(t,"cli","node",o);if(!l.existsSync(n))throw new Error(`Invalid yaml-flow-cli ref: could not find ${o} under ${a.join(t,"cli","node")}`);return n}return r.value}function _(e){let r=e.extra?.notifyChannel;return typeof r=="string"&&r.length>0?r:void 0}function j(e){if(!e.endsWith(".ts"))return {cmd:process.execPath,args:[e]};let r=a.dirname(e),o=[];for(let n=1;n<=5;n++){let s=a.join(r,...Array(n).fill(".."),"node_modules");o.push(a.join(s,"tsx","dist","cli.mjs")),o.push(a.join(s,".bin","tsx"));}let t=o.find(n=>l.existsSync(n));return t?{cmd:process.execPath,args:[t,e]}:{cmd:"npx",args:["tsx",e]}}function O(e,r){let{token:o,via:t}=e;if(t.howToRun==="local-node"||t.howToRun==="local-process"){let n=b(t.whatToRun),{cmd:s,args:p}=j(n),f=_(t),d=[...p,"source-data-fetched","--ref",C(r),"--token",o,...f?["--notify-channel",f]:[]],i=spawnSync(s,d,{encoding:"utf-8",windowsHide:true});if(i.status!==0)throw new Error(`reportComplete: board CLI exited ${i.status}: ${i.stderr?.trim()}`);return}if(t.howToRun==="http:post"){let n=b(t.whatToRun),s=JSON.stringify({status:"complete",ref:C(r),token:o});F(n,s);return}throw new Error(`reportComplete: unsupported via.howToRun "${t.howToRun}"`)}function q(e,r){let{token:o,via:t}=e;if(t.howToRun==="local-node"||t.howToRun==="local-process"){let n=b(t.whatToRun),{cmd:s,args:p}=j(n),f=_(t),d=[...p,"source-data-fetch-failure","--token",o,"--reason",r,...f?["--notify-channel",f]:[]],i=spawnSync(s,d,{encoding:"utf-8",windowsHide:true});if(i.status!==0)throw new Error(`reportFailed: board CLI exited ${i.status}: ${i.stderr?.trim()}`);return}if(t.howToRun==="http:post"){let n=b(t.whatToRun),s=JSON.stringify({status:"failed",reason:r,token:o});F(n,s);return}throw new Error(`reportFailed: unsupported via.howToRun "${t.howToRun}"`)}function F(e,r){let o=`
3
3
  const {request} = require(new URL('${e}').protocol === 'https:' ? 'https' : 'http');
4
- const h = ${JSON.stringify({"Content-Type":"application/json","Content-Length":Buffer.byteLength(n)})};
4
+ const h = ${JSON.stringify({"Content-Type":"application/json","Content-Length":Buffer.byteLength(r)})};
5
5
  const u = new URL('${e}');
6
6
  const req = request({hostname:u.hostname,port:u.port,path:u.pathname+u.search,method:'POST',headers:h});
7
7
  req.on('error', e => { process.stderr.write(e.message); process.exit(1); });
8
- req.write(${JSON.stringify(n)});
8
+ req.write(${JSON.stringify(r)});
9
9
  req.end();
10
- `,t=spawnSync(process.execPath,["-e",o],{encoding:"utf-8",windowsHide:true});if(t.status!==0)throw new Error(`http-post failed: ${t.stderr?.trim()}`)}function H(e){let n=[],o="",t=false,r=false;for(let s of e){if(s==="'"&&!r){t=!t;continue}if(s==='"'&&!t){r=!r;continue}s===" "&&!t&&!r?o&&(n.push(o),o=""):o+=s;}return o&&n.push(o),n}function W(e){if(process.platform!=="win32"||d.isAbsolute(e)||e.includes("/")||e.includes("\\"))return e;let n=process.env.PATH??"";for(let o of n.split(d.delimiter))for(let t of [".cmd",".bat"]){let r=d.join(o,e+t);if(l.existsSync(r))return r}return e}function z(e){let n=e.indexOf("--in-ref"),o=e.indexOf("--out-ref"),t=e.indexOf("--err-ref"),r=n!==-1?e[n+1]:void 0,s=o!==-1?e[o+1]:void 0,p=t!==-1?e[t+1]:void 0;(!r||!s)&&(console.error("[source-cli-task-executor] Usage: run-source-fetch --in-ref <b64-ref> --out-ref <b64-ref> [--err-ref <b64-ref>]"),process.exit(1));let u,f,i;try{u=b(r),f=b(s),p&&(i=b(p));}catch(c){console.error(`[source-cli-task-executor] invalid ref: ${c.message}`),process.exit(1);}let D=x(u),A=x(f),T=i?x(i):void 0;function h(c,C){if(T&&i)try{T.write(i.value,c);}catch{}if(console.error(`[source-cli-task-executor] ${c}`),C)try{j(C,c);}catch{}process.exit(1);}let $=D.read(u.value);$===null&&h(`Input not found: ${r}`);let w;try{w=JSON.parse($);}catch(c){h(`Cannot parse input envelope: ${c.message}`);}let g=w.source_def!=null?w.callback:void 0,a=w.source_def??w;(!a.cli||typeof a.cli!="string")&&h("source_def missing required field: cli (source-cli-task-executor only handles source.cli)",g);let K=typeof a.timeout=="number"?a.timeout:12e4,k=typeof a.boardDir=="string"&&a.boardDir?a.boardDir:void 0,V=k??process.cwd(),N=typeof a.bindTo=="string"?a.bindTo:"unknown",R=H(a.cli);R.length===0&&h("source_def.cli is empty",g);let J=W(R[0]),L=R.slice(1);console.log(`[source-cli-task-executor] ${N}: ${a.cli}`);let E;try{E=execFileSync(J,L,{shell:!1,encoding:"utf-8",timeout:K,cwd:V,env:{...process.env,...k?{BOARD_DIR:k}:{}},maxBuffer:50*1024*1024});}catch(c){h(`cli execution failed: ${c.message}`,g);}try{A.write(f.value,E.trim());}catch(c){h(`Cannot write output: ${c.message}`,g);}if(g)try{F(g,f);}catch(c){console.error(`[source-cli-task-executor] reportComplete failed: ${c.message}`),process.exit(1);}}var Q={version:"1.0",executor:"source-cli-task-executor",subcommands:["run-source-fetch","describe-capabilities"],sourceKinds:{cli:{description:"Execute a shell command (source_def.cli) synchronously and capture stdout as the source data.",inputSchema:{cli:{type:"string",required:true,description:"Command string to execute. Quoted arguments are supported. Runs via execFileSync (no shell)."},timeout:{type:"number",required:false,description:"Execution timeout in milliseconds (default: 120000)."},cwd:{type:"string",required:false,description:"Working directory for the command (default: process.cwd())."},boardDir:{type:"string",required:false,description:"Injected as BOARD_DIR environment variable."}},outputShape:"string \u2014 trimmed stdout of the command."}}},S=process.argv[2];S==="run-source-fetch"?z(process.argv.slice(3)):S==="describe-capabilities"?console.log(JSON.stringify(Q,null,2)):(console.warn(`[source-cli-task-executor] Unknown subcommand: ${S??"(none)"}`),process.exit(1));//# sourceMappingURL=source-cli-task-executor.js.map
10
+ `,t=spawnSync(process.execPath,["-e",o],{encoding:"utf-8",windowsHide:true});if(t.status!==0)throw new Error(`http-post failed: ${t.stderr?.trim()}`)}function z(e){let r=[],o="",t=false,n=false;for(let s of e){if(s==="'"&&!n){t=!t;continue}if(s==='"'&&!t){n=!n;continue}s===" "&&!t&&!n?o&&(r.push(o),o=""):o+=s;}return o&&r.push(o),r}function Q(e){if(process.platform!=="win32"||a.isAbsolute(e)||e.includes("/")||e.includes("\\"))return e;let r=process.env.PATH??"";for(let o of r.split(a.delimiter))for(let t of [".cmd",".bat"]){let n=a.join(o,e+t);if(l.existsSync(n))return n}return e}function G(e){let r=e.indexOf("--in-ref"),o=e.indexOf("--out-ref"),t=e.indexOf("--err-ref"),n=r!==-1?e[r+1]:void 0,s=o!==-1?e[o+1]:void 0,p=t!==-1?e[t+1]:void 0;(!n||!s)&&(console.error("[source-cli-task-executor] Usage: run-source-fetch --in-ref <b64-ref> --out-ref <b64-ref> [--err-ref <b64-ref>]"),process.exit(1));let f,d,i;try{f=y(n),d=y(s),p&&(i=y(p));}catch(c){console.error(`[source-cli-task-executor] invalid ref: ${c.message}`),process.exit(1);}let D=x(f),A=x(d),$=i?x(i):void 0;function h(c,I){if($&&i)try{$.write(i.value,c);}catch{}if(console.error(`[source-cli-task-executor] ${c}`),I)try{q(I,c);}catch{}process.exit(1);}let T=D.read(f.value);T===null&&h(`Input not found: ${n}`);let w;try{w=JSON.parse(T);}catch(c){h(`Cannot parse input envelope: ${c.message}`);}let g=w.source_def!=null?w.callback:void 0,u=w.source_def??w;(!u.cli||typeof u.cli!="string")&&h("source_def missing required field: cli (source-cli-task-executor only handles source.cli)",g);let K=typeof u.timeout=="number"?u.timeout:12e4,k=typeof u.boardDir=="string"&&u.boardDir?u.boardDir:void 0,N=k??process.cwd(),V=typeof u.bindTo=="string"?u.bindTo:"unknown",R=z(u.cli);R.length===0&&h("source_def.cli is empty",g);let J=Q(R[0]),L=R.slice(1);console.log(`[source-cli-task-executor] ${V}: ${u.cli}`);let E;try{E=execFileSync(J,L,{shell:!1,encoding:"utf-8",timeout:K,cwd:N,env:{...process.env,...k?{BOARD_DIR:k}:{}},maxBuffer:50*1024*1024});}catch(c){h(`cli execution failed: ${c.message}`,g);}try{A.write(d.value,E.trim());}catch(c){h(`Cannot write output: ${c.message}`,g);}if(g)try{O(g,d);}catch(c){console.error(`[source-cli-task-executor] reportComplete failed: ${c.message}`),process.exit(1);}}var M={version:"1.0",executor:"source-cli-task-executor",subcommands:["run-source-fetch","describe-capabilities"],sourceKinds:{cli:{description:"Execute a shell command (source_def.cli) synchronously and capture stdout as the source data.",inputSchema:{cli:{type:"string",required:true,description:"Command string to execute. Quoted arguments are supported. Runs via execFileSync (no shell)."},timeout:{type:"number",required:false,description:"Execution timeout in milliseconds (default: 120000)."},cwd:{type:"string",required:false,description:"Working directory for the command (default: process.cwd())."},boardDir:{type:"string",required:false,description:"Injected as BOARD_DIR environment variable."}},outputShape:"string \u2014 trimmed stdout of the command."}}},S=process.argv[2];S==="run-source-fetch"?G(process.argv.slice(3)):S==="describe-capabilities"?console.log(JSON.stringify(M,null,2)):(console.warn(`[source-cli-task-executor] Unknown subcommand: ${S??"(none)"}`),process.exit(1));//# sourceMappingURL=source-cli-task-executor.js.map
11
11
  //# sourceMappingURL=source-cli-task-executor.js.map
@@ -1,5 +1,5 @@
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:
1
+ import*as m from'fs';import {existsSync}from'fs';import*as R from'path';import {dirname,resolve}from'path';import'ajv-formats';import {createRequire}from'module';import {fileURLToPath}from'url';import {spawn,execFile,execFileSync}from'child_process';import*as vt from'os';import'net';import {randomUUID}from'crypto';import'proper-lockfile';function q(e,t,n,r){let o=e.steps[n];if(!o)throw new Error(`Step "${n}" not found in flow configuration`);if(r.result==="failure"&&o.retry){let i=t.retryCounts[n]??0;if(i<o.retry.max_attempts)return {newState:{...t,retryCounts:{...t.retryCounts,[n]:i+1},updatedAt:Date.now()},nextStep:n,isTerminal:false,isCircuitBroken:false,shouldRetry:true}}let s=o.failure_transitions?.[r.result]??o.transitions[r.result];if(!s)throw new Error(`No transition defined for result "${r.result}" in step "${n}"`);let a=!!e.terminal_states[s];return {newState:{...t,currentStep:s,stepHistory:[...t.stepHistory,n],retryCounts:{...t.retryCounts,[n]:0},updatedAt:Date.now()},nextStep:s,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 o=t.iterationCounts[n]??0;return o>=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]:o+1},updatedAt:Date.now()}}}function V(e,t,n){let r=e.steps[t];if(!r)throw new Error(`Step "${t}" not found`);if(r.expects_data){let o={};for(let s of r.expects_data)o[s]=n[s];return o}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 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 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 o=this.data.get(t);o[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 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[o,s]of Object.entries(n)){for(let[a,i]of Object.entries(s.transitions))if(!n[i]&&!r[i])throw new Error(`Step "${o}" transition "${a}" points to unknown step "${i}"`);if(s.failure_transitions){for(let[a,i]of Object.entries(s.failure_transitions))if(!n[i]&&!r[i])throw new Error(`Step "${o}" 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[o,s]of Object.entries(t))await this.store.setData(n,o,s);this.emit({type:"flow:start",runId:n,timestamp:r.startedAt,data:{initialData:t??{}}});try{return await this.executeLoop(n,r)}catch(o){let s=o instanceof Error?o:new Error(String(o));return this.emit({type:"flow:error",runId:n,timestamp:Date.now(),data:{error:s.message}}),this.options.onError?.(s),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:s}}}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,o=this.flow.settings.timeout_ms,s=n,a=0;for(;a<r;){if(this.aborted)return s={...s,status:"cancelled",updatedAt:Date.now()},await this.store.saveRunState(t,s),{runId:t,status:"cancelled",data:await this.store.getAllData(t),finalStep:s.currentStep,stepHistory:s.stepHistory,durationMs:Date.now()-s.startedAt};if(o&&Date.now()-s.startedAt>o)return s={...s,status:"completed",updatedAt:Date.now()},await this.store.saveRunState(t,s),{runId:t,status:"timeout",intent:"timeout",data:await this.store.getAllData(t),finalStep:s.currentStep,stepHistory:s.stepHistory,durationMs:Date.now()-s.startedAt};let i=s.currentStep,u=this.flow.terminal_states[i];if(u){s={...s,status:"completed",updatedAt:Date.now()},await this.store.saveRunState(t,s);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:s.stepHistory,durationMs:Date.now()-s.startedAt};return this.emit({type:"flow:complete",runId:t,timestamp:Date.now(),data:{...g}}),this.options.onComplete?.(g),g}let c=U(this.flow,s,i);if(c.broken){s=c.newState,await this.store.saveRunState(t,s),a++;continue}s=c.newState;let d=await this.store.getAllData(t),l=V(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=q(this.flow,s,i,h);if(s=w.newState,w.shouldRetry){await this.store.saveRunState(t,s);let p=this.flow.steps[i];if(p.retry?.delay_ms){let g=s.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,s),this.emit({type:"transition",runId:t,timestamp:Date.now(),data:{from:i,to:s.currentStep,result:h.result}}),this.options.onTransition?.(i,s.currentStep),a++;}return s={...s,status:"completed",updatedAt:Date.now()},await this.store.saveRunState(t,s),{runId:t,status:"max_iterations",intent:"max_iterations",data:await this.store.getAllData(t),finalStep:s.currentStep,stepHistory:s.stepHistory,durationMs:Date.now()-s.startedAt}}};function $(e,t,n){return new I(e,t,n)}async function G(e){return (await import('yaml')).parse(e)}async function Ot(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 It(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[o,s]of Object.entries(r)){if(!s||typeof s!="object"){t.push(`Step "${o}" must be an object`);continue}let a=s;(!a.transitions||typeof a.transitions!="object")&&t.push(`Step "${o}" must have a "transitions" object`),a.failure_transitions!==void 0&&typeof a.failure_transitions!="object"&&t.push(`Step "${o}" 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[o,s]of Object.entries(r)){if(!s||typeof s!="object"){t.push(`Terminal state "${o}" must be an object`);continue}typeof s.return_intent!="string"&&t.push(`Terminal state "${o}" 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 Ot(e):e.includes("{")?t=JSON.parse(e):t=await It(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 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
3
+ - `)}`);return t}function Y(e){return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function rt(e){return atob(e.replace(/-/g,"+").replace(/_/g,"/"))}var C=class{constructor(t){this.kv=t;}kv;stateKey(t){return `state_${Y(t)}`}dataPrefix(t){return `data_${Y(t)}_`}dataKey(t,n){return `${this.dataPrefix(t)}${Y(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 o of this.kv.listKeys(n))r[rt(o.slice(n.length))]=this.kv.read(o);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 st=dirname(fileURLToPath(import.meta.url)),Bt=createRequire(import.meta.url);function Nt(){let e=resolve(st,"./jsonata-sync.cjs");return existsSync(e)?e:resolve(st,"../card-compute/jsonata-sync.cjs")}var P=Bt(Nt());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 o=n.data&&typeof n.data=="object"&&!Array.isArray(n.data)?{...n.data}:{},s=typeof n.error=="string"?n.error:void 0;return s&&!("error"in o)&&(o.error=s),{result:r,data:o,...s?{error:s}:{}}}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 o=await e(n,r),s=it(o,r?.stepName??"unknown");return {result:s.result,data:at(s.data,t),...s.error?{error:s.error}:{}}}}function ct(e,t,n){if(!t||t.length===0)return null;for(let r of t)try{if(!P(r).evaluate(e))return {result:"failure",data:{error:`[${n}] input validation failed: ${r}`}}}catch(o){let s=o instanceof Error?o.message:String(o);return {result:"failure",data:{error:`[${n}] input validation error on "${r}": ${s}`}}}return null}function Q(e,t,n){return !t||t.length===0?e:async(r,o)=>{let s=ct(r,t,n);return s||e(r,o)}}var lt=dirname(fileURLToPath(import.meta.url)),Vt=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 v=Vt(zt());function pt(e,t,n){if(!e||typeof e!="object")return {};let r={};if(Array.isArray(e.cmdTemplate)){let o=[];for(let s of e.cmdTemplate)try{o.push(String(v(s).evaluate(t)));}catch(a){let i=a instanceof Error?a.message:String(a);throw new Error(`[${n}] argsMassaging.cmdTemplate failed on "${s}": ${i}`)}r.cmdArgs=o;}if(typeof e.stdinTemplate=="string")try{r.stdin=v(e.stdinTemplate).evaluate(t);}catch(o){let s=o instanceof Error?o.message:String(o);throw new Error(`[${n}] argsMassaging.stdinTemplate failed: ${s}`)}if(typeof e.urlTemplate=="string")try{r.url=String(v(e.urlTemplate).evaluate(t));}catch(o){let s=o instanceof Error?o.message:String(o);throw new Error(`[${n}] argsMassaging.urlTemplate failed: ${s}`)}if(typeof e.headerTemplate=="string")try{let o=v(e.headerTemplate).evaluate(t);if(typeof o!="object"||o===null)throw new Error(`headerTemplate must produce an object, got: ${JSON.stringify(o)}`);r.headers=o;}catch(o){let s=o instanceof Error?o.message:String(o);throw new Error(`[${n}] argsMassaging.headerTemplate failed: ${s}`)}if(typeof e.bodyTemplate=="string")try{r.body=v(e.bodyTemplate).evaluate(t);}catch(o){let s=o instanceof Error?o.message:String(o);throw new Error(`[${n}] argsMassaging.bodyTemplate failed: ${s}`)}return r}function dt(e,t,n){if(!e||typeof e!="object")return t;let r={output:t},o=t.result,s=t.data,a=t.error;if(typeof e.resultExpr=="string")try{let i=v(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)})`);o=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=v(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)})`);s=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=v(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:o,data:s,error:a}:{result:o,data:s}}var _="b64:";function Wt(e){let t=new TextEncoder().encode(e),n=globalThis.Buffer,r;if(n)r=n.from(t).toString("base64");else if(typeof btoa=="function"){let o="";for(let s of t)o+=String.fromCharCode(s);r=btoa(o);}else throw new Error("No base64 encoder available in this runtime");return r.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function Gt(e){let t=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-e.length%4)%4),n=globalThis.Buffer;if(n)return n.from(t,"base64").toString("utf8");if(typeof atob=="function"){let r=atob(t),o=new Uint8Array(r.length);for(let s=0;s<r.length;s+=1)o[s]=r.charCodeAt(s);return new TextDecoder().decode(o)}throw new Error("No base64 decoder available in this runtime")}function J(e){return `${_}${Wt(JSON.stringify(e))}`}function ft(e){if(!e.startsWith(_))throw new Error(`Invalid ref format (expected ${_}<base64url(json)>): ${e}`);let t;try{t=JSON.parse(Gt(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 gt(e){return !!e&&typeof e=="object"&&e.type==="compute-jsonata"&&Array.isArray(e.expr)&&e.expr.length>0}function mt(e){if(!e||typeof e!="object")return false;let t=e;if(t.type!=="ref"||typeof t.howToRun!="string")return false;if(typeof t.whatToRun=="string")return true;if(t.whatToRun&&typeof t.whatToRun=="object"){let n=t.whatToRun;return typeof n.kind=="string"&&typeof n.value=="string"}return false}function Yt(e){if(typeof e=="string"){let t=e.indexOf("=");if(t<1)throw new Error(`[step-machine-public] Invalid compute expression (missing "="): "${e}"`);return {bindTo:e.slice(0,t).trim(),expr:e.slice(t+1).trim()}}if(e&&typeof e=="object"&&typeof e.bindTo=="string"&&typeof e.expr=="string")return e;throw new Error(`[step-machine-public] Invalid compute step: ${JSON.stringify(e)}`)}function Xt(e,t,n){let r=t.split("."),o=e;for(let s=0;s<r.length-1;s++){let a=r[s];(o[a]==null||typeof o[a]!="object")&&(o[a]={}),o=o[a];}o[r[r.length-1]]=n;}function ht(e,t,n){let r=e.expr.map(Yt);return async o=>{let s=o&&typeof o=="object"&&!Array.isArray(o)?{...o}:{},a={},i={expects_data:s,data:a,...n?{config:n}:{}},u,c;for(let d of r)try{let l=P(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 yt(e,t,n,r){let{type:o,...s}=e,a={...s,whatToRun:typeof s.whatToRun=="object"?J(s.whatToRun):s.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 wt(){return async e=>({result:"success",data:e&&typeof e=="object"&&!Array.isArray(e)?e:{}})}function Qt(e,t,n){return async(r,o)=>{let s=r?.[t.items];if(!Array.isArray(s))return {result:"failure",data:{},error:`[${n}] forEach: "${t.items}" is not an array (got ${typeof s})`};let a=s,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 M={...c,[t.as]:a[x]};e(M,o).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 St(e,t,n){let r=Array.isArray(t?.produces_data)?t?.produces_data:void 0,o=Array.isArray(t?.input_validations)?t?.input_validations:void 0,s=t?.config??void 0,a=t?.handler,i;return gt(a)?i=ht(a,e,s):mt(a)?i=yt(a,e,n.invoke,s):i=wt(),t?.forEach&&(i=Qt(i,t.forEach,e)),Q(X(i,r),o,e)}function D(e,t){let n={};for(let[r,o]of Object.entries(e.steps??{}))n[r]=St(r,o,t);return n}function ne(e){if(typeof e=="object"&&e!==null){let{command:n,args:r=[],...o}=e,s=xt(n,r);return {...o,command:s.command,args:s.args}}let t=kt(e);if(t.length===0)throw new Error(`Empty command spec: ${JSON.stringify(e)}`);return xt(t[0],t.slice(1))}function xt(e,t){return /^(node|node\.exe)$/i.test(e)?{command:process.execPath,args:t}:/\.m?js$/i.test(e)?{command:process.execPath,args:[e,...t]}:{command:e,args:t}}function kt(e){let t=[],n="",r=null;for(let o of e.trim()){if(r){o===r?r=null:n+=o;continue}if(o==='"'||o==="'"){r=o;continue}if(/\s/.test(o)){n&&(t.push(n),n="");continue}n+=o;}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 bt(e,t){let{command:n,args:r=[],cwd:o,env:s,timeoutMs:a}=e;return execFileSync(n,r,{shell:Z(n),timeout:a,encoding:t?.encoding??"utf-8",cwd:o,windowsHide:true,env:s?{...process.env,...s}:void 0,input:t?.input})}function re(e,t){let{command:n,args:r=[],cwd:o,env:s,timeoutMs:a=3e4}=e;execFile(n,r,{shell:Z(n),encoding:"utf8",windowsHide:true,timeout:a,maxBuffer:10*1024*1024,cwd:o,env:s?{...process.env,...s}:void 0},(i,u,c)=>t(i??null,u,c));}R.join(vt.tmpdir(),".board-live-cards-git-bash-cache.json");function Et(e){let{command:t,args:n=[]}=e;if(process.platform==="win32"){spawn(t,n,{detached:true,stdio:"ignore",windowsHide:true,shell:Z(t)}).unref();return}spawn(t,n,{detached:true,stdio:"ignore"}).unref();}function At(e,t,n){let r=R.join(e,"board-live-cards-cli.js");if(m.existsSync(r))return {cmd:process.execPath,args:[r,t,...n]};let o=R.join(e,"board-live-cards-cli.ts"),s=R.join(e,"..","..","node_modules","tsx","dist","cli.mjs"),a=R.join(e,"..","..","node_modules",".bin","tsx"),i=m.existsSync(s)?s:a;return m.existsSync(o)&&m.existsSync(i)?{cmd:process.execPath,args:[i,o,t,...n]}:{cmd:process.platform==="win32"?"npx.cmd":"npx",args:["tsx",o,t,...n]}}function jt(){return {executeSync(e,t,n){return bt({command:e,args:t,cwd:n?.cwd,timeoutMs:n?.timeout,env:n?.env},{encoding:n?.encoding,input:n?.input})},executeAsync(e,t,n){re({command:e,args:t},n);},resolveInvocation(e,t){let n=ne({command:e,args:t});return {cmd:n.command,args:n.args??[]}},splitCommand:kt,spawnDetached(e,t){Et({command:e,args:t});}}}var se=createRequire(import.meta.url);function ie(e){return typeof e=="object"?e:ft(e)}function ae(e){let t=R.basename(String(e||"").trim());if(!t)throw new Error(`resolveYamlFlowCliPath: expected non-empty cli file name, got ${JSON.stringify(e)}`);let n=R.dirname(se.resolve("yaml-flow/package.json")),r=R.join(n,"cli","node",t);if(!m.existsSync(r))throw new Error(`resolveYamlFlowCliPath: could not find ${t} under ${R.join(n,"cli","node")}`);return r}function K(e){let t=ie(e);return t.kind==="yaml-flow-cli"?ae(t.value):t.value}function ce(e,t){let n=K(e);switch(n){case "source-cli-task-executor":{let r=R.join(t,"source-cli-task-executor.js");if(m.existsSync(r))return {command:process.execPath,args:[r]};let o=R.join(t,"source-cli-task-executor.ts"),s=R.join(t,"..","..","node_modules","tsx","dist","cli.mjs"),a=R.join(t,"..","..","node_modules",".bin","tsx"),i=m.existsSync(s)?s:a;return m.existsSync(o)&&m.existsSync(i)?{command:process.execPath,args:[i,o]}:{command:process.execPath,args:[r]}}case "board-live-cards":{let{cmd:r,args:o}=At(t,"_",[]);return {command:r,args:o}}default:throw new Error(`resolveBuiltIn: unknown built-in name "${n}". Supported: source-cli-task-executor, board-live-cards`)}}function ue(e,t){if(e.howToRun==="built-in"){let{command:r,args:o}=ce(e.whatToRun,t);return {command:r,baseArgs:o}}let n=(typeof e.whatToRun=="object",K(e.whatToRun));switch(e.howToRun){case "local-node":return {command:process.execPath,baseArgs:[n]};case "local-python":return {command:process.platform==="win32"?"python":"python3",baseArgs:[n]};case "local-process":return {command:n,baseArgs:[]};default:throw new Error(`resolveBaseInvocation: howToRun "${e.howToRun}" is not a local transport`)}}function le(e,t){return ue(e,t)}function pe(e){let t=e.trim();if(!t)throw new Error("empty stdout");try{return JSON.parse(t)}catch{let n=t.split(/\r?\n/).filter(Boolean),r=n[n.length-1];return JSON.parse(r)}}function de(e,t){return {...t,whatToRun:K(e.whatToRun),...e.extra?{extra:e.extra}:{}}}function fe(e,t,n="invokeExecutionRef"){return pt(e,t,n)}function ge(e){return e&&typeof e=="object"&&!Array.isArray(e)&&typeof e.result=="string"&&e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e:{result:"success",data:e&&typeof e=="object"&&!Array.isArray(e)?e:{stdout:e}}}function N(e){return {result:"failure",data:{error:e}}}function B(e,t,n){let r=n?.label??"invokeExecutionRefSync",o=n?.cliDir??n?.cwd??process.cwd(),s;try{s=fe(e.argsMassaging,de(e,t),r);}catch(l){let f=l instanceof Error?l.message:String(l);return N(f)}let a;try{a=le(e,o);}catch(l){let f=l instanceof Error?l.message:String(l);return N(`[${r}] ref resolution failed: ${f}`)}let i=[...a.baseArgs,...s.cmdArgs??[]],u=JSON.stringify(s.stdin??t),c=jt(),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 ge(pe(d))}catch{return {result:"success",data:{stdout:d.trim()}}}}var me={"local-node":B,"local-python":B,"local-process":B,"built-in":B};function he(e,t,n){let r=n?.syncTransports?.[e.howToRun]??me[e.howToRun];return r?r(e,t,n):N(`[${n?.label??"invokeExecutionRefSync"}] unsupported sync howToRun: ${e.howToRun}`)}function Ct(e,t,n){return he(e,t,n)}function we(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(o){let s=o.code;if((s==="EPERM"||s==="EBUSY")&&r<n.length){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,n[r]);continue}throw o}}function Tt(e){function t(r){return R.join(e,...r.split("/"))+".json"}function n(r,o,s,a){if(m.existsSync(r))for(let i of m.readdirSync(r,{withFileTypes:true})){let u=o?`${o}/${i.name}`:i.name;if(i.isDirectory()){n(R.join(r,i.name),u,s,a);continue}if(!i.isFile()||!i.name.endsWith(".json"))continue;let c=u.replace(/\.json$/,"");(!s||c.startsWith(s))&&a.push(c);}}return {read(r){let o=t(r);if(!m.existsSync(o))return null;try{return JSON.parse(m.readFileSync(o,"utf-8"))}catch{return null}},write(r,o){let s=t(r),a=`${s}.${process.pid}.${randomUUID()}.tmp`;m.mkdirSync(R.dirname(s),{recursive:true}),m.writeFileSync(a,JSON.stringify(o,null,2),"utf-8"),we(a,s);},delete(r){let o=t(r);try{m.existsSync(o)&&m.unlinkSync(o);}catch{}},listKeys(r){let o=[];return n(e,"",r,o),o.sort()}}}var L=class extends Error{constructor(n,r){super(r);this.code=n;this.name="CliExitError";}code},Se=".pause";async function nr(e){let t=Re(e);if(t.help||e.length===0)throw Ce(),new L(e.length===0?1:0);let{flowArg:n,dataArg:r,storeArg:o,storeDirArg:s,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=xe(o,s);if(u){await be(c);return}if(i){await ve(c);return}if(!n)throw new Error("[step-machine-cli] Flow path is required for run/resume operations.");let d=Pt(n),l=R.dirname(d),f=Ee(r),{store:h}=c,w=await H(d),p=je(w,l);Ft(c);let g=new AbortController,x=false,M=$(w,p,{store:h,signal:g.signal,onStep:()=>{!x&&et(c)&&(x=true,g.abort());}}),S;if(a){if(S=await $t(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 $t(c));let y=S?await M.resume(S):await M.run(f);if(x&&y.status==="cancelled"){let O=await ke(h,y.runId);Ft(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 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 Re(e){let t=new Set(["--initial-data","--store","--store-dir"]),n={},r=[],o=false,s=false,a=false,i=false;for(let u=0;u<e.length;u++){let c=e[u];if(c==="-h"||c==="--help"){o=true;continue}if(c==="--resume"){s=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([s,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:o,flowArg:r[0],dataArg:n["--initial-data"],storeArg:String(n["--store"]??"memory").toLowerCase(),storeDirArg:n["--store-dir"],resumeRequested:s,pauseRequested:a,statusRequested:i}}function Pt(e){return R.isAbsolute(e)?e:R.resolve(process.cwd(),e)}function xe(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=Pt(t);return {storeType:e,storeDir:n,pauseFilePath:R.join(n,Se),store:new C(Tt(n))}}async function tt(e){if(!e.listRuns)return [];let t=await e.listRuns(),n=[];for(let r of t){let o=await e.loadRunState(r);o&&n.push(o);}return n.sort((r,o)=>(o.updatedAt??o.startedAt??0)-(r.updatedAt??r.startedAt??0)),n}function et(e){return e.storeType!=="file"||!e.pauseFilePath?false:m.existsSync(e.pauseFilePath)}function Ft(e){et(e)&&m.unlinkSync(e.pauseFilePath);}async function ve(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 $t(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 ke(e,t){let n=await e.loadRunState(t);if(!n)return null;let r={...n,status:"paused",pausedAt:Date.now(),updatedAt:Date.now()};return await e.saveRunState(t,r),r}async function be(e){if(e.storeType!=="file")throw new Error("[step-machine-cli] --status requires --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 Ee(e){if(e)try{let t=JSON.parse(e);if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Initial data must be a JSON object.");return t}catch(t){let n=t instanceof Error?t.message:String(t);throw new Error(`[step-machine-cli] Invalid --initial-data value: ${n}`)}}function Ae(e){if(!e||typeof e!="object")return e;let t=e;if(typeof t.whatToRun!="string"||!t.whatToRun.startsWith("b64:"))return e;try{let n=t.whatToRun.slice(4),r=n+"=".repeat((4-n.length%4)%4),o=Buffer.from(r.replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8"),s=JSON.parse(o);return !s||typeof s!="object"||typeof s.value!="string"?e:{...t,whatToRun:s}}catch{return e}}function je(e,t){return D(e,{invoke:(r,o)=>Ct(Ae(r),o,{cliDir:t,cwd:t})})}function Ce(){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{L as CliExitError,nr as cli};//# sourceMappingURL=step-machine-cli.js.map
5
5
  //# sourceMappingURL=step-machine-cli.js.map
@@ -1,110 +1,5 @@
1
- import { E as ExecutionRef } from './execution-interface-ftO1W7Po.js';
2
- import { L as LiveCard, a as BoardStatusObject, J as JournalStorageAdapter, O as OutputStoreEvent } from './board-live-cards-lib-Iq_XAC09.js';
3
-
4
- /**
5
- * storage-interface.ts
6
- *
7
- * Three minimal storage primitives that together cover all persistence needs
8
- * of the board-live-cards system. Any backend (Node fs, CosmosDB, Azure Blob,
9
- * browser localStorage, in-memory test double) implements these three interfaces.
10
- *
11
- * The pure-logic stores in board-live-cards-all-stores.ts depend only on these
12
- * interfaces — never on Node built-ins.
13
- *
14
- * Blob — raw string content at a logical, backend-neutral key
15
- * Journal — append-only log with cursor-based reads
16
- * KV — key-value store with list/delete
17
- *
18
- * Mapping to existing storage adapters:
19
- *
20
- * CardStorageAdapter
21
- * inventory (cardId → { blobRef, checksum, fileMetadata? }) → KV
22
- * card JSON files → Blob
23
- * source output files → Blob
24
- *
25
- * JournalStorageAdapter → Journal (board-journal.jsonl)
26
- *
27
- * ExecutionRequestStore → KV (keyed by journalId, via createFsKvStorage)
28
- *
29
- * StateSnapshotStorageAdapter
30
- * board-graph.json (packed single JSON, written atomically) → Blob
31
- * per-card sidecars (cards/<id>/runtime, fetched-sources-manifest) → KV
32
- */
33
- interface BlobStat {
34
- key: string;
35
- size: number;
36
- updatedAt?: string;
37
- contentType?: string;
38
- }
39
- interface BlobStorage {
40
- /** Returns raw content string, or null if the blob does not exist. */
41
- read(key: string): string | null;
42
- /** Write content at key. Implementations should be atomic (write-rename). */
43
- write(key: string, content: string): void;
44
- /** Returns true if a blob exists at key. */
45
- exists(key: string): boolean;
46
- /** Delete the blob at key. No-op if it does not exist. */
47
- remove(key: string): void;
48
- /** Optional binary read for file-like artifacts. */
49
- readBytes?(key: string): Uint8Array | null;
50
- /** Optional binary write for file-like artifacts. */
51
- writeBytes?(key: string, content: Uint8Array): void;
52
- /** List all keys that start with the given prefix. */
53
- listKeys(prefix?: string): string[];
54
- /** Optional metadata lookup. */
55
- stat?(key: string): BlobStat | null;
56
- }
57
- interface KindValueRef {
58
- readonly kind: string;
59
- readonly value: string;
60
- }
61
- /** Serialize a KindValueRef to the wire format: b64:<base64url(json)> */
62
- declare function serializeRef(ref: KindValueRef): string;
63
- /** Parse a wire-format ref string (b64:<base64url(json)>) into a KindValueRef. */
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
- }
87
- interface KVStorage {
88
- /** Returns the stored value, or null if the key does not exist. */
89
- read(key: string): unknown | null;
90
- /** Write value at key. Overwrites any existing value. */
91
- write(key: string, value: unknown): void;
92
- /** Delete the key. No-op if it does not exist. */
93
- delete(key: string): void;
94
- /**
95
- * List all keys, optionally filtered to those starting with prefix.
96
- * Order is implementation-defined.
97
- */
98
- listKeys(prefix?: string): string[];
99
- }
100
- interface AtomicRelayLock {
101
- /**
102
- * Attempt to acquire the lock without blocking.
103
- * Returns a `release` function if successful, or `null` if the lock is
104
- * already held by another actor (relay: that actor will complete the work).
105
- */
106
- tryAcquire(): (() => void) | null;
107
- }
1
+ import { b as KVStorage, B as BlobStorage, c as AtomicRelayLock, E as ExecutionRef, K as KindValueRef, J as JournalStorage } from './execution-interface-CrG5gzAx.js';
2
+ import { L as LiveCard, B as BoardStatusObject, J as JournalStorageAdapter, O as OutputStoreEvent } from './board-live-cards-lib-tjYsPt5U.js';
108
3
 
109
4
  /**
110
5
  * board-live-cards-public.ts
@@ -198,7 +93,7 @@ interface BoardPlatformAdapter {
198
93
  /**
199
94
  * Self-identity ExecutionRef — how to invoke THIS board instance.
200
95
  * Embedded in source callback tokens so executors know where to report back.
201
- * Node/FS: { howToRun: 'local-node', whatToRun: 'b64:<base64url({"kind":"fs-path","value":"/path/to/cli.js"})>' }
96
+ * Node/FS: { howToRun: 'local-node', whatToRun: 'b64:<base64url({"kind":"yaml-flow-cli","value":"board-live-cards-cli.js"})>' }
202
97
  * Azure Fn: { howToRun: 'http:post', whatToRun: 'b64:<base64url({"kind":"http-url","value":"https://…/api/board"})>' }
203
98
  */
204
99
  selfRef: ExecutionRef;
@@ -464,4 +359,4 @@ interface DescribeEnvelope {
464
359
  supports?: string[];
465
360
  }
466
361
 
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 };
362
+ export { type BoardPlatformAdapter as B, type ChatStorage as C, type DescribeEnvelope as D, type InvocationAdapter as I, type NotificationTransport as N, type CommandInput as a, type CommandResult as b, type BoardNonCorePlatformAdapter as c, type BoardLiveCardsNonCorePublic as d, type BoardLiveCardsPublic as e, type ChatConfig as f, type ChatRecord as g, createBoardLiveCardsNonCorePublic as h, createBoardLiveCardsPublic as i, createChatStorage as j, createInMemoryChatStorage as k };
@@ -19,8 +19,8 @@
19
19
  <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
20
20
  <script src="https://cdn.jsdelivr.net/npm/dompurify/dist/purify.min.js"></script>
21
21
  <script src="https://cdn.jsdelivr.net/npm/leader-line/leader-line.min.js"></script>
22
- <script src="https://cdn.jsdelivr.net/npm/yaml-flow@8.2.4/browser/live-cards.js"></script>
23
- <script src="https://cdn.jsdelivr.net/npm/yaml-flow@8.2.4/browser/board-livecards-client.js"></script>
22
+ <script src="https://cdn.jsdelivr.net/npm/yaml-flow@8.3.0/browser/live-cards.js"></script>
23
+ <script src="https://cdn.jsdelivr.net/npm/yaml-flow@8.3.0/browser/board-livecards-client.js"></script>
24
24
  </head>
25
25
  <body class="bg-light">
26
26
  <div class="container-fluid py-3">
@@ -77,7 +77,7 @@
77
77
  }
78
78
  let currentMode = 'canvas';
79
79
  let bootstrapCompleted = false;
80
- let activeBoardId = 'default';
80
+ let activeBoardId = 'live';
81
81
  let runtimeClient = null;
82
82
 
83
83
  function boardPaths(boardId) {