yaml-flow 8.2.5 → 8.4.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 (93) 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 +6 -4
  4. package/browser/live-cards.js +19 -25
  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/board-live-cards-browser-adapter.js +3 -2
  8. package/cli/browser-api/card-store-browser-api.d.ts +1 -1
  9. package/cli/browser-api/card-store-browser-api.js +1 -1
  10. package/cli/{execution-interface-ftO1W7Po.d.ts → execution-interface-DCFBy4L8.d.ts} +151 -2
  11. package/cli/node/artifacts-store-cli.js +5 -5
  12. package/cli/node/batch-runner-cli.d.ts +3 -0
  13. package/cli/node/batch-runner-cli.js +2 -1
  14. package/cli/node/board-live-cards-cli.js +14 -8
  15. package/cli/node/card-store-cli.js +6 -6
  16. package/cli/node/chat-store-cli.d.ts +23 -0
  17. package/cli/node/chat-store-cli.js +8 -0
  18. package/cli/node/execution-adapter.d.ts +4 -2
  19. package/cli/node/execution-adapter.js +2 -2
  20. package/cli/node/fs-board-adapter.d.ts +75 -75
  21. package/cli/node/fs-board-adapter.js +14 -10
  22. package/cli/node/source-cli-task-executor.js +4 -4
  23. package/cli/node/step-machine-cli.js +3 -3
  24. package/cli/{types--rXGWbSR.d.ts → types-Dc2VRMUw.d.ts} +27 -124
  25. package/examples/board/demo-shell-with-server.html +3 -196
  26. package/examples/board/doc.html +465 -0
  27. package/examples/board/server/board-server.js +30 -82
  28. package/examples/board/server/board-worker/source_def_flows.json +2 -2
  29. package/examples/board/server/chat-flow/copilot-chat/assistant.js +44 -185
  30. package/examples/board/server/chat-flow/copilot-chat/copilot_wrapper.bat +157 -0
  31. package/examples/board/server/chat-flow/copilot-chat/copilot_wrapper_helper.ps1 +190 -0
  32. package/examples/board/server/chat-flow/flow-steps.json +122 -56
  33. package/examples/board/test/server-http-test.js +252 -220
  34. package/examples/board-local/demo-shell-localstorage.html +3 -3
  35. package/lib/{artifacts-store-lib-public-GD4H-fFp.d.ts → artifacts-store-lib-454TAuov.d.ts} +2 -32
  36. package/lib/{artifacts-store-lib-public-C5UL5tyG.d.cts → artifacts-store-lib-zsGFbBV8.d.cts} +2 -32
  37. package/lib/artifacts-store-public.d.cts +34 -3
  38. package/lib/artifacts-store-public.d.ts +34 -3
  39. package/lib/board-live-cards-node.cjs +14 -10
  40. package/lib/board-live-cards-node.d.cts +42 -21
  41. package/lib/board-live-cards-node.d.ts +42 -21
  42. package/lib/board-live-cards-node.js +14 -10
  43. package/lib/{board-live-cards-public-BLXbcBNk.d.cts → board-live-cards-public-BM6jCEIa.d.cts} +25 -5
  44. package/lib/{board-live-cards-public-BZaNb2mi.d.ts → board-live-cards-public-Bz07XKRK.d.ts} +25 -5
  45. package/lib/board-live-cards-public.cjs +2 -2
  46. package/lib/board-live-cards-public.d.cts +2 -2
  47. package/lib/board-live-cards-public.d.ts +2 -2
  48. package/lib/board-live-cards-public.js +2 -2
  49. package/lib/board-live-cards-server-runtime.cjs +4 -4
  50. package/lib/board-live-cards-server-runtime.d.cts +5 -3
  51. package/lib/board-live-cards-server-runtime.d.ts +5 -3
  52. package/lib/board-live-cards-server-runtime.js +4 -4
  53. package/lib/board-worker-adapter.cjs +2 -2
  54. package/lib/board-worker-adapter.js +2 -2
  55. package/lib/card-store-public.d.cts +2 -2
  56. package/lib/card-store-public.d.ts +2 -2
  57. package/lib/chat-storage-lib-DGaKrjVe.d.ts +53 -0
  58. package/lib/chat-storage-lib-OX0Q_Ttf.d.cts +53 -0
  59. package/lib/chat-store-public.cjs +2 -0
  60. package/lib/chat-store-public.d.cts +128 -0
  61. package/lib/chat-store-public.d.ts +128 -0
  62. package/lib/chat-store-public.js +2 -0
  63. package/lib/execution-refs.cjs +1 -1
  64. package/lib/execution-refs.d.cts +10 -1
  65. package/lib/execution-refs.d.ts +10 -1
  66. package/lib/execution-refs.js +1 -1
  67. package/lib/index.d.cts +1 -1
  68. package/lib/index.d.ts +1 -1
  69. package/lib/server-runtime/index.cjs +4 -4
  70. package/lib/server-runtime/index.d.cts +6 -4
  71. package/lib/server-runtime/index.d.ts +6 -4
  72. package/lib/server-runtime/index.js +4 -4
  73. package/lib/step-machine-public/index.cjs +3 -3
  74. package/lib/step-machine-public/index.d.cts +1 -1
  75. package/lib/step-machine-public/index.d.ts +1 -1
  76. package/lib/step-machine-public/index.js +3 -3
  77. package/lib/{storage-interface-B6ecOulj.d.ts → storage-interface-B-7pDHwD.d.cts} +36 -1
  78. package/lib/{storage-interface-B6ecOulj.d.cts → storage-interface-B-7pDHwD.d.ts} +36 -1
  79. package/lib/stores/index.d.cts +1 -1
  80. package/lib/stores/index.d.ts +1 -1
  81. package/lib/stores/kv.d.cts +1 -1
  82. package/lib/stores/kv.d.ts +1 -1
  83. package/lib/{types-D-xVWPdY.d.ts → types-Cn0b8G-i.d.ts} +16 -65
  84. package/lib/{types-Bztd1KoK.d.cts → types-Dszjwfud.d.cts} +16 -65
  85. package/package.json +8 -2
  86. package/examples/board/.board-ws/cards/store/_index.json +0 -17
  87. package/examples/board/.board-ws/cards/store/card-market-prices.json +0 -80
  88. package/examples/board/.board-ws/cards/store/card-portfolio-value.json +0 -90
  89. package/examples/board/.board-ws/cards/store/card-portfolio.json +0 -78
  90. package/examples/board/server/chat-flow/chat-clear-processing.js +0 -41
  91. package/examples/board/server/chat-flow/chat-open-turn.js +0 -144
  92. package/examples/board/server/chat-flow/chat-write-assistant.js +0 -44
  93. 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 x 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 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 V(e,t,n){let r=e.steps[n];if(!r?.circuit_breaker)return {broken:false,newState:{...t,iterationCounts:{...t.iterationCounts,[n]:(t.iterationCounts[n]??0)+1},updatedAt:Date.now()}};let s=t.iterationCounts[n]??0;return s>=r.circuit_breaker.max_iterations?{broken:true,redirectStep:r.circuit_breaker.on_open,newState:{...t,currentStep:r.circuit_breaker.on_open,updatedAt:Date.now()}}:{broken:false,newState:{...t,iterationCounts:{...t.iterationCounts,[n]:s+1},updatedAt:Date.now()}}}function q(e,t,n){let r=e.steps[t];if(!r)throw new Error(`Step "${t}" not found`);if(r.expects_data){let s={};for(let o of r.expects_data)s[o]=n[o];return s}return {...n}}function z(e,t){if(e===false||e===void 0)return {};if(typeof e=="string")return {[e]:t[e]};if(Array.isArray(e)){let n={};for(let r of e)n[r]=t[r];return n}return {}}function 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 s=this.data.get(t);s[n]=r;}async getData(t,n){return this.data.get(t)?.[n]}async getAllData(t){return {...this.data.get(t)??{}}}async clearData(t){this.data.delete(t);}async listRuns(){return Array.from(this.runs.keys())}clear(){this.runs.clear(),this.data.clear();}};function Pt(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return (e==="x"?t:t&3|8).toString(16)})}var O=class{flow;handlers;store;components;options;listeners=new Map;aborted=false;constructor(t,n,r={}){this.flow=t,this.handlers=new Map(Object.entries(n)),this.store=r.store??new k,this.components=r.components??{},this.options=r,r.signal&&r.signal.addEventListener("abort",()=>{this.aborted=true;}),this.validateFlow();}validateFlow(){let{settings:t,steps:n,terminal_states:r}=this.flow;if(!t?.start_step)throw new Error("Flow must have settings.start_step defined");if(!n||Object.keys(n).length===0)throw new Error("Flow must have at least one step defined");if(!r||Object.keys(r).length===0)throw new Error("Flow must have at least one terminal_state defined");if(!n[t.start_step]&&!r[t.start_step])throw new Error(`Start step "${t.start_step}" not found`);for(let[s,o]of Object.entries(n)){for(let[a,i]of Object.entries(o.transitions))if(!n[i]&&!r[i])throw new Error(`Step "${s}" transition "${a}" points to unknown step "${i}"`);if(o.failure_transitions){for(let[a,i]of Object.entries(o.failure_transitions))if(!n[i]&&!r[i])throw new Error(`Step "${s}" failure_transition "${a}" points to unknown step "${i}"`)}}}on(t,n){this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(n);}off(t,n){this.listeners.get(t)?.delete(n);}emit(t){let n=this.listeners.get(t.type);if(n)for(let r of n)try{r(t);}catch{}}sleep(t){return new Promise(n=>setTimeout(n,t))}async run(t){let n=Pt(),r=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:z(u.return_artifacts,p),finalStep:i,stepHistory:o.stepHistory,durationMs:Date.now()-o.startedAt};return this.emit({type:"flow:complete",runId:t,timestamp:Date.now(),data:{...g}}),this.options.onComplete?.(g),g}let c=V(this.flow,o,i);if(c.broken){o=c.newState,await this.store.saveRunState(t,o),a++;continue}o=c.newState;let f=await this.store.getAllData(t),l=q(this.flow,i,f),d={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,d);}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 $(e,t,n){return new O(e,t,n)}async function G(e){return (await import('yaml')).parse(e)}async function _t(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 I(e){let t;typeof e=="string"?e.startsWith("http://")||e.startsWith("https://")?t=await _t(e):e.includes("{")?t=JSON.parse(e):t=await Ot(e):t=e;let n=nt(t);if(n.length>0)throw new Error(`Invalid step flow configuration:
2
2
  - ${n.join(`
3
- - `)}`);return t}function 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 F=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 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 Nt(){let e=resolve(ot,"./jsonata-sync.cjs");return existsSync(e)?e:resolve(ot,"../card-compute/jsonata-sync.cjs")}var M=Dt(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 s=n.data&&typeof n.data=="object"&&!Array.isArray(n.data)?{...n.data}:{},o=typeof n.error=="string"?n.error:void 0;return o&&!("error"in s)&&(s.error=o),{result:r,data:s,...o?{error:o}:{}}}return {result:"success",data:{...n}}}function at(e,t){if(!t||t.length===0)return e;let n={};for(let r of t)Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function X(e,t){return async(n,r)=>{let s=await e(n,r),o=it(s,r?.stepName??"unknown");return {result:o.result,data:at(o.data,t),...o.error?{error:o.error}:{}}}}function ct(e,t,n){if(!t||t.length===0)return null;for(let r of t)try{if(!M(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 Z(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 v=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(v(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=v(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(v(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=v(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=v(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 ft(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=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)})`);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=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)})`);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=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:s,data:o,error:a}:{result:s,data:o}}var H="b64:";function Wt(e){let t=new TextEncoder().encode(e),n=globalThis.Buffer,r;if(n)r=n.from(t).toString("base64");else if(typeof btoa=="function"){let s="";for(let o of t)s+=String.fromCharCode(o);r=btoa(s);}else throw new Error("No base64 encoder available in this runtime");return r.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function Gt(e){let t=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-e.length%4)%4),n=globalThis.Buffer;if(n)return n.from(t,"base64").toString("utf8");if(typeof atob=="function"){let r=atob(t),s=new Uint8Array(r.length);for(let o=0;o<r.length;o+=1)s[o]=r.charCodeAt(o);return new TextDecoder().decode(s)}throw new Error("No base64 decoder available in this runtime")}function J(e){return `${H}${Wt(JSON.stringify(e))}`}function dt(e){if(!e.startsWith(H))throw new Error(`Invalid ref format (expected ${H}<base64url(json)>): ${e}`);let t;try{t=JSON.parse(Gt(e.slice(H.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("."),s=e;for(let o=0;o<r.length-1;o++){let a=r[o];(s[a]==null||typeof s[a]!="object")&&(s[a]={}),s=s[a];}s[r[r.length-1]]=n;}function ht(e,t,n){let r=e.expr.map(Yt);return async s=>{let o=s&&typeof s=="object"&&!Array.isArray(s)?{...s}:{},a={},i={expects_data:o,data:a,...n?{config:n}:{}},u,c;for(let f of r)try{let l=M(f.expr).evaluate(i);if(f.bindTo==="result")u=l!=null?String(l):"success";else if(f.bindTo==="error")c=l!=null?String(l):void 0;else if(f.bindTo.startsWith("data."))Xt(a,f.bindTo.slice(5),l);else return {result:"failure",data:{},error:`[${t}] invalid bindTo "${f.bindTo}": must be "result", "error", or start with "data."`}}catch(l){let d=l instanceof Error?l.message:String(l);return {result:"failure",data:{},error:`[${t}] compute "${f.bindTo}" failed: ${d}`}}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: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 ft(e.outputTransforms,c,t)}catch(f){let l=f instanceof Error?f.message:String(f);return {result:"failure",data:{},error:l}}}catch(c){let f=c instanceof Error?c.message:String(c);return {result:"failure",data:{error:`[step-machine-public] step "${t}" invoke threw: ${f}`}}}}}function wt(){return async e=>({result:"success",data:e&&typeof e=="object"&&!Array.isArray(e)?e:{}})}function Zt(e,t,n){return async(r,s)=>{let o=r?.[t.items];if(!Array.isArray(o))return {result:"failure",data:{},error:`[${n}] forEach: "${t.items}" is not an array (got ${typeof o})`};let a=o,i=t.collectAs??`${t.items}_results`;if(a.length===0)return {result:"success",data:{[i]:[]}};let{[t.items]:u,...c}=r,f=Math.max(1,t.concurrency??1),l=new Array(a.length),d=0,h=0,w=0;return await new Promise(p=>{function g(){for(;d<f&&h<a.length;){let R=h++;d++;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(()=>{d--,l[R]?.result==="failure"&&w++,h>=a.length&&d===0?p():g();});}d===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,s=Array.isArray(t?.input_validations)?t?.input_validations:void 0,o=t?.config??void 0,a=t?.handler,i;return gt(a)?i=ht(a,e,o):mt(a)?i=yt(a,e,n.invoke,o):i=wt(),t?.forEach&&(i=Zt(i,t.forEach,e)),Z(X(i,r),s,e)}function B(e,t){let n={};for(let[r,s]of Object.entries(e.steps??{}))n[r]=St(r,s,t);return n}function ne(e){if(typeof e=="object"&&e!==null){let{command:n,args:r=[],...s}=e,o=Rt(n,r);return {...s,command:o.command,args:o.args}}let t=kt(e);if(t.length===0)throw new Error(`Empty command spec: ${JSON.stringify(e)}`);return 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 kt(e){let t=[],n="",r=null;for(let s of e.trim()){if(r){s===r?r=null:n+=s;continue}if(s==='"'||s==="'"){r=s;continue}if(/\s/.test(s)){n&&(t.push(n),n="");continue}n+=s;}if(r)throw new Error(`Unterminated quote in command: ${e}`);return n&&t.push(n),t}function Q(e){return process.platform==="win32"&&/\.(cmd|bat)$/i.test(e)}function bt(e,t){let{command:n,args:r=[],cwd:s,env:o,timeoutMs:a}=e;return execFileSync(n,r,{shell:Q(n),timeout:a,encoding:t?.encoding??"utf-8",cwd:s,windowsHide:true,env:o?{...process.env,...o}:void 0,input:t?.input})}function re(e,t){let{command:n,args:r=[],cwd:s,env:o,timeoutMs:a=3e4}=e;execFile(n,r,{shell:Q(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));}x.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:Q(t)}).unref();return}spawn(t,n,{detached:true,stdio:"ignore"}).unref();}function At(e,t,n){let r=x.join(e,"board-live-cards-cli.js");if(m.existsSync(r))return {cmd:process.execPath,args:[r,t,...n]};let s=x.join(e,"board-live-cards-cli.ts"),o=x.join(e,"..","..","node_modules","tsx","dist","cli.mjs"),a=x.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 jt(){return {executeSync(e,t,n){return bt({command:e,args:t,cwd:n?.cwd,timeoutMs:n?.timeout,env:n?.env},{encoding:n?.encoding,input:n?.input})},executeAsync(e,t,n){re({command:e,args:t},n);},resolveInvocation(e,t){let n=ne({command:e,args:t});return {cmd:n.command,args:n.args??[]}},splitCommand:kt,spawnDetached(e,t){Et({command:e,args:t});}}}var oe=createRequire(import.meta.url);function ie(e){return typeof e=="object"?e:dt(e)}function ae(e){let t=x.basename(String(e||"").trim());if(!t)throw new Error(`resolveYamlFlowCliPath: expected non-empty cli file name, got ${JSON.stringify(e)}`);let n=x.dirname(oe.resolve("yaml-flow/package.json")),r=x.join(n,"cli","node",t);if(!m.existsSync(r))throw new Error(`resolveYamlFlowCliPath: could not find ${t} under ${x.join(n,"cli","node")}`);return r}function L(e){let t=ie(e);return t.kind==="yaml-flow-cli"?ae(t.value):t.value}function ce(e,t){let n=L(e);switch(n){case "source-cli-task-executor":{let r=x.join(t,"source-cli-task-executor.js");if(m.existsSync(r))return {command:process.execPath,args:[r]};let s=x.join(t,"source-cli-task-executor.ts"),o=x.join(t,"..","..","node_modules","tsx","dist","cli.mjs"),a=x.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}=At(t,"_",[]);return {command:r,args:s}}default:throw new Error(`resolveBuiltIn: unknown built-in name "${n}". Supported: source-cli-task-executor, board-live-cards`)}}function ue(e,t){if(e.howToRun==="built-in"){let{command:r,args:s}=ce(e.whatToRun,t);return {command:r,baseArgs:s}}let n=(typeof e.whatToRun=="object",L(e.whatToRun));switch(e.howToRun){case "local-node":return {command:process.execPath,baseArgs:[n]};case "local-python":return {command:process.platform==="win32"?"python":"python3",baseArgs:[n]};case "local-process":return {command:n,baseArgs:[]};default:throw new Error(`resolveBaseInvocation: howToRun "${e.howToRun}" is not a local transport`)}}function le(e,t){return ue(e,t)}function pe(e){let t=e.trim();if(!t)throw new Error("empty stdout");try{return JSON.parse(t)}catch{let n=t.split(/\r?\n/).filter(Boolean),r=n[n.length-1];return JSON.parse(r)}}function fe(e,t){return {...t,whatToRun:L(e.whatToRun),...e.extra?{extra:e.extra}:{}}}function de(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 D(e,t,n){let r=n?.label??"invokeExecutionRefSync",s=n?.cliDir??n?.cwd??process.cwd(),o;try{o=de(e.argsMassaging,fe(e,t),r);}catch(l){let d=l instanceof Error?l.message:String(l);return N(d)}let a;try{a=le(e,s);}catch(l){let d=l instanceof Error?l.message:String(l);return N(`[${r}] ref resolution failed: ${d}`)}let i=[...a.baseArgs,...o.cmdArgs??[]],u=JSON.stringify(o.stdin??t),c=jt(),f;try{f=c.executeSync(a.command,i,{timeout:n?.timeoutMs??3e4,encoding:"utf-8",cwd:n?.cwd,input:u});}catch(l){let d=l,h=(d.stderr?String(d.stderr):"").trim(),w=typeof d.status=="number"?d.status:"unknown",p=h||d.message;return N(`[${r}] ref exited with status ${w}${p?`: ${p}`:""}`)}try{return ge(pe(f))}catch{return {result:"success",data:{stdout:f.trim()}}}}var me={"local-node":D,"local-python":D,"local-process":D,"built-in":D};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 Ft(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(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 x.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(x.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(x.dirname(o),{recursive:true}),m.writeFileSync(a,JSON.stringify(s,null,2),"utf-8"),we(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},Se=".pause";async function sr(e){let t=xe(e);if(t.help||e.length===0)throw Fe(),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=Re(s,o);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 f=Mt(n),l=x.dirname(f),d=Ee(r),{store:h}=c,w=await I(f),p=je(w,l);Tt(c);let g=new AbortController,R=false,P=$(w,p,{store:h,signal:g.signal,onStep:()=>{!R&&et(c)&&(R=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"&&!d&&(S=await $t(c));let y=S?await P.resume(S):await P.run(d);if(R&&y.status==="cancelled"){let _=await ke(h,y.runId);Tt(c),console.log(JSON.stringify({runId:y.runId,status:"paused",currentStep:_?.currentStep,pausedAt:_?.pausedAt,stepHistory:y.stepHistory,data:y.data},null,2));return}if(y.status!=="completed"){let _=y.error?.message??y.intent??y.status;throw console.error(`[step-machine-cli] Run failed: ${_}`),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 xe(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 f=e[u+1];if(!f||f.startsWith("--"))throw new Error(`[step-machine-cli] Missing value for ${c}.`);n[c]=f,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 Mt(e){return x.isAbsolute(e)?e:x.resolve(process.cwd(),e)}function Re(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=Mt(t);return {storeType:e,storeDir:n,pauseFilePath:x.join(n,Se),store:new F(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 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),s=Buffer.from(r.replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8"),o=JSON.parse(s);return !o||typeof o!="object"||typeof o.value!="string"?e:{...t,whatToRun:o}}catch{return e}}function je(e,t){return B(e,{invoke:(r,s)=>Ft(Ae(r),s,{cliDir:t,cwd:t})})}function Fe(){console.error("Usage: step-machine-cli <step-flow.yaml> [--initial-data <json>] [--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,sr 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, S as ScratchStorage, c as ArchiveFactory, d as AtomicRelayLock, E as ExecutionRef, K as KindValueRef, J as JournalStorage } from './execution-interface-DCFBy4L8.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
@@ -181,6 +76,22 @@ interface BoardPlatformAdapter {
181
76
  * '' — root-scoped blob access (for resolving arbitrary KindValueRef blobs)
182
77
  */
183
78
  blobStorage(namespace: string): BlobStorage;
79
+ /**
80
+ * Ephemeral scratch store for transient I/O staging (probe in/out/err,
81
+ * dispatchExecution argv/out/err). Default scope is board-local; if the
82
+ * config has a 'scratch-store-ref' set, scratchStorageForRef(ref) is used
83
+ * instead.
84
+ */
85
+ scratchStorage(): ScratchStorage;
86
+ scratchStorageForRef(ref: string): ScratchStorage;
87
+ /**
88
+ * Archive factory — long-lived tracking / audit store. Default scope is
89
+ * board-local; if the config has an 'archive-store-ref' set,
90
+ * archiveFactoryForRef(ref) is used instead so archives can live on a
91
+ * different backend / path than the main board runtime.
92
+ */
93
+ archiveFactory(): ArchiveFactory;
94
+ archiveFactoryForRef(ref: string): ArchiveFactory;
184
95
  /**
185
96
  * Journal storage adapter (append-only log).
186
97
  * Uses the lib's JournalStorageAdapter interface.
@@ -198,7 +109,7 @@ interface BoardPlatformAdapter {
198
109
  /**
199
110
  * Self-identity ExecutionRef — how to invoke THIS board instance.
200
111
  * 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"})>' }
112
+ * Node/FS: { howToRun: 'local-node', whatToRun: 'b64:<base64url({"kind":"yaml-flow-cli","value":"board-live-cards-cli.js"})>' }
202
113
  * Azure Fn: { howToRun: 'http:post', whatToRun: 'b64:<base64url({"kind":"http-url","value":"https://…/api/board"})>' }
203
114
  */
204
115
  selfRef: ExecutionRef;
@@ -259,6 +170,12 @@ interface BoardLiveCardsPublic {
259
170
  getOutputsStoreRef(input: CommandInput): CommandResult<{
260
171
  storeRef: string;
261
172
  }>;
173
+ getScratchStoreRef(input: CommandInput): CommandResult<{
174
+ storeRef: string | null;
175
+ }>;
176
+ getArchiveStoreRef(input: CommandInput): CommandResult<{
177
+ storeRef: string | null;
178
+ }>;
262
179
  getConfig(input: CommandInput): CommandResult<{
263
180
  value: unknown;
264
181
  }>;
@@ -295,9 +212,7 @@ interface BoardNonCorePlatformAdapter extends BoardPlatformAdapter {
295
212
  ok: boolean;
296
213
  errors: string[];
297
214
  };
298
- /** Create a temp file path for I/O staging absolute, board-scoped. */
299
- makeTempFilePath(label: string, ext?: string): string;
300
- /** Absolute-path blob I/O for temp files and card file references. */
215
+ /** Absolute-path blob I/O for resolving arbitrary KindValueRef blobs. */
301
216
  absoluteBlob: BlobStorage;
302
217
  /**
303
218
  * Default timeouts (ms) for synchronous executor invocations.
@@ -416,18 +331,6 @@ interface ChatStorage {
416
331
  declare function createChatStorage(journalFactory: (cardId: string) => JournalStorage, kv: KVStorage): ChatStorage;
417
332
  declare function createInMemoryChatStorage(): ChatStorage;
418
333
 
419
- /**
420
- * server-runtime/types.ts
421
- *
422
- * Platform-free adapter interfaces for the board server runtime.
423
- *
424
- * The runtime (index.ts) imports ONLY this file and board-live-cards-public
425
- * for its dependencies — no node:fs, node:net, node:child_process, etc.
426
- *
427
- * Hosts (demo-server, Azure Function, Firebase Function) provide implementations
428
- * of these interfaces when constructing the runtime.
429
- */
430
-
431
334
  interface InvocationAdapter {
432
335
  /**
433
336
  * Fire-and-forget invocation of an ExecutionRef with args.
@@ -464,4 +367,4 @@ interface DescribeEnvelope {
464
367
  supports?: string[];
465
368
  }
466
369
 
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 };
370
+ 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 };