yaml-flow 8.5.3 → 8.6.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/browser/asset-integrity.json +3 -3
- package/examples/board/demo-shell-with-server.html +2 -2
- package/examples/board/doc.html +2 -2
- package/examples/board/server/board-server.js +773 -13
- package/examples/board/server/board-worker/task-executor.js +166 -51
- package/examples/board/server/chat-flow/copilot-chat/assistant.js +25 -12
- package/examples/board/server/chat-flow/copilot-chat/probe.js +7 -0
- package/examples/board/server/chat-flow/copilot-chat/shared.js +97 -0
- package/examples/board/server/chat-flow/flow-steps.json +109 -51
- package/examples/board/server-config.json +2 -0
- package/examples/board/test/server-http-test.js +878 -67
- package/examples/board-local/demo-shell-localstorage.html +3 -3
- package/lib/{artifacts-store-lib-CVgtQrNZ.d.cts → artifacts-store-lib-BR-Samty.d.cts} +1 -1
- package/lib/{artifacts-store-lib-D-k-E8Vy.d.ts → artifacts-store-lib-DT7XlWUL.d.ts} +1 -1
- package/lib/artifacts-store-public.cjs +1 -1
- package/lib/artifacts-store-public.d.cts +3 -3
- package/lib/artifacts-store-public.d.ts +3 -3
- package/lib/artifacts-store-public.js +1 -1
- package/lib/batch/index.cjs +1 -1
- package/lib/batch/index.js +1 -1
- package/lib/board-live-cards-mcp.cjs +1 -1
- package/lib/board-live-cards-mcp.d.cts +87 -34
- package/lib/board-live-cards-mcp.d.ts +87 -34
- package/lib/board-live-cards-mcp.js +1 -1
- package/lib/board-live-cards-node.cjs +8 -16
- package/lib/board-live-cards-node.d.cts +52 -14
- package/lib/board-live-cards-node.d.ts +52 -14
- package/lib/board-live-cards-node.js +8 -16
- package/lib/{board-live-cards-public-BGS22cMb.d.ts → board-live-cards-public-BMUIPOrc.d.ts} +90 -30
- package/lib/board-live-cards-public-async-DKZqbJVU.d.ts +256 -0
- package/lib/board-live-cards-public-async-dMWNbWq6.d.cts +256 -0
- package/lib/{board-live-cards-public-B13InXhC.d.cts → board-live-cards-public-wkNmBIRC.d.cts} +90 -30
- package/lib/board-live-cards-public.cjs +1 -2
- package/lib/board-live-cards-public.d.cts +2 -2
- package/lib/board-live-cards-public.d.ts +2 -2
- package/lib/board-live-cards-public.js +1 -2
- package/lib/board-live-cards-server-runtime.cjs +1 -7
- package/lib/board-live-cards-server-runtime.d.cts +7 -6
- package/lib/board-live-cards-server-runtime.d.ts +7 -6
- package/lib/board-live-cards-server-runtime.js +1 -7
- package/lib/board-livegraph-runtime/index.cjs +1 -2
- package/lib/board-livegraph-runtime/index.js +1 -2
- package/lib/board-worker-adapter.cjs +22 -7
- package/lib/board-worker-adapter.d.cts +28 -3
- package/lib/board-worker-adapter.d.ts +28 -3
- package/lib/board-worker-adapter.js +22 -7
- package/lib/card-compute/index.cjs +1 -9
- package/lib/card-compute/index.js +1 -9
- package/lib/card-store-public.cjs +1 -1
- package/lib/card-store-public.d.cts +2 -2
- package/lib/card-store-public.d.ts +2 -2
- package/lib/card-store-public.js +1 -1
- package/lib/card-validation.cjs +1 -9
- package/lib/card-validation.js +1 -9
- package/lib/{chat-storage-lib-0imhRX3l.d.cts → chat-storage-lib-BIUbE-fM.d.cts} +1 -1
- package/lib/{chat-storage-lib-CJn7a6OH.d.ts → chat-storage-lib-BlG-sobS.d.ts} +1 -1
- package/lib/chat-store-public.cjs +1 -1
- package/lib/chat-store-public.d.cts +3 -3
- package/lib/chat-store-public.d.ts +3 -3
- package/lib/chat-store-public.js +1 -1
- package/lib/chunk-2MZUYY65.cjs +2 -0
- package/lib/chunk-5EA2ESS4.cjs +16 -0
- package/lib/chunk-76ON3V7R.js +2 -0
- package/lib/chunk-7BKNHFNH.js +2 -0
- package/lib/chunk-BQS3EIEK.js +3 -0
- package/lib/chunk-CIAJNUR4.js +2 -0
- package/lib/chunk-DAXACY63.js +2 -0
- package/lib/chunk-FW4363Y4.js +2 -0
- package/lib/chunk-FZ2SBU5M.js +3 -0
- package/lib/chunk-G4XXRHL2.cjs +3 -0
- package/lib/chunk-GJJMEAVN.cjs +2 -0
- package/lib/chunk-GNFE24S7.cjs +2 -0
- package/lib/chunk-GYQXDNNI.cjs +2 -0
- package/lib/chunk-H5HBXPOI.cjs +3 -0
- package/lib/chunk-H5KD3JPY.cjs +2 -0
- package/lib/chunk-HEEDJEKM.js +2 -0
- package/lib/chunk-HLJH7LGW.js +16 -0
- package/lib/chunk-IXZG74EW.cjs +2 -0
- package/lib/chunk-JAL25FGA.cjs +2 -0
- package/lib/chunk-JM5EKT57.js +2 -0
- package/lib/chunk-JMDHDY6M.js +2 -0
- package/lib/chunk-KBELAKIY.js +2 -0
- package/lib/chunk-KHJABJ45.cjs +3 -0
- package/lib/chunk-KLRUISRY.cjs +2 -0
- package/lib/chunk-KQX6R4PV.cjs +8 -0
- package/lib/chunk-LODXIALE.cjs +2 -0
- package/lib/chunk-MLVTJASJ.js +2 -0
- package/lib/chunk-MNEOJWPS.js +10 -0
- package/lib/chunk-N6P2JW4W.js +3 -0
- package/lib/chunk-NMZ6XNLB.cjs +3 -0
- package/lib/chunk-OEFTOO47.cjs +3 -0
- package/lib/chunk-OPNGCSXJ.js +2 -0
- package/lib/chunk-OSWJKJLB.js +8 -0
- package/lib/chunk-P7ZCDICS.cjs +2 -0
- package/lib/chunk-PBCDDO4V.cjs +2 -0
- package/lib/chunk-PMUSJQSR.cjs +2 -0
- package/lib/chunk-Q6H7NINN.cjs +5 -0
- package/lib/chunk-QWBNDVUA.js +5 -0
- package/lib/chunk-S6DRP2HX.cjs +2 -0
- package/lib/chunk-SCWHDI3I.js +2 -0
- package/lib/chunk-SFVO2LB2.cjs +3 -0
- package/lib/chunk-U2N6MCD5.cjs +2 -0
- package/lib/chunk-UJ7ZTV4J.cjs +10 -0
- package/lib/chunk-VGT3TRQG.js +3 -0
- package/lib/chunk-VLBB3D6B.js +3 -0
- package/lib/chunk-VMW4Z6EF.js +3 -0
- package/lib/chunk-WDPOGXTY.js +2 -0
- package/lib/chunk-WOALA3V5.cjs +2 -0
- package/lib/chunk-X3LC4LII.js +2 -0
- package/lib/chunk-XQRNDX4Q.js +2 -0
- package/lib/chunk-YGKDQLYP.js +2 -0
- package/lib/chunk-YMEIPKLW.cjs +2 -0
- package/lib/cloud-storage.cjs +2 -0
- package/lib/cloud-storage.d.cts +177 -0
- package/lib/cloud-storage.d.ts +177 -0
- package/lib/cloud-storage.js +2 -0
- package/lib/config/index.cjs +1 -1
- package/lib/config/index.js +1 -1
- package/lib/continuous-event-graph/index.cjs +1 -2
- package/lib/continuous-event-graph/index.js +1 -2
- package/lib/event-graph/index.cjs +1 -22
- package/lib/event-graph/index.js +1 -22
- package/lib/execution-refs.cjs +1 -2
- package/lib/execution-refs.d.cts +3 -2
- package/lib/execution-refs.d.ts +3 -2
- package/lib/execution-refs.js +1 -2
- package/lib/index.cjs +2 -24
- package/lib/index.d.cts +1 -1
- package/lib/index.d.ts +1 -1
- package/lib/index.js +2 -24
- package/lib/{types-CIgsh56O.d.cts → queue-lane-registry-BPKWWgd4.d.cts} +66 -14
- package/lib/{types-30R357js.d.ts → queue-lane-registry-Be6c0ftj.d.ts} +66 -14
- package/lib/server-runtime/index.cjs +1 -7
- package/lib/server-runtime/index.d.cts +18 -7
- package/lib/server-runtime/index.d.ts +18 -7
- package/lib/server-runtime/index.js +1 -7
- package/lib/step-machine/index.cjs +1 -11
- package/lib/step-machine/index.js +1 -11
- package/lib/step-machine-public/index.cjs +1 -4
- package/lib/step-machine-public/index.d.cts +1 -1
- package/lib/step-machine-public/index.d.ts +1 -1
- package/lib/step-machine-public/index.js +1 -4
- package/lib/{storage-interface-B2WD9D5n.d.cts → storage-interface-BFiD3kyB.d.cts} +38 -1
- package/lib/{storage-interface-B2WD9D5n.d.ts → storage-interface-BFiD3kyB.d.ts} +38 -1
- package/lib/stores/index.cjs +1 -2
- package/lib/stores/index.d.cts +1 -1
- package/lib/stores/index.d.ts +1 -1
- package/lib/stores/index.js +1 -2
- package/lib/stores/kv.cjs +1 -2
- package/lib/stores/kv.d.cts +1 -1
- package/lib/stores/kv.d.ts +1 -1
- package/lib/stores/kv.js +1 -2
- package/lib/stores/memory.cjs +1 -1
- package/lib/stores/memory.js +1 -1
- package/package.json +7 -16
- package/cli/board-live-cards-lib-COi4bSpk.d.ts +0 -322
- package/cli/browser-api/board-live-cards-browser-adapter.d.ts +0 -36
- package/cli/browser-api/board-live-cards-browser-adapter.js +0 -4
- package/cli/browser-api/card-store-browser-api.d.ts +0 -25
- package/cli/browser-api/card-store-browser-api.js +0 -2
- package/cli/browser-api/jsonata-sync.cjs +0 -7623
- package/cli/bundled/artifacts-store-cli.mjs +0 -12
- package/cli/bundled/batch-runner-cli.mjs +0 -3
- package/cli/bundled/board-live-cards-cli.mjs +0 -29
- package/cli/bundled/card-store-cli.mjs +0 -154
- package/cli/bundled/chat-store-cli.mjs +0 -16
- package/cli/bundled/jsonata-sync.cjs +0 -7623
- package/cli/bundled/step-machine-cli.mjs +0 -150
- package/cli/execution-interface-BCIhu1gO.d.ts +0 -442
- package/cli/types-H3EMBPY2.d.ts +0 -398
- package/examples/board/server/README-mcp-api.md +0 -690
- package/examples/board/test/server-http-mcp-test.js +0 -1280
- package/lib/board-livegraph-runtime/jsonata-sync.cjs +0 -7623
- package/lib/card-compute/jsonata-sync.cjs +0 -7623
- package/lib/continuous-event-graph/jsonata-sync.cjs +0 -7623
- package/lib/server-runtime/jsonata-sync.cjs +0 -7623
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {c,n,m,l as l$1,k,j,i as i$1,h as h$1,g as g$1,f,e,d,u}from'./chunk-VGT3TRQG.js';import {i,a,g,h,l}from'./chunk-WDPOGXTY.js';import {a as a$1}from'./chunk-JMDHDY6M.js';import {exec,execFile}from'child_process';function z(s){let{config:e,state:o}=s,a$1=i(e),i$1=Object.keys(a$1),d=0,c=0,l=0,f=0,t=0,r=0;for(let h of i$1){let T=o.tasks[h];if(!T||T.status===a.NOT_STARTED)t++;else switch(T.status){case a.RUNNING:d++;break;case a.COMPLETED:c++;break;case a.FAILED:l++;break;case "inactivated":r++;break;default:f++;}}let n={};for(let[h,T]of Object.entries(a$1)){for(let R of g(T))n[R]||(n[R]=[]),n[R].push(h);if(T.on)for(let R of Object.values(T.on))for(let g of R)n[g]||(n[g]=[]),n[g].includes(h)||n[g].push(h);if(T.on_failure)for(let R of T.on_failure)n[R]||(n[R]=[]),n[R].includes(h)||n[R].push(h);}let u=new Set,p=0,k=0;for(let[h$1,T]of Object.entries(a$1)){let R=o.tasks[h$1];if(R?.status===a.COMPLETED||R?.status===a.RUNNING)continue;let g=false,H=false;for(let x of h(T)){let q=n[x]||[];q.length===0?(u.add(x),g=true):q.every(Y=>{let W=o.tasks[Y];return W?.status===a.FAILED||W?.status==="inactivated"})&&(H=true);}g&&p++,H&&!g&&k++;}let m=[];for(let[h,T]of Object.entries(n))T.length>1&&m.push(h);let v=Q(a$1,n),b=Z(i$1,v);return {totalNodes:i$1.length,running:d,completed:c,failed:l,waiting:f,notStarted:t,disabled:r,unresolvedCount:p,blockedCount:k,openDependencies:[...u],cycles:b,conflictTokens:m}}function Q(s,e){let o={};for(let[a,i]of Object.entries(s)){o[a]=new Set;for(let d of h(i))for(let c of e[d]||[])c!==a&&o[a].add(c);}return o}function Z(s,e){let d={},c={},l=[];for(let t of s)d[t]=0,c[t]=null;function f(t){d[t]=1;for(let r of e[t]||[])if(d[r]===1){let n=[r],u=t;for(;u!==r;)n.push(u),u=c[u];n.push(r),n.reverse(),l.push(n);}else d[r]===0&&(c[r]=t,f(r));d[t]=2;}for(let t of s)d[t]===0&&f(t);return l}function B(s){let e={};for(let[o,a]of Object.entries(s)){for(let i of g(a))e[i]||(e[i]=[]),e[i].push(o);if(a.on)for(let i of Object.values(a.on))for(let d of i)e[d]||(e[d]=[]),e[d].includes(o)||e[d].push(o);if(a.on_failure)for(let i of a.on_failure)e[i]||(e[i]=[]),e[i].includes(o)||e[i].push(o);}return e}function V(s){let{config:e,state:o}=s,a=i(e),i$1=B(a),d=new Set([...o.availableOutputs]);for(let[n,u]of Object.entries(o.tasks))if(u.status==="completed"){let p=a[n];p&&g(p).forEach(k=>d.add(k));}let c=new Set;for(let n of Object.values(a))for(let u of h(n))c.add(u);let l$1=new Set,f=new Set;for(let n of c){if(d.has(n))continue;(i$1[n]||[]).length===0&&l$1.add(n);}let t=true;for(;t;){t=false;for(let[n,u]of Object.entries(a)){if(f.has(n))continue;let p=o.tasks[n];if(p?.status==="completed")continue;let k=l(p),v=h(u).some(b=>l$1.has(b));(k||v)&&(f.has(n)||(f.add(n),t=true));}for(let n of c){if(l$1.has(n)||d.has(n))continue;let u=i$1[n]||[],p=u.length>0&&u.every(k=>f.has(k)||l(o.tasks[k]));(u.length===0||p)&&(l$1.has(n)||(l$1.add(n),t=true));}}let r=[];for(let n of l$1){let u=i$1[n]||[],p;u.length===0?p="no-producer":p=u.every(m=>l(o.tasks[m]))?"all-producers-failed":"transitive",r.push({token:n,reason:p,producers:u});}return {tokens:r}}function ee(s){let{config:e,state:o}=s,a=i(e),{tokens:i$1}=V(s),d=new Set(i$1.map(l=>l.token)),c=[];for(let[l$1,f]of Object.entries(a)){let t=o.tasks[l$1];if(t?.status==="completed")continue;let n=h(f).filter(u=>d.has(u));n.length>0?c.push({nodeName:l$1,missingTokens:n}):l(t)&&c.push({nodeName:l$1,missingTokens:[]});}return {nodes:c}}function te(s,e){let o=i(s.config);if(!o[e])return {nodeName:e,nodes:[],tokens:[]};let a=B(o),i$1=new Set,d=new Set,c=new Map;function l(t){let r=o[t];if(r)for(let n of h(r)){let u=a[n]||[];for(let p of u)p!==e&&(d.add(n),c.has(p)||c.set(p,new Set),c.get(p).add(n),i$1.has(p)||(i$1.add(p),l(p)));}}l(e);let f=[...c.entries()].map(([t,r])=>({nodeName:t,providesTokens:[...r]}));return {nodeName:e,nodes:f,tokens:[...d]}}function ne(s,e){let o=i(s.config);if(!o[e])return {nodeName:e,nodes:[],tokens:[]};let a={};for(let[t,r]of Object.entries(o))for(let n of h(r))a[n]||(a[n]=[]),a[n].push(t);let i$1=new Set,d=new Set,c=new Map;function l(t){let r=o[t];if(r)for(let n of g(r)){let u=a[n]||[];for(let p of u)p!==e&&(d.add(n),c.has(p)||c.set(p,new Set),c.get(p).add(n),i$1.has(p)||(i$1.add(p),l(p)));}}l(e);let f=[...c.entries()].map(([t,r])=>({nodeName:t,requiresTokens:[...r]}));return {nodeName:e,nodes:f,tokens:[...d]}}function K(s){let e=[],{config:o,state:a$1}=s,i$1=i(o),d=Object.keys(i$1);for(let t of d)a$1.tasks[t]||e.push({severity:"error",code:"MISSING_STATE",message:`Task "${t}" exists in config but has no state entry`,tasks:[t]});for(let t of Object.keys(a$1.tasks))i$1[t]||e.push({severity:"warning",code:"ORPHAN_STATE",message:`State entry "${t}" has no corresponding task config`,tasks:[t]});for(let t of d){let r=a$1.tasks[t];r&&(r.status===a.RUNNING&&!r.startedAt&&e.push({severity:"warning",code:"RUNNING_WITHOUT_START",message:`Task "${t}" is running but has no startedAt timestamp`,tasks:[t]}),r.status===a.COMPLETED&&!r.completedAt&&e.push({severity:"warning",code:"COMPLETED_WITHOUT_TIMESTAMP",message:`Task "${t}" is completed but has no completedAt timestamp`,tasks:[t]}),r.status===a.FAILED&&(r.failedAt||e.push({severity:"warning",code:"FAILED_WITHOUT_INFO",message:`Task "${t}" is failed but has no failedAt timestamp`,tasks:[t]}),r.error||e.push({severity:"info",code:"FAILED_WITHOUT_INFO",message:`Task "${t}" is failed but has no error message`,tasks:[t]})));}let c=new Set;for(let t of d)if(a$1.tasks[t]?.status===a.COMPLETED)for(let n of g(i$1[t]))c.add(n);let l=new Set(a$1.availableOutputs),f=new Set;for(let t of Object.values(i$1)){for(let r of g(t))f.add(r);if(t.on)for(let r of Object.values(t.on))for(let n of r)f.add(n);if(t.on_failure)for(let r of t.on_failure)f.add(r);}for(let t of l)!c.has(t)&&!f.has(t)&&e.push({severity:"info",code:"INJECTED_TOKEN",message:`Token "${t}" is available but no task in the graph can produce it (likely injected)`,tokens:[t]});for(let t of c)l.has(t)||e.push({severity:"warning",code:"MISSING_OUTPUT",message:`Token "${t}" should be available (its producer completed) but is not in availableOutputs`,tokens:[t]});for(let t of d){let r=a$1.tasks[t];if(!r)continue;r.executionCount<0&&e.push({severity:"error",code:"INVALID_EXECUTION_COUNT",message:`Task "${t}" has negative execution count: ${r.executionCount}`,tasks:[t]});let n=i$1[t].maxExecutions;n!==void 0&&r.executionCount>n&&e.push({severity:"error",code:"EXCEEDED_MAX_EXECUTIONS",message:`Task "${t}" executed ${r.executionCount} times, exceeding maxExecutions of ${n}`,tasks:[t]});}return J(e)}function se(s){let{graph:e,handlers:o}=s,a=e.getState(),i$1=[],d=i(a.config),c=Object.keys(d),l=new Set(Object.keys(o)),f=new Set;for(let r of c){let n=d[r].taskHandlers;if(n)for(let u of n)f.add(u);}for(let r of c){let n=d[r].taskHandlers;if(n)for(let u of n)o[u]||i$1.push({severity:"error",code:"MISSING_HANDLER",message:`Task "${r}" references handler "${u}" but it is not in the registry`,tasks:[r]});}for(let r of l)f.has(r)||i$1.push({severity:"warning",code:"ORPHAN_HANDLER",message:`Handler "${r}" is registered but not referenced by any task's taskHandlers`,tasks:[r]});let t=K(a);return i$1.push(...t.issues),J(i$1)}function J(s){let e=s.filter(a=>a.severity==="error"),o=s.filter(a=>a.severity==="warning");return {valid:e.length===0,issues:s,errors:e,warnings:o}}function re(s,e){let o=s;for(let a of e)o=oe(o,a);return o}function oe(s,e$1){switch(e$1.type){case "add-node":return d(s,e$1.name,e$1.config);case "remove-node":return e(s,e$1.name);case "add-requires":return f(s,e$1.taskName,e$1.tokens);case "remove-requires":return g$1(s,e$1.taskName,e$1.tokens);case "add-provides":return h$1(s,e$1.taskName,e$1.tokens);case "remove-provides":return i$1(s,e$1.taskName,e$1.tokens);case "inject-tokens":return j(s,e$1.tokens);case "drain-tokens":return k(s,e$1.tokens);case "reset-node":return l$1(s,e$1.name);case "disable-node":return m(s,e$1.name);case "enable-node":return n(s,e$1.name);case "apply-events":return c(s,e$1.events);default:throw new Error(`Unknown mutation type: ${e$1.type}`)}}function ce(s,e){return async o=>{let{callbackToken:a}=o;return Promise.resolve(s(o)).then(i=>e()(a,i)).catch(i=>e()(a,{},[i instanceof Error?i.message:String(i)])),"task-initiated"}}function de(s,e){return async o=>{let{callbackToken:a}=o;return Promise.resolve(s(o)).then(()=>e()(a,{})).catch(()=>e()(a,{})),"task-initiated"}}function ue(s){let{command:e,cwd:o,env:a,timeoutMs:i=3e4,exitCodeMap:d,captureOutput:c=false,getResolve:l}=s;return async f=>{let{callbackToken:t,nodeId:r}=f,n=e.replace(/\$\{taskName\}/g,r);return exec(n,{cwd:o,env:a?{...process.env,...a}:void 0,timeout:i,maxBuffer:10*1024*1024},(u,p,k)=>{let m=u?.code??(u?1:0);if(m!==0&&!d?.[m]){l()(t,{},[`Command exited with code ${m}: ${k||u?.message}`]);return}let v={};c&&(v.stdout=p,v.stderr=k,v.exitCode=m),l()(t,v);}),"task-initiated"}}function X(s){let{command:e,args:o=[],cwd:a,env:i,timeoutMs:d=3e4,exitCodeMap:c,captureOutput:l=false,getResolve:f}=s;return async t=>{let{callbackToken:r,nodeId:n}=t,u=e.replace(/\$\{taskName\}/g,n),p=o.map(k=>k.replace(/\$\{taskName\}/g,n));return execFile(u,p,{cwd:a,env:i?{...process.env,...i}:void 0,timeout:d,maxBuffer:10*1024*1024,encoding:"utf8",windowsHide:true},(k,m,v)=>{let b=k?.code??(k?1:0);if(b!==0&&!c?.[b]){f()(r,{},[`Process exited with code ${b}: ${v||k?.message}`]);return}let h={};l&&(h.stdout=m,h.stderr=v,h.exitCode=b),f()(r,h);}),"task-initiated"}}function le(s){return s.endsWith(".js")||s.endsWith(".mjs")||s.endsWith(".ts")?"node":s.endsWith(".py")?"python3":(s.endsWith(".sh"),"bash")}function pe(s){let{scriptPath:e,runtime:o,args:a=[],cwd:i,timeoutMs:d=6e4,captureOutput:c=false,getResolve:l}=s,f=o??le(e),t=f==="node"?process.execPath:f;return X({command:t,args:[e,"${taskName}",...a],cwd:i,timeoutMs:d,captureOutput:c,getResolve:l})}function fe(s){let{url:e,method:o="POST",headers:a={},timeoutMs:i=3e4,failOnNon2xx:d=true,getResolve:c}=s;return async l=>{let{callbackToken:f,nodeId:t,config:r}=l,n=e.replace(/\$\{taskName\}/g,t),u=JSON.stringify({taskName:t,callbackToken:f,config:r}),p=new AbortController,k=setTimeout(()=>p.abort(),i);return fetch(n,{method:o,headers:{"Content-Type":"application/json",...a},body:u,signal:p.signal}).then(async m=>{if(clearTimeout(k),d&&!m.ok){let b=await m.text().catch(()=>"");c()(f,{},[`HTTP ${m.status}: ${b}`]);return}let v=await m.json().catch(()=>({}));c()(f,v);}).catch(m=>{clearTimeout(k),c()(f,{},[m instanceof Error?m.message:String(m)]);}),"task-initiated"}}function ge(s,e){return async o=>(s()(o.callbackToken,e??{}),"task-initiated")}function ke(s,e={}){let o,a={},i;if(!Array.isArray(s)&&"nodes"in s){let g=s;o=g.nodes,i=g.id,a=g.settings??{};}else o=s;let{sourceHandlers:d={},defaultSourceHandler:c,cardHandlers:l={},reactiveOptions:f={},graphSettings:t={},executionId:r}=e,n=new Map;for(let g of o){if(n.has(g.id))throw new Error(`Duplicate card ID: "${g.id}"`);n.set(g.id,g);}let u$1=e.sharedState??new Map,p={},k=new Set,m=new Map;for(let g of o)for(let H of g.provides??[{bindTo:g.id,ref:"card_data"}])k.add(H.bindTo),m.set(H.bindTo,g.id);for(let g of o){let H=g.requires??[];for(let x of H)if(!k.has(x))throw new Error(`Card "${g.id}" requires "${x}" but no card provides that token`);p[g.id]={requires:H.length>0?H:void 0,provides:(g.provides??[{bindTo:g.id,ref:"card_data"}]).map(x=>x.bindTo),taskHandlers:[g.id],description:g.meta?.title??g.id};}let v={id:i??`live-cards-${Date.now()}`,settings:{completion:"manual",execution_mode:"eligibility-mode",...a,...t},tasks:p},b={},h=null,T=()=>(g,H,x)=>{h.resolveCallback(g,H,x);};for(let g of o)g.source_defs&&g.source_defs.length>0?b[g.id]=me(g,d,c,u$1,T):b[g.id]=he(g,l,u$1,n,m,T);let R=u(v,{...f,handlers:b},r);return h=R,{graph:R,config:v,handlers:b,cards:n,sharedState:u$1}}function me(s,e,o,a,i){if(e[s.id]){let d=e[s.id];return async c=>d(c)}if(o){let d=o(s);return async c=>d(c)}return async d=>{let c={...s.card_data};return a.set(s.id,c),i()(d.callbackToken,c),"task-initiated"}}function he(s,e,o,a,i,d){if(e[s.id]){let c=e[s.id];return async l=>c(l)}return async c=>{let l={},f=s.requires??[];for(let u of f){let p=i.get(u)??u,k=o.get(p);k&&(l[u]=k[u]??k);}let t={id:s.id,card_data:{...s.card_data},requires:l,compute:s.compute};await a$1.run(t);let r;if(s.provides&&s.provides.length>0){r={};for(let{bindTo:u,ref:p}of s.provides)r[u]=a$1.resolve(t,p);}else r={...t.card_data,...t.computed_values};let n={...t.card_data,...t.computed_values};return o.set(s.id,n),d()(c.callbackToken,r),"task-initiated"}}export{z as a,V as b,ee as c,te as d,ne as e,K as f,se as g,re as h,ce as i,de as j,ue as k,X as l,pe as m,fe as n,ge as o,ke as p};//# sourceMappingURL=chunk-OPNGCSXJ.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-OPNGCSXJ.js.map
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import {f,b,c as c$1,e}from'./chunk-MLVTJASJ.js';import {j,d,c,b as b$1}from'./chunk-VMW4Z6EF.js';import {y,z,l}from'./chunk-N6P2JW4W.js';import {b as b$2}from'./chunk-BQS3EIEK.js';import {a as a$2}from'./chunk-SCWHDI3I.js';import {a as a$1}from'./chunk-KBELAKIY.js';import {a}from'./chunk-76ON3V7R.js';function Ie(){return {status:null,computedValues:{},dataObjects:{},cards:{}}}function Nt(c){if(!c||typeof c!="object")return false;let l=c.summary;return !l||typeof l!="object"?false:Number(l.card_count||0)>0}function Dt(c,l){if(!l||typeof l!="object")return;let y=l;if(y.kind==="notification-batch"&&Array.isArray(y.notifications)){for(let _ of y.notifications)Dt(c,_);return}y.kind==="status"&&Nt(y.status)&&(c.status=y.status),y.kind==="computed_values"&&y.cardId&&(c.computedValues[y.cardId]=y.values),y.kind==="data_object"&&y.key&&(c.dataObjects[y.key]=y.payload),y.kind==="card_refreshed"&&y.cardId&&(c.cards[y.cardId]=y.card),y.kind==="card_removed"&&y.cardId&&(delete c.cards[y.cardId],delete c.computedValues[y.cardId]);}function nt(c){return typeof c.journalStorage=="function"}function Oe(c){return typeof c.whatToRun=="string"?c.whatToRun.startsWith("b64:")?b$2(c.whatToRun).value:c.whatToRun:c.whatToRun.value}function V(c){return c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function vt(c){let l=c.reduce((h,x)=>h+x.length,0),y=new Uint8Array(l),_=0;for(let h of c)y.set(h,_),_+=h.length;return y}function E(c,...l){for(let y of l)if(typeof c[y]=="string")return String(c[y]);return ""}function at(c,...l){for(let y of l)if(c[y]!==void 0)return Number(c[y])}function lt(c,...l){for(let y of l){let _=c[y];if(_&&typeof _=="object"&&!Array.isArray(_))return _}return {}}function st(c,l,...y){for(let _ of y){let h=c[_];if(h&&typeof h=="object"&&!Array.isArray(h))return h}throw Object.assign(new Error(`MCP tool requires ${l}`),{statusCode:400})}function _t(c,l,...y){for(let _ of y){let h=c[_];if(h!==void 0){let x=Number(h);if(Number.isFinite(x))return x}}throw Object.assign(new Error(`MCP tool requires ${l}`),{statusCode:400})}function xe(c){if(Array.isArray(c.bytes))return new Uint8Array(c.bytes.map(l=>Math.max(0,Math.min(255,Number(l)||0))));if(typeof c.text=="string")return new TextEncoder().encode(c.text);if(typeof c.base64=="string"){let l=String(c.base64).replace(/-/g,"+").replace(/_/g,"/"),y=l+"=".repeat((4-l.length%4)%4),_=atob(y);return Uint8Array.from(_,h=>h.charCodeAt(0))}return null}function Ut(c,l){return l?{...c,...l.pollIntervalMs!=null?{pollIntervalMs:l.pollIntervalMs}:{},...l.visibilityMs!=null?{visibilityMs:l.visibilityMs}:{},...l.concurrency!=null?{concurrency:l.concurrency}:{},...l.maxAttempts!=null?{maxAttempts:l.maxAttempts}:{}}:c}function Pe(c,l,y,_){return {id:c,async lease(h){return (await Promise.resolve(l.leaseRequests(h))).map(I=>({id:I.messageId,attempt:I.attempt,message:I.request,ack:()=>Promise.resolve(l.ackRequest(I.messageId,I.leaseToken)),nack:O=>Promise.resolve(l.nackRequest(I.messageId,I.leaseToken,O))}))},async handle(h){await y(h.args,h);},onError:_?(h,x)=>_(h,x.attempt,x.message):void 0}}function gr(c,l,y,_){return {id:c,async lease(h){return (await Promise.resolve(l.lease(h))).map(I=>({id:I.id,attempt:I.attempt,message:I.body,ack:()=>Promise.resolve(l.ack(I.id,I.leaseToken)),nack:O=>Promise.resolve(l.nack(I.id,I.leaseToken,O))}))},async handle(){await y();},onError:_?(h,x)=>_(h,x.attempt):void 0}}function kr(c){let l=c.logger??{info(){},warn(){},error(){}},y=c.boardAdapter,_=c.runtime.queueLaneTuning??{},h=y.processAccumulatedStore(),x=y.chatAgentStore(),I=[];if(I.push(Ut(gr("process-accumulated",h,async()=>{let O=await c.runtime.processAccumulatedLane();if(O.status!=="success")throw new Error(O.error||`processAccumulatedLane returned ${O.status}`)},(O,P)=>{l.error(`[board-server] queued process-accumulated failed for ${c.boardId} (attempt ${P}): ${String(O&&O.message||O)}`);}),_.processAccumulated)),I.push(Ut(Pe("chat-agent",x,async(O,P)=>{await c.runtime.handleChatAgentRequest(P);},(O,P,W)=>{let ot=typeof W.args?.cardId=="string"?W.args.cardId:"";l.error(`[board-server] queued chat-agent failed for ${c.boardId}${ot?`/${ot}`:""} (attempt ${P}): ${String(O&&O.message||O)}`);}),_.chatAgent)),c.executeTaskExecutorRequest){let O=y.boardWorkerStore();I.push(Ut(Pe("task-executor",O,c.executeTaskExecutorRequest,(P,W)=>{l.error(`[board-server] queued board-worker failed for ${c.boardId} (attempt ${W}): ${String(P&&P.message||P)}`);}),_.taskExecutor));}return f(I)}var Te={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"content-type,x-file-name","Access-Control-Allow-Methods":"GET,POST,PATCH,OPTIONS"},je="chat-handler-flow-queue";function qr(c$2){let l$1=String(c$2.apiBasePath||"/api/board").replace(/\/$/,""),y$1={...Te,...c$2.corsHeaders||{}},_=c$2.queueLaneTuning??{},h=c$2.boardId||"",x=c$2.logger||{info:console.log,warn:console.warn,error:console.error},I=c$2.invocationAdapter,O=c$2.chatFlowRunner||null,P=c$2.chatStorage??b(),W=a(P),ot=c$2.notificationTransport||null,z$1=c$2.serverUrl||null,mt=c$2.executionExtra||{},Bt=c$2.onSseClientConnected,It=c$2.onSseClientDisconnected,Ot=c$2.onChannelSubscribed,B=c$2.onChannelUnsubscribed,v=new Map,F=new Map,M=new Map,D=null;function Z(t){function e(u){if(Array.isArray(u))return u;if(u&&typeof u=="object"){let b=u;return Array.isArray(b.files)?b.files:[u]}return null}function r(u){return {async get(b){return u.get(b)},async set(b){return u.set(b)},async del(b){return u.del(b)},async patch(b){return u.patch(b)},async appendFiles(b){return u.appendFiles(b)}}}function n(u){function b(i){return {status:"success",data:i}}function A(i){return {status:"fail",error:i}}function R(i){return {status:"error",error:i instanceof Error?i.message:String(i)}}return {async get(i){try{let o=i.params?.id;if(o){let g=await u.readCard(o);return g?b({cards:[g]}):A(`card "${o}" not found`)}return b({cards:await u.readAllCards()})}catch(o){return R(o)}},async set(i){try{let o=i.body;if(o==null)return A("set requires a body (card object or array of cards)");let g=Array.isArray(o)?o:[o];for(let f of g){if(typeof f.id!="string")return A("each card must have a string `id` field");await u.writeCard(f.id,f);}return b({count:g.length})}catch(o){return R(o)}},async del(i){try{let o=i.body?.ids??[],g=i.params?.id,f=g?[...o,g]:o;if(f.length===0)return A("del requires body.ids (string[]) or params.id");for(let k of f)await u.removeCard(k);return b({count:f.length})}catch(o){return R(o)}},async patch(i){try{let o=i.params?.id,g=i.params?.path;if(!o)return A("patch requires params.id");if(!g)return A("patch requires params.path");let f=i.body,k=f&&Object.prototype.hasOwnProperty.call(f,"value")?f.value:i.body;return await u.patchCard(o,g,k),b({count:1})}catch(o){return R(o)}},async appendFiles(i){try{let o=i.params?.id;if(!o)return A("appendFiles requires params.id");let g=await u.readCard(o);if(!g)return A(`card "${o}" not found`);let f=e(i.body);if(!f||f.length===0)return A("appendFiles requires a file metadata object, array, or body.files array");let k=g.card_data&&typeof g.card_data=="object"&&!Array.isArray(g.card_data)?g.card_data:{},$=Array.isArray(k.files)?k.files:[],T=[...$,...f];return await u.patchCard(o,"card_data.files",T),b({files_added:f.map((N,rt)=>({idx:$.length+rt,entry:N}))})}catch(o){return R(o)}}}}let a=nt(t.boardAdapter)?j(t.baseRef,t.boardAdapter):y(t.baseRef,t.boardAdapter),s=t.nonCoreAdapter??(!nt(t.boardAdapter)&&ft(t.boardAdapter)?t.boardAdapter:null),d$1=s?z(t.baseRef,s):null,p,m=nt(t.boardAdapter)?(()=>{let u=d(c(b$1(t.boardAdapter.kvStorageForRef(t.cardStoreRef)),t.boardAdapter.hashFn),x.warn),b=n(u);return p={get(A){return b.get(A)},set(A){return b.set(A)}},b})():(()=>{let u=t.boardAdapter.kvStorageForRef(t.cardStoreRef),A=a$1(l({readIndex:()=>u.read("_index"),writeIndex:R=>u.write("_index",R),readCard:R=>u.read(R),writeCard:(R,i)=>(u.write(R,i),R),removeCard:R=>{u.delete(R);},cardExists:R=>u.read(R)!==null,defaultCardKey:R=>R},x.warn));return p=A,r(A)})(),C=t.artifactsAdapter||t.boardAdapter,S=t.filesArtifactsStore??null,q=S?{putBytes(u,b,A){S.putBytes(u,b,A);},getBytes(u){return S.getBytes(u)},listKeys(u){return S.list(u).map(b=>b.key)}}:null;if(!q&&!nt(C)){let u=t.artifactsAdapter?C.blobStorage(""):C.blobStorage("files"),b=c$1(u);q={putBytes(A,R,i){b.putBytes(A,R,i);},getBytes(A){return b.getBytes(A)},listKeys(A){return b.list(A).map(R=>R.key)}};}else if(!q&&nt(C)){let u=t.artifactsAdapter?C.blobStorage(""):C.blobStorage("files");q={async putBytes(b,A){if(u.writeBytes){await u.writeBytes(b,A);return}let R=JSON.stringify({__kind:"bytes-array",data:[...A]});await u.write(b,R);},async getBytes(b){if(u.readBytes){let R=await u.readBytes(b);if(R!==null)return R}let A=await u.read(b);if(A===null)return null;try{let R=JSON.parse(A);if(R&&R.__kind==="bytes-array"&&Array.isArray(R.data))return new Uint8Array(R.data)}catch{}return new TextEncoder().encode(A)},async listKeys(b){return await u.listKeys(b)}};}let L={async init(u){return a.init(u)},async status(u){return a.status(u)},async getConfig(u){return a.getConfig(u)},async getAllOutputsDataObjects(u){return a.getAllOutputsDataObjects(u)},async getAllOutputsComputedValues(u){return a.getAllOutputsComputedValues(u)},async getOutputsFetchedSources(u){return a.getOutputsFetchedSources(u)},async upsertCard(u){return a.upsertCard(u)},async removeCard(u){return a.removeCard(u)},async cardRefreshedNotify(u){return a.cardRefreshedNotify(u)},async sourceDataFetched(u){return a.sourceDataFetched(u)},async sourceDataFetchFailure(u){return a.sourceDataFetchFailure(u)}};return {label:t.label,board:a,nonCore:d$1,publicCardStore:p,boardOps:L,cardStoreOps:m,get filesArtifacts(){return q},boardAdapter:t.boardAdapter,cardStoreRef:t.cardStoreRef,outputsStoreRef:t.outputsStoreRef,artifactsStoreRef:t.artifactsStoreRef,scratchStoreRef:t.scratchStoreRef,archiveStoreRef:t.archiveStoreRef,notifyRef:t.notifyRef,taskExecutorRef:t.taskExecutorRef,chatHandlerRef:t.chatHandlerRef,chatHandlerFlow:t.chatHandlerFlow,inferenceAdapterRef:t.inferenceAdapterRef,notification:Ie(),notificationTeardown:null,initialized:false,cardsBootstrapped:false}}let j$1=c$2.boards.map(Z),U=new Map;function X(t){return U.get(t)??0}function ft(t){let e=t;return typeof e.invokeExecutor=="function"&&typeof e.validateSchema=="function"}function yt(t){let e=j$1[X(t)];return {files:e?e.filesArtifacts:null}}function Y(){return e()}function tt(t){return String(t||"").replace(/[^a-zA-Z0-9_-]/g,"_")||"unknown-card"}async function pt(t){if(!t||t.notificationTeardown||!ot||!t.notifyRef)return;let e=await ot.subscribe(t.notifyRef,r=>{Dt(t.notification,r);let n=r.kind==="notification-batch"?r.notifications:[r];le(n);});t.notificationTeardown=e;}async function Ee(t){if(!t||t.initialized)return;let e={cardStoreRef:t.cardStoreRef,outputsStoreRef:t.outputsStoreRef};t.artifactsStoreRef&&(e.artifactsStoreRef=t.artifactsStoreRef),t.scratchStoreRef&&(e.scratchStoreRef=t.scratchStoreRef),t.archiveStoreRef&&(e.archiveStoreRef=t.archiveStoreRef);let r={};t.taskExecutorRef&&(r["task-executor-ref"]=t.taskExecutorRef),t.chatHandlerFlow!==void 0&&(r["chat-handler-flow"]=t.chatHandlerFlow),t.inferenceAdapterRef&&(r["inference-adapter-ref"]=t.inferenceAdapterRef);let n=await t.boardOps.init({params:e,body:r});if(n.status!=="success")throw Object.assign(new Error(n.error||`init failed for ${t.label}`),{statusCode:500});if(await pt(t),!t.chatHandlerFlow&&t.chatHandlerRef&&I.describe)try{let a=await I.describe(t.chatHandlerRef);a&&a.kind!=="chat-handler"?x.warn(`[init] chat-handler describe returned kind="${a.kind}", expected "chat-handler" for ${t.label}`):a&&x.info(`[init] chat-handler validated: ${a.name} (protocol ${a.protocolVersion}) for ${t.label}`);}catch(a){x.warn(`[init] chat-handler describe failed for ${t.label}: ${a?.message||String(a)}`);}t.initialized=true;}async function wt(t){if(!t.boardAdapter.publishBoardChangeNotifications)return;let e=[],r=await t.boardOps.status({});r.status==="success"&&r.data!=null&&Nt(r.data)&&e.push({kind:"status",status:r.data});let n=await t.boardOps.getAllOutputsDataObjects({});if(n.status==="success"&&n.data!=null)for(let[s,d]of Object.entries(n.data))s&&e.push({kind:"data_object",key:s,payload:d});let a=await t.boardOps.getAllOutputsComputedValues({});if(a.status==="success"&&a.data!=null)for(let[s,d]of Object.entries(a.data))s&&e.push({kind:"computed_values",cardId:s,values:d});e.length>0&&t.boardAdapter.publishBoardChangeNotifications(e);}async function Ht(t,e){if(!t||t.cardsBootstrapped)return;let r=await t.cardStoreOps.get({}),n=r.status==="success"&&Array.isArray(r.data?.cards)?r.data.cards:[];for(let a of n)typeof a.id=="string"&&(U.set(a.id,e),await t.boardOps.upsertCard({params:{cardId:a.id}}));t.cardsBootstrapped=true;}async function ct(){for(let t of j$1)await Ee(t);}async function H(){await ct();for(let t=0;t<j$1.length;t++)await wt(j$1[t]),await Ht(j$1[t],t),await wt(j$1[t]);}async function xt(t=false){t||await ct();for(let e of j$1){let r=await e.board.processAccumulatedEvents({});if(r.status!=="success")return r}return {status:"success"}}async function $e(){return await ct(),xt(true)}function Q(t){return j$1[X(t)]??null}async function dt(t){let e=Q(t);if(!e)return null;let r=await e.cardStoreOps.get({params:{id:t}});if(r.status!=="success")return null;let n=Array.isArray(r.data?.cards)?r.data.cards:[];return n.length>0?n[0]:null}async function Qt(){let t=async r=>{if(!r)return [];let n=await r.cardStoreOps.get({});return n.status!=="success"||!Array.isArray(n.data?.cards)?[]:n.data.cards},e=[];for(let r of j$1)e.push(...await t(r));return e}function J(){return j$1[0]??null}function Fe(){return {async status(){let t=await Zt();return t==null?{status:"fail",error:"Board status is unavailable"}:{status:"success",data:t}},async getOutputsDataObject(t){let e=t?.params?.key;return e?{status:"success",data:(await Yt())[e]}:{status:"fail",error:"getOutputsDataObject requires params.key"}},async getOutputsComputedValues(t){let e=t?.params?.key;return e?{status:"success",data:(await Xt())[e]?.computed_values}:{status:"fail",error:"getOutputsComputedValues requires params.key"}},async getOutputsFetchedSources(t){let e=t?.params?.key;if(!e)return {status:"fail",error:"getOutputsFetchedSources requires params.key"};let r=Q(e)??J();return r?r.boardOps.getOutputsFetchedSources({params:{key:e}}):{status:"fail",error:"Board context is unavailable"}},async removeCard(t){let e=t?.params?.id;if(!e)return {status:"fail",error:"removeCard requires params.id"};let r=Q(e)??J();return r?r.boardOps.removeCard({params:{id:e}}):{status:"fail",error:"Board context is unavailable"}},async cardRefreshedNotify(t){let e=t?.params?.cardId;if(!e)return {status:"fail",error:"cardRefreshedNotify requires params.cardId"};let r=Q(e)??J();return r?r.boardOps.cardRefreshedNotify({params:{cardId:e}}):{status:"fail",error:"Board context is unavailable"}},async upsertCard(t){let e=t?.params?.cardId;if(!e)return {status:"fail",error:"upsertCard requires params.cardId"};let r=Q(e)??J();if(!r)return {status:"fail",error:"Board context is unavailable"};let n=await r.boardOps.upsertCard({params:{cardId:e,restart:t.params.restart===true}});if(n.status!=="success")return n;if(nt(r.boardAdapter)){let a=await xt(true);if(a.status!=="success")return a}return n}}}function qe(){let t=()=>{let e=J();if(!e?.nonCore)throw new Error("Board non-core adapter is not configured for MCP preflight/discovery tools");return e.nonCore};return {describeTaskExecutorCapabilities(e){return t().describeTaskExecutorCapabilities(e)},validateCardPreflight(e){return t().validateCardPreflight(e)},evalCardCompute(e){return t().evalCardCompute(e)},probeSourcePreflight(e){return t().probeSourcePreflight(e)},runSourcePreflight(e){return t().runSourcePreflight(e)},simulateCardCycle(e){return t().simulateCardCycle(e)}}}function bt(){return {async get(t){let e=typeof t.params?.id=="string"?t.params.id:void 0;if(e){let r=await dt(e);return r?{status:"success",data:{cards:[r]}}:{status:"success",data:{cards:[]}}}return {status:"success",data:{cards:await Qt()}}},async set(t){let e=t.body;if(e==null)return {status:"fail",error:"set requires a body (card object or array of cards)"};let r=Array.isArray(e)?e:[e];for(let n of r){let a=n,s=typeof a.id=="string"?a.id:"";if(!s)return {status:"fail",error:"each card must have a string `id` field"};let d=U.get(s)??0,p=j$1[d]??J();if(!p)return {status:"fail",error:"Board context is unavailable"};let m=await p.cardStoreOps.set({body:a});if(m.status!=="success")return m;U.set(s,d);}return {status:"success",data:{count:r.length}}},async del(t){let e=[t.params?.id,...t.body?.ids??[]].filter(r=>typeof r=="string"&&!!r);if(e.length===0)return {status:"fail",error:"del requires body.ids (string[]) or params.id"};for(let r of e){let n=Q(r)??J();if(!n)return {status:"fail",error:"Board context is unavailable"};let a=await n.cardStoreOps.del({params:{id:r}});if(a.status!=="success")return a;U.delete(r);}return {status:"success",data:{count:e.length}}},async patch(t){let e=typeof t.params?.id=="string"?t.params.id:void 0,r=typeof t.params?.path=="string"?t.params.path:void 0;if(!e||!r)return {status:"fail",error:"patch requires params.id and params.path"};let n=Q(e)??J();return n?n.cardStoreOps.patch(t):{status:"fail",error:"Board context is unavailable"}},async appendFiles(t){let e=typeof t.params?.id=="string"?t.params.id:void 0;if(!e)return {status:"fail",error:"appendFiles requires params.id"};let r=Q(e)??J();return r?r.cardStoreOps.appendFiles(t):{status:"fail",error:"Board context is unavailable"}}}}function et(){return a$2({board:Fe(),nonCore:qe(),cardStore:bt(),chatStore:W,uploadCardFile({cardId:t,fileName:e,contentType:r,bytes:n}){return Tt(t,e,r,n,{inChat:false})},buildFileDownloadUrl({cardId:t,fileIdx:e,storedName:r}){let n=`${z$1||""}${l$1}/cards/${encodeURIComponent(t)}/files/${e}`;return r?`${n}?sn=${encodeURIComponent(r)}`:n},readFetchedSourceJsonByRef({cardId:t,ref:e}){let r=Q(t)??J();if(!r||nt(r.boardAdapter))return null;let a=r.boardAdapter.resolveBlob(b$2(e)).trim();return a?JSON.parse(a):null}})}function Vt(t,e){let r=E(t,"board_id"),n=E(t,"card_id");if(!r)throw Object.assign(new Error("MCP tool requires board_id"),{statusCode:400});if(!n)throw Object.assign(new Error("MCP tool requires card_id"),{statusCode:400});if(r!==h)throw Object.assign(new Error(`Unknown board_id: ${r}`),{statusCode:400});return et().setChatProcessing({cardId:n,active:e}),{status:"success",data:{boardId:h,cardId:n,active:e}}}function ht(t){let e=E(t,"board_id"),r=E(t,"card_id");if(!e)throw Object.assign(new Error("MCP tool requires board_id"),{statusCode:400});if(!r)throw Object.assign(new Error("MCP tool requires card_id"),{statusCode:400});if(e!==h)throw Object.assign(new Error(`Unknown board_id: ${e}`),{statusCode:400});return {cardId:r}}function Wt(t,e){if(t?.status==="success")return Object.prototype.hasOwnProperty.call(t,"data")?t.data:void 0;throw t?.status==="fail"||t?.status==="error"?Object.assign(new Error(t.error||`${e} failed`),{statusCode:400}):Object.assign(new Error(`${e} returned an unexpected response`),{statusCode:500})}async function zt(t,e){return Wt(await t,e)}function Jt(t){let e=E(t,"key");if(!e)throw Object.assign(new Error("MCP tool requires key"),{statusCode:400});let r=e.split(".");if(!(r.length>=2&&r[0]==="chat"&&r.every(a=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(a))))throw Object.assign(new Error("MCP tool only supports card meta keys under chat.*"),{statusCode:400});return e}function Kt(t,e){let r=t.meta;for(let n of e.split(".")){if(!r||typeof r!="object"||Array.isArray(r)||!Object.prototype.hasOwnProperty.call(r,n))return {exists:false,value:null};r=r[n];}return {exists:true,value:r}}function Me(t){let{cardId:e}=ht(t),r=et().getChatProcessing({cardId:e});return {status:"success",data:{boardId:h,cardId:e,active:r.active}}}async function Le(t){let{cardId:e}=ht(t),r=Jt(t);if(!Object.prototype.hasOwnProperty.call(t,"value"))throw Object.assign(new Error("MCP tool requires value"),{statusCode:400});if(r.split(".").includes("__visible_controlplane_only")){let n=await zt(bt().get({params:{id:e}}),"cardStore.get"),a=Array.isArray(n.cards)&&n.cards.length>0&&typeof n.cards[0]=="object"&&!Array.isArray(n.cards[0])?n.cards[0]:null,s=a?Kt(a,"__visible_controlplane_only").value:void 0;if(t.value!==s)throw Object.assign(new Error("MCP tool cannot change the reserved meta flag __visible_controlplane_only"),{statusCode:403});return {status:"success",data:{boardId:h,cardId:e,key:r}}}return Wt(await bt().patch({params:{id:e,path:`meta.${r}`},body:{value:t.value}}),"cardStore.patch"),{status:"success",data:{boardId:h,cardId:e,key:r}}}async function Ne(t){let{cardId:e}=ht(t),r=Jt(t),n=await zt(bt().get({params:{id:e}}),"cardStore.get"),a=Array.isArray(n.cards)&&n.cards.length>0&&n.cards[0]&&typeof n.cards[0]=="object"&&!Array.isArray(n.cards[0])?n.cards[0]:null;if(!a)throw Object.assign(new Error(`Card "${e}" not found`),{statusCode:404});let s=Kt(a,r);return {status:"success",data:{boardId:h,cardId:e,key:r,exists:s.exists,value:s.value}}}function De(t){return {"discover.source-kinds":()=>t.discoverSourceKinds(),"inspect.board-runtime-status":()=>t.inspectBoardRuntimeStatus(),"inspect.card-definition-and-runtime":e=>t.inspectCardDefinitionAndRuntime({cardId:E(e,"card_id")}),"inspect.chat-messages-on-cards":e=>{let r=at(e,"tail_turns"),n=at(e,"tail"),a=E(e,"turn_id"),s=e.all_turns===true,d=E(e,"tail_turns_before_id");return t.inspectChatMessagesOnCards({cardId:E(e,"card_id"),...r!==void 0?{lastUserTurns:r}:{},...n!==void 0?{tail:n}:{},...a?{turnId:a}:{},...s?{allTurns:true}:{},...d?{tailTurnsBeforeId:d}:{}})},"inspect.file-contents":e=>t.inspectFileContents({cardId:E(e,"card_id"),fileIdx:Number(at(e,"file_idx"))}),"preflight.validate-candidate-card-definition":e=>t.preflightValidateCandidateCardDefinition({candidateCardContent:st(e,"candidate_card_content","candidate_card_content")}),"preflight.materialize-candidate-card":e=>t.preflightMaterializeCandidateCard({candidateCardContent:st(e,"candidate_card_content","candidate_card_content"),mockRequires:st(e,"mock_requires","mock_requires"),mockFetchedSources:st(e,"mock_fetched_sources","mock_fetched_sources")}),"preflight.probe-single-source-in-candidate-card":e=>t.preflightProbeSingleSourceInCandidateCard({candidateCardContent:st(e,"candidate_card_content","candidate_card_content"),mockProjections:lt(e,"mock_projections"),sourceIdx:_t(e,"source_idx","source_idx")}),"preflight.run-single-source-in-candidate-card":e=>t.preflightRunSingleSourceInCandidateCard({candidateCardContent:st(e,"candidate_card_content","candidate_card_content"),mockProjections:lt(e,"mock_projections"),sourceIdx:_t(e,"source_idx","source_idx")}),"preflight.run-single-source-in-live-card":e=>t.preflightRunSingleSourceInLiveCard({cardId:E(e,"card_id"),sourceIdx:_t(e,"source_idx","source_idx"),mockRequires:st(e,"mock_requires","mock_requires")}),"preflight.run-one-cycle-with-candidate-card":e=>t.preflightRunOneCycleWithCandidateCard({candidateCardContent:st(e,"candidate_card_content","candidate_card_content"),mockRequires:lt(e,"mock_requires")}),"manage.read-card":e=>t.manageReadCard({cardId:E(e,"card_id")}),"stage-ai-response-and-any-attachments":e=>{let r=E(e,"turn_id");if(!r)throw Object.assign(new Error("stage-ai-response-and-any-attachments requires a non-empty turn_id"),{statusCode:400});return t.manageAddChatEntryAndAnyAttachments({cardId:E(e,"card_id"),role:"assistant",...typeof e.text=="string"?{text:e.text}:{},...r?{turn:r}:{},...Array.isArray(e.files)?{files:e.files}:{}})},"manage.upsert-card":e=>t.manageUpsertCard({cardId:E(e,"card_id"),candidateCardContent:lt(e,"candidate_card_content")}),"manage.remove-card":e=>t.manageRemoveCard({cardId:E(e,"card_id")})}}function Ue(){return {"getstate.is-chat-processing":t=>Me(t),"setstate.chat-processing-started":t=>Vt(t,true),"setstate.chat-processing-done":t=>Vt(t,false),"getstate.card-meta":t=>Ne(t),"setstate.card-meta":t=>Le(t),"manage.upload-card-file":t=>{let e=E(t,"board_id"),r=E(t,"card_id"),n=E(t,"file_name"),a=E(t,"content_type")||"application/octet-stream",s=xe(t);if(!e)throw Object.assign(new Error("manage.upload-card-file requires board_id"),{statusCode:400});if(e!==h)throw Object.assign(new Error(`Unknown board_id: ${e}`),{statusCode:400});if(!r)throw Object.assign(new Error("manage.upload-card-file requires card_id"),{statusCode:400});if(!n)throw Object.assign(new Error("manage.upload-card-file requires file_name"),{statusCode:400});if(!s)throw Object.assign(new Error("manage.upload-card-file requires args.bytes, args.text, or args.base64"),{statusCode:400});return Tt(r,n,a,s,{inChat:false})},"manage.admin-read-card":async t=>{let{cardId:e}=ht(t);return {status:"success",data:{cards:await et().adminReadCard({cardId:e})}}},"manage.admin-upsert-card":t=>{let e=E(t,"board_id"),r=E(t,"card_id");if(!e)throw Object.assign(new Error("manage.admin-upsert-card requires board_id"),{statusCode:400});if(!r)throw Object.assign(new Error("manage.admin-upsert-card requires card_id"),{statusCode:400});if(e!==h)throw Object.assign(new Error(`Unknown board_id: ${e}`),{statusCode:400});return et().adminUpsertCard({cardId:r,candidateCardContent:lt(t,"candidate_card_content")})}}}async function Gt(t,e,r){let n=r[t];if(!n)throw Object.assign(new Error(`Unknown MCP tool: ${t}`),{statusCode:400});let a=await n(e);if(a&&typeof a=="object"&&!Array.isArray(a)){let s=a,d=s.status;if(d==="success")return Object.prototype.hasOwnProperty.call(s,"data")?a:{status:"success",data:{}};if(d==="fail"||d==="error")return a}return {status:"success",data:a}}function Rt(t,e){if(!t||typeof t!="object"||Array.isArray(t))return e;let r=t;if(typeof r.error=="string"&&r.error.trim())return r.error;if(r.step==="validate"){let n=r.validation;if(n&&typeof n=="object"&&!Array.isArray(n)){let s=n.data;if(s&&typeof s=="object"&&!Array.isArray(s)){let d=s.issues;if(Array.isArray(d)){let m=d.find(C=>typeof C=="string"&&C.trim());if(typeof m=="string")return `Validation failed: ${m}`}let p=s.errors;if(Array.isArray(p)&&p.length>0)return "Validation failed"}}return "Validation failed"}return e}async function Zt(){let t=(await Promise.all(j$1.map(async s=>{try{let d=s.boardAdapter.kvStorageForRef(s.outputsStoreRef),p=await Promise.resolve(d.read("status"));if(p!=null)return p}catch{}return s.notification.status}))).filter(Boolean);if(t.length===0)return null;if(t.length===1)return t[0];let e=[],r=["completed","eligible","pending","blocked","unresolved","failed","in_progress","orphan_cards"],n={};for(let s of r)n[s]=0;for(let s of t){let d=s,p=Array.isArray(d.cards)?d.cards:[];e.push(...p);for(let m of r)n[m]+=Number(d?.summary?.[m]||0);}let a=t[0];return {...a,cards:e,summary:{...a.summary||{},card_count:e.length,...n}}}async function Xt(){let t={},e=async r=>{try{let n=await r.boardOps.getAllOutputsComputedValues({});if(n.status==="success"&&n.data&&typeof n.data=="object"){for(let[a,s]of Object.entries(n.data)){let d=r.notification.cards[a];t[a]={schema_version:"v1",card_id:a,card_data:d?.card_data??{},computed_values:s??{}};}return}}catch{}for(let[n,a]of Object.entries(r.notification.computedValues)){let s=r.notification.cards[n];t[n]={schema_version:"v1",card_id:n,card_data:s?.card_data??{},computed_values:a??{}};}};for(let r of j$1)await e(r);return t}async function Yt(){let t={};for(let e of j$1){try{let r=await e.boardOps.getAllOutputsDataObjects({});if(r.status==="success"&&r.data&&typeof r.data=="object"){Object.assign(t,r.data);continue}}catch{}Object.assign(t,e.notification.dataObjects||{});}return t}async function Ct(){let t=await Qt(),e=await Xt(),r=await Yt(),n={};for(let s of t){if(!s?.id)continue;let d=s.id,p=e[d]||{},m={...p.card_data&&typeof p.card_data=="object"?p.card_data:s.card_data&&typeof s.card_data=="object"?s.card_data:{}};n[d]={schema_version:p.schema_version||"v1",card_id:p.card_id||d,card_data:m,computed_values:p.computed_values&&typeof p.computed_values=="object"?p.computed_values:{}};}let a={};for(let s of t){if(!s?.id)continue;let d=s.id;try{let p=jt(d),m=et().getChatProcessing({cardId:d}).active;(p.length>0||m)&&(a[d]={messages:p.map(C=>({role:String(C.role||"system"),text:String(C.text||""),files:Array.isArray(C.files)?C.files:[]})),receiving:!1,processing:m});}catch{}}return {boardId:h,cardDefinitions:t,statusSnapshot:await Zt(),dataObjectsByToken:r,cardRuntimeById:n,cardChatsByCardId:a}}async function Pt(t,e,r){let n=r?.syncBoard!==false,a=r?.restartOnlyIfChanged===true,s=Q(t);if(!s)throw Object.assign(new Error(`Card not found: ${t}`),{statusCode:404});let d=await dt(t);if(!d)throw Object.assign(new Error(`Card not found: ${t}`),{statusCode:404});let p=a?JSON.stringify(d):null,m=e(d)||d;if(a&&JSON.stringify(m)===p)return;let C=await s.cardStoreOps.set({body:m});if(C.status!=="success")throw Object.assign(new Error(C.error||`Failed to persist card: ${t}`),{statusCode:500});if(n){let S=await s.boardOps.upsertCard({params:{cardId:t,restart:true}});if(S.status!=="success")throw Object.assign(new Error(S.error||`Failed to upsert card: ${t}`),{statusCode:500})}}async function He(t,e){await Pt(t,e,{syncBoard:true});}async function te(t,e){await Pt(t,e,{syncBoard:false});}async function Qe(t){let e=Q(t);if(!e)throw Object.assign(new Error(`Card not found: ${t}`),{statusCode:404});if(!await dt(t))throw Object.assign(new Error(`Card not found: ${t}`),{statusCode:404});let n=await e.boardOps.upsertCard({params:{cardId:t,restart:true}});if(n.status!=="success")throw Object.assign(new Error(n.error||`Failed to retrigger card: ${t}`),{statusCode:500})}async function Ve(t,e){await Pt(t,r=>{if(!e||typeof e!="object"||Object.keys(e).length===0)return r;function n(a,s,d){let p=String(s||"").split(".").filter(Boolean);if(!p.length)return;let m=a;for(let C=0;C<p.length-1;C++){let S=p[C];(!m[S]||typeof m[S]!="object")&&(m[S]={}),m=m[S];}m[p[p.length-1]]=d;}if(e.fieldValues!==void 0&&e.fieldValues!==null){let a=null,s=r.view;if(s&&Array.isArray(s.elements)){for(let d of s.elements)if(d?.data&&d.data.writeTo){a=d.data.writeTo;break}}a?n(r,a,e.fieldValues):typeof e.fieldValues=="object"&&!Array.isArray(e.fieldValues)&&(r.card_data={...r.card_data||{},...e.fieldValues});}else {if(Array.isArray(e._stagedFiles)&&e._stagedFiles.length>0)return r;for(let[a,s]of Object.entries(e))a!=="_stagedFiles"&&(s!==null&&typeof s=="object"&&!Array.isArray(s)&&r[a]!==null&&typeof r[a]=="object"&&!Array.isArray(r[a])?r[a]={...r[a],...s}:r[a]=s);}return r},{syncBoard:true,restartOnlyIfChanged:true});}function We(t){let e=String(t||"").trim();if(!e)return "upload.bin";let r=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return (r>=0?e.slice(r+1):e)||"upload.bin"}function ze(t){P.clear(t);try{et().setChatProcessing({cardId:t,active:!1});}catch{}}function Je(t,e,r,n,a=""){let s=typeof r=="string"?r.trim():"";return P.append(t,e,s,n,a)}function jt(t){return P.readAll(t)}async function Ke(t){let e=[];try{let r=await dt(t);if(!r)return e;let n=Y().read(r.card_data&&typeof r.card_data=="object"?r.card_data:null);for(let a of n)e.push(a.stored_name);}catch{}return e}async function Ge(t,e,r,n){let a=tt(t),s=yt(t),d=We(e),p=await Ke(t),C=`${String(p.length+1).padStart(3,"0")}-${d}`.slice(-36);return s.files&&await s.files.putBytes(`${a}/${C}`,new Uint8Array(n),r||"application/octet-stream"),{name:d,stored_name:C,size:n.length,mime_type:r||"application/octet-stream",uploaded_at:new Date().toISOString()}}async function Tt(t,e,r,n,a){if(!n.length)throw Object.assign(new Error("Empty upload body"),{statusCode:400});let s=a?.inChat===true,d=await Ge(t,e,r,n),p=null;if(await te(t,m=>{let C=new Date().toISOString(),S=m.card_data&&typeof m.card_data=="object"?m.card_data:{};m.card_data=S;let q=Y().normalizeIncoming([{name:d.name,stored_name:d.stored_name,size:d.size,mime_type:d.mime_type,uploaded_at:d.uploaded_at||C,chat:s}],C);return p=Y().merge(S,q).findIndex(u=>u.stored_name===d.stored_name),m}),s){let m=typeof p=="number"&&p>=0?` #${p}`:"";Je(t,"system",`file uploaded: ${d.name} as ${d.stored_name}${m}`,[],a?.turnId??"");}return {ok:true,file:d}}async function ee(t){let e=Q(t);if(!e)return null;let r=await e.boardOps.getConfig({params:{key:"chat-handler-flow"}}),n=r.status==="success"?r.data?.value:null,a=e.chatHandlerRef;return n==null&&(!a||typeof a!="object")?null:{ctx:e,handlerFlow:n,handlerRef:a}}async function Ze(t,e,r=false,n=""){let a=await ee(t);if(!a)return;let{ctx:s,handlerFlow:d,handlerRef:p}=a;if(!r)try{et().setChatProcessing({cardId:t,active:!0});}catch{}let m={boardId:h,cardId:String(t),lastChatEntryId:e,...n?{turnId:n}:{},...mt,...z$1?{serverUrl:z$1}:{}},C=d!=null?{meta:"chat-handler-flow",howToRun:"built-in",whatToRun:{kind:"built-in",value:je}}:p;try{nt(s.boardAdapter)?await s.boardAdapter.chatAgentStore().enqueueRequest({boardId:h,ref:C,args:d!=null?{...m,__chatHandlerFlow:d}:m}):s.boardAdapter.chatAgentStore().enqueueRequest({boardId:h,ref:C,args:d!=null?{...m,__chatHandlerFlow:d}:m}),await Promise.resolve(s.boardAdapter.requestProcessAccumulated?.());}catch(S){try{et().setChatProcessing({cardId:t,active:!1});}catch{}x.warn(`[chat-handler] queue failed for card "${t}": ${S instanceof Error?S.message:String(S)}`);}}async function Xe(t,e,r){if(e.howToRun==="built-in"&&Oe(e)===je){let n=O,a=r.__chatHandlerFlow,s={...r};return delete s.__chatHandlerFlow,n?n.run(a,s,{boardId:h,cardId:String(s.cardId||""),label:t.label,logger:x,serverUrl:z$1,executionExtra:mt}):{dispatched:false,error:"chat-handler-flow configured but no chatFlowRunner was provided"}}return I.invoke(e,r)}async function Ye(t,e=false){e||await ct();let r=typeof t.args?.cardId=="string"?t.args.cardId:"",n=r?Q(r):J();if(!n)throw new Error(r?`Board context is unavailable for chat-agent request: ${r}`:"Board context is unavailable for chat-agent request");let a=await Xe(n,t.ref,t.args);if(!a.dispatched){if(r)try{P.setProcessing(r,!1);}catch{}throw new Error(a.error||`chat-agent dispatch failed for card "${r||"unknown"}"`)}}async function tr(t,e,r){let n=e==="chat-send"?te:He,a;await n(t,s=>{let d=new Date().toISOString(),p=s.card_data&&typeof s.card_data=="object"?s.card_data:{};if(s.card_data=p,e==="chat-send"){let m=r&&typeof r.text=="string"?r.text.trim():"",C=r&&typeof r["turn-id"]=="string"?r["turn-id"]:r&&typeof r.turnId=="string"?r.turnId:r&&typeof r.turn=="string"?r.turn:"",S=[];if(Array.isArray(r?.files)){for(let q of r.files)if(q){if(typeof q=="string"){S.push({name:q});continue}if(typeof q=="object"){let L=q;typeof L.name=="string"&&S.push({name:L.name,size:L.size,mime_type:L.mime_type,uploaded_at:L.uploaded_at,stored_name:L.stored_name,chat:L.chat===true});}}}if(m||S.length>0){let q=W.runBatch({cardId:t,commands:[{command:"append",role:"user",text:m,files:S,turn:C},{command:"set-processing",active:true}]});if(q.status!=="success")throw new Error(q.error);let L=q.data.results[0]?.data?.id;if(typeof L!="string"||!L)throw new Error(`chat-send did not return an append id for card ${t}`);a={cardId:t,lastEntryId:L,processingAlreadySet:true,turnId:C};try{let A=jt(t);le([{kind:"card_chats",cardId:t,messages:A.map(R=>({role:String(R.role||"system"),text:String(R.text||""),files:Array.isArray(R.files)?R.files:[]})),receiving:!0,processing:P.isProcessing(t)}]);}catch{}}return s}if(e==="file-upload"){let m=Y().normalizeIncoming(r?.files,d);return m.length>0&&Y().merge(p,m),s}if(e==="action"){let m=r&&typeof r.buttonId=="string"?r.buttonId:"";if(!m)return s;p.lastAction={buttonId:m,at:d},p.lastActionText=`${m} @ ${d}`;}return s}),a&&Ze(a.cardId,a.lastEntryId,a.processingAlreadySet,a.turnId??"");}function w(t,e,r){let n=JSON.stringify(r),a=typeof Buffer<"u"?Buffer.byteLength(n):new TextEncoder().encode(n).length;t.writeHead(e,{...y$1,"Content-Type":"application/json; charset=utf-8","Content-Length":a}),t.end(n);}async function re(t,e,r){let n=await dt(t);if(!n)throw Object.assign(new Error("Card not found"),{statusCode:404});let a=Y().resolve(n.card_data,e,r);if(!a.ok&&a.reason==="stale_reference")throw Object.assign(new Error("File reference is stale. Refresh and try again."),{statusCode:409});if(!a.ok)throw Object.assign(new Error("File not found"),{statusCode:404});let s=a.file,d=tt(t),p=yt(t),m=String(s.stored_name||""),C=`${d}/${m}`,S=p.files?await p.files.getBytes(C):null;if(!S)throw Object.assign(new Error("File not found"),{statusCode:404});return {fileRecord:s,bytes:S}}async function er(t,e,r,n){let{fileRecord:a,bytes:s}=await re(e,r,n),d=String(a.name||a.stored_name||"download.bin"),p=String(a.mime_type||"application/octet-stream");t.writeHead(200,{"Content-Type":p,"Content-Disposition":`attachment; filename="${d}"`,"Content-Length":s.length}),t.end(s);}function rr(t){let e=String(t||"").toLowerCase();return e.startsWith("text/")||e.includes("json")||e.includes("xml")||e.includes("javascript")||e.includes("typescript")||e.includes("yaml")||e.includes("csv")}function ne(t,e,r){let n=t.split(/\r?\n/);return (e==="head"?n.slice(0,r):n.slice(-r)).join(`
|
|
2
|
+
`)}async function K(t){let e=[];for await(let n of t)e.push(n);let r=typeof Buffer<"u"?Buffer.concat(e).toString("utf-8").trim():new TextDecoder().decode(vt(e)).trim();return r?JSON.parse(r):{}}async function nr(t){let e=[];for await(let r of t)e.push(r);return typeof Buffer<"u"?Buffer.concat(e):vt(e)}async function ae(t,e){let r=typeof e.ref=="string"?e.ref.trim():"";if(!r)return {status:"fail",error:"board-worker success callback requires body.ref"};let n=j$1[0];return n?n.boardOps.sourceDataFetched({params:{token:t,ref:r}}):{status:"fail",error:"no board context"}}async function se(t,e){let r=typeof e.reason=="string"&&e.reason.trim()?e.reason:"unknown",n=j$1[0];return n?n.boardOps.sourceDataFetchFailure({params:{token:t,reason:r}}):{status:"fail",error:"no board context"}}async function ar(t,e,r){let n=String(t||"").trim();if(!n)return {statusCode:400,body:{error:"callback token is required"}};let a=e==="success"?await ae(n,r):await se(n,r);return a.status==="success"?{statusCode:200,body:a}:a.status==="fail"?{statusCode:400,body:{error:a.error}}:{statusCode:500,body:{error:a.error}}}let oe=0;function ie(t){let e=JSON.stringify(t);return oe++,`id: ${oe}
|
|
3
|
+
data: ${e}
|
|
4
|
+
|
|
5
|
+
`}function ce(t){let e=t;try{e.flushHeaders?.();}catch{}try{e.flush?.();}catch{}try{e.socket?.setNoDelay?.(!0);}catch{}try{e.socket?.uncork?.();}catch{}}function Et(t,e){let r=v.get(t);if(r&&!(e&&r.res!==e)){v.delete(t),qt();try{It?.(t);}catch{}try{r.res.end();}catch{}}}function kt(t,e){let r=v.get(t);if(!r)return;let n=ie(e);try{r.res.write(n),ce(r.res);}catch{Et(t,r.res);}}function de(t,e,r,n,a){if(!v.has(e)){w(t,404,{error:`SSE client not connected: ${e}`});return}a?Ot?.(e,r,n):B?.(e,r,n),w(t,200,{ok:true,clientId:e,channelName:r,...n.cardId?{cardId:n.cardId}:{},subscribed:a});}function $t(){let t=new Set;for(let e of v.values())for(let r of e.subscribedChatCardIds)t.add(r);return Array.from(t)}function sr(t){let e=F.has(t)?F.get(t):null,{cursor:r}=P.readAfter(t,e),n=P.isProcessing(t),a=n!==(M.get(t)??false),s=r!==e;return s&&F.set(t,r),M.set(t,n),s||a}function ue(t,e=true){let r=jt(t),n=Date.now();return {kind:"card_chats",cardId:t,sentAt:new Date(n).toISOString(),sentAtMs:n,messages:r.map(a=>({role:String(a.role||"system"),text:String(a.text||""),files:Array.isArray(a.files)?a.files:[]})),receiving:e,processing:P.isProcessing(t)}}function Ft(t,e=true){let r={kind:"notification-batch",notifications:[ue(t,e)]};for(let[n,a]of v.entries())a.subscribedChatCardIds.has(t)&&kt(n,r);}function qt(){$t().length>0||(D&&(clearInterval(D),D=null),F.clear(),M.clear());}function or(){if(D)return;let t=()=>{let e=$t();if(e.length===0){qt();return}let r=new Set(e);for(let n of Array.from(F.keys()))r.has(n)||F.delete(n);for(let n of Array.from(M.keys()))r.has(n)||M.delete(n);for(let n of e)sr(n)&&Ft(n,true);};t(),D=setInterval(t,1e3);}function ir(t,e){let r=v.get(t);if(!r)return false;r.subscribedChatCardIds.add(e);let{cursor:n}=P.readAfter(e,null);return F.set(e,n),M.set(e,P.isProcessing(e)),or(),kt(t,{kind:"notification-batch",notifications:[ue(e,true)]}),true}function cr(t,e){let r=v.get(t);return r?(r.subscribedChatCardIds.delete(e),$t().includes(e)||(F.delete(e),M.delete(e)),qt(),true):false}function dr(t){if(!t||typeof t!="object")return false;let e=t.kind;return e==="card_chats"||e==="chat_messages"}function le(t){if(!t||t.length===0)return;let e=[],r=new Set;for(let n of t)dr(n)&&typeof n.cardId=="string"?r.add(String(n.cardId)):e.push(n);if(e.length>0){let n={kind:"notification-batch",notifications:e};for(let a of v.keys())kt(a,n);}for(let n of r)Ft(n,true);}async function ur(t,e,r){let n=v.get(r),a=n?new Set(n.subscribedChatCardIds):new Set;n&&Et(r,n.res),e.writeHead(200,{...y$1,"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),ce(e),v.set(r,{res:e,subscribedChatCardIds:a});let s=await Ct(),d=ie(s);e.write(d);try{Bt?.(r,m=>{kt(r,m);});}catch{}let p=setInterval(()=>{try{e.write(`: keepalive
|
|
6
|
+
|
|
7
|
+
`);}catch{}},15e3);t.on("close",()=>{clearInterval(p),Et(r,e);});}async function lr(t,e,r){let n=t.method||"GET",a=r,s=a.pathname;try{if(n==="GET"&&s===`${l$1}/init-board`)return await ct(),w(e,200,await Ct()),!0;if(n==="GET"&&s===`${l$1}/sse`){await ct();let i=String(a.searchParams.get("clientId")||"").trim();if(!i)return w(e,400,{error:"clientId query param is required for SSE"}),!0;await ur(t,e,i);for(let o=0;o<j$1.length;o++)await wt(j$1[o]),await Ht(j$1[o],o),await wt(j$1[o]);return !0}if(n==="GET"&&s===`${l$1}/board-status`)return w(e,200,await Ct()),!0;let d=s.match(new RegExp(`^${V(l$1)}/callback/board-worker/([^/]+)/(success|failure)$`));if(n==="POST"&&d){await ct();let i=decodeURIComponent(d[1]),o=d[2],g=await K(t),f=await ar(i,o,g);return w(e,f.statusCode,f.body),!0}if(n==="POST"&&s===`${l$1}/mcp`){await H();let i=await K(t),o=typeof i.tool=="string"?i.tool.trim():"",g=i.args&&typeof i.args=="object"&&!Array.isArray(i.args)?i.args:{};if(!o)return w(e,400,{error:"tool is required"}),!0;if(o==="inspect.file-contents")return w(e,400,{error:"inspect.file-contents is only available on /mcp-raw"}),!0;try{let f=await Gt(o,g,De(et()));if(f&&typeof f=="object"&&!Array.isArray(f)){let k=f;if(k.status==="fail")return w(e,400,{error:Rt(f,"Request failed")}),!0;if(k.status==="error")return w(e,500,{error:Rt(f,"Internal error")}),!0}w(e,200,f);}catch(f){let k=typeof f?.statusCode=="number"?Number(f.statusCode):500,$=f instanceof Error?f.message:String(f);w(e,k,{error:$});}return !0}if(n==="POST"&&s===`${l$1}/mcp-controlplane`){await H();let i=await K(t),o=typeof i.tool=="string"?i.tool.trim():"",g=i.args&&typeof i.args=="object"&&!Array.isArray(i.args)?i.args:{};if(!o)return w(e,400,{error:"tool is required"}),!0;try{let f=await Gt(o,g,Ue());if(f&&typeof f=="object"&&!Array.isArray(f)){let k=f;if(k.status==="fail")return w(e,400,{error:Rt(f,"Request failed")}),!0;if(k.status==="error")return w(e,500,{error:Rt(f,"Internal error")}),!0}w(e,200,f);}catch(f){let k=typeof f?.statusCode=="number"?Number(f.statusCode):500,$=f instanceof Error?f.message:String(f);w(e,k,{error:$});}return !0}if(n==="POST"&&s===`${l$1}/mcp-raw`){await H();let i=await K(t),o=typeof i.tool=="string"?i.tool.trim():"",g=i.args&&typeof i.args=="object"&&!Array.isArray(i.args)?i.args:{};if(!o)return w(e,400,{error:"tool is required"}),!0;if(o!=="inspect.file-contents")return w(e,400,{error:`Tool does not support raw response: ${o}`}),!0;let f=E(g,"card_id","cardId"),k=at(g,"file_idx","fileIdx"),$=at(g,"head-lines","headLines"),T=at(g,"tail-lines","tailLines"),N=at(g,"head-bytes","headBytes"),rt=at(g,"tail-bytes","tailBytes");if(!f)return w(e,400,{error:"inspect.file-contents requires card_id"}),!0;if(k===void 0||!Number.isInteger(k)||k<0)return w(e,400,{error:"inspect.file-contents requires file_idx to be a non-negative integer"}),!0;if([$,T,N,rt].filter(G=>G!==void 0).length>1)return w(e,400,{error:"inspect.file-contents accepts at most one of head-lines, tail-lines, head-bytes, tail-bytes"}),!0;for(let[G,ut]of [["head-lines",$],["tail-lines",T],["head-bytes",N],["tail-bytes",rt]])if(ut!==void 0&&(!Number.isInteger(ut)||ut<0))return w(e,400,{error:`inspect.file-contents requires ${G} to be a non-negative integer`}),!0;let fe=await et().inspectFileContents({cardId:f,fileIdx:k}),fr=typeof fe?.stored_name=="string"?fe.stored_name:null,{fileRecord:Mt,bytes:gt}=await re(f,k,fr),pe=String(Mt.name||Mt.stored_name||"download.bin"),Lt=String(Mt.mime_type||"application/octet-stream"),At=(a.searchParams.get("resp")||"").trim().toLowerCase();if(At&&At!=="json-b64")return w(e,400,{error:`unsupported resp mode: ${At}`}),!0;let pr=At==="json-b64",it;if($!==void 0||T!==void 0){if(!rr(Lt))return w(e,400,{error:"head-lines/tail-lines are only supported for text-like files; use head-bytes/tail-bytes for binary content"}),!0;let G=new TextDecoder().decode(gt),ut=$!==void 0?ne(G,"head",$):ne(G,"tail",T);it=typeof Buffer<"u"?Buffer.from(ut,"utf8"):new TextEncoder().encode(ut);}else if(N!==void 0||rt!==void 0){let G=N??rt;it=N!==void 0?gt.slice(0,G):gt.slice(Math.max(0,gt.length-G));}else it=gt;if(pr){let G=typeof Buffer<"u"?Buffer.from(it).toString("base64"):btoa(String.fromCharCode(...it));return w(e,200,{bodyBase64:G,mimeType:Lt,filename:pe,byteLength:it.length}),!0}return e.writeHead(200,{"Content-Type":Lt,"Content-Disposition":`attachment; filename="${pe}"`,"Content-Length":it.length}),e.end(it),!0}let p=s.match(new RegExp(`^${V(l$1)}/cards/([^/]+)$`));if(n==="GET"&&p){await H();let i=decodeURIComponent(p[1]),o=await dt(i);return o?(w(e,200,o),!0):(w(e,404,{error:`card not found: ${i}`}),!0)}if(n==="PATCH"&&p){await H();let i=decodeURIComponent(p[1]),o=await K(t);return await Ve(i,o),w(e,200,{ok:!0}),!0}let m=s.match(new RegExp(`^${V(l$1)}/cards/([^/]+)/retrigger$`));if(n==="POST"&&m){await H();let i=decodeURIComponent(m[1]);return await Qe(i),w(e,200,{ok:!0}),!0}let C=s.match(new RegExp(`^${V(l$1)}/cards/([^/]+)/actions$`));if(n==="POST"&&C){await H();let i=decodeURIComponent(C[1]),o=Date.now(),g=new Date(o).toISOString(),f=await K(t),k=f?.actionType;if(k==="chat-send"&&!await ee(i)){let T=Date.now();return w(e,409,{error:`chat handler is not configured for card: ${i}`,requestReceivedAt:g,requestReceivedAtMs:o,responseSentAt:new Date(T).toISOString(),responseSentAtMs:T,responseStatus:409}),!0}if(k==="chat-send"){let T=f?.payload??{},N=typeof T["turn-id"]=="string"?T["turn-id"]:typeof T.turnId=="string"?T.turnId:typeof T.turn=="string"?T.turn:"";if(!N||!String(N).trim()){let rt=Date.now();return w(e,400,{error:`chat-send requires a non-empty 'turn-id' (or 'turnId'/'turn') in payload for card: ${i}`,requestReceivedAt:g,requestReceivedAtMs:o,responseSentAt:new Date(rt).toISOString(),responseSentAtMs:rt,responseStatus:400}),!0}}await tr(i,k,f?.payload);let $=Date.now();return w(e,200,{ok:!0,requestReceivedAt:g,requestReceivedAtMs:o,responseSentAt:new Date($).toISOString(),responseSentAtMs:$,responseStatus:200}),!0}let S=s.match(new RegExp(`^${V(l$1)}/cards/([^/]+)/chats$`));if(n==="GET"&&S){await H();let i=decodeURIComponent(S[1]),o=String(a.searchParams.get("turn-id")||""),g=String(a.searchParams.get("all-turns")||"").toLowerCase()==="true",f=String(a.searchParams.get("tail-turns-before-id")||""),k=a.searchParams.get("tail-turns"),$=k==null||k===""?g||o?void 0:1:Number.parseInt(k,10),T=W.readAll({params:{cardId:i},body:{...$===void 0?{}:{tailTurns:$},...o?{turnId:o}:{},...g?{allTurns:!0}:{},...f?{tailTurnsBeforeId:f}:{}}});if(T.status!=="success")return w(e,400,{error:T.error||"Failed to read chats"}),!0;let N=T.data.records;return w(e,200,{ok:!0,messages:N}),!0}if(n==="POST"&&S){await H();let i=decodeURIComponent(S[1]),o=await K(t),g=typeof o?.role=="string"?o.role:"assistant",f=typeof o?.text=="string"?o.text:"",k=Array.isArray(o?.files)?o.files:[],$=typeof o?.turn=="string"?o.turn:typeof o?.["turn-id"]=="string"?o["turn-id"]:typeof o?.turnId=="string"?o.turnId:"",T=o?.done===!0,N=P.append(i,g,f,k,$);return T&&P.setProcessing(i,!1),Ft(i,!T),w(e,200,{ok:!0,id:N}),!0}let q=s.match(new RegExp(`^${V(l$1)}/cards/([^/]+)/chats/subscribe-sse$`));if(n==="POST"&&q){await H();let i=decodeURIComponent(q[1]),o=await K(t),g=typeof o?.clientId=="string"?o.clientId.trim():"";return g?ir(g,i)?(w(e,200,{ok:!0,clientId:g,cardId:i,subscribed:!0}),!0):(w(e,404,{error:`SSE client not connected: ${g}`}),!0):(w(e,400,{error:"clientId is required"}),!0)}let L=s.match(new RegExp(`^${V(l$1)}/cards/([^/]+)/chats/unsubscribe-sse$`));if(n==="POST"&&L){await H();let i=decodeURIComponent(L[1]),o=await K(t),g=typeof o?.clientId=="string"?o.clientId.trim():"";return g?cr(g,i)?(w(e,200,{ok:!0,clientId:g,cardId:i,subscribed:!1}),!0):(w(e,404,{error:`SSE client not connected: ${g}`}),!0):(w(e,400,{error:"clientId is required"}),!0)}let u=s.match(new RegExp(`^${V(l$1)}/watch-channel/([^/]+)/(subscribe|unsubscribe)-sse$`));if(n==="POST"&&u){await H();let i=decodeURIComponent(u[1]),o=u[2]==="subscribe",g=await K(t),f=typeof g?.clientId=="string"?g.clientId.trim():"";return f?(de(e,f,i,{},o),!0):(w(e,400,{error:"clientId is required"}),!0)}let b=s.match(new RegExp(`^${V(l$1)}/cards/([^/]+)/watch-channel/([^/]+)/(subscribe|unsubscribe)-sse$`));if(n==="POST"&&b){await H();let i=decodeURIComponent(b[1]),o=decodeURIComponent(b[2]),g=b[3]==="subscribe",f=await K(t),k=typeof f?.clientId=="string"?f.clientId.trim():"";return k?(de(e,k,o,{cardId:i},g),!0):(w(e,400,{error:"clientId is required"}),!0)}let A=s.match(new RegExp(`^${V(l$1)}/cards/([^/]+)/files$`));if(n==="POST"&&A){await H();let i=decodeURIComponent(A[1]),o=String(a.searchParams.get("inChat")||"").toLowerCase()==="true",g=String(a.searchParams.get("turn-id")||"").trim();if(o&&!g)return w(e,400,{error:`file upload with inChat=true requires a non-empty 'turn-id' query parameter for card: ${i}`}),!0;let f=t.headers["x-file-name"],k=String(t.headers["content-type"]||"application/octet-stream"),$=Array.isArray(f)?f[0]:f,T=$?decodeURIComponent(String($)):"upload.bin",N=await nr(t);return w(e,200,await Tt(i,T,k,N,{inChat:o,turnId:g})),!0}let R=s.match(new RegExp(`^${V(l$1)}/cards/([^/]+)/files/(\\d+)$`));if(n==="GET"&&R){let i=decodeURIComponent(R[1]),o=parseInt(R[2],10),g=a.searchParams.get("sn");return await er(e,i,o,g),!0}return !1}catch(d){let p=d?.statusCode||500;return w(e,p,{error:String(d?.message||d)}),true}}return {get apiBasePath(){return l$1},get corsHeaders(){return y$1},get queueLaneTuning(){return _},handleRuntimeApi:lr,buildPublishedRuntimePayload:Ct,processAccumulatedEvents:$e,processAccumulatedLane:xt,handleChatAgentRequest:Ye,clearChatRecords:ze,reportSourceFetched(t,e){return ae(t,{ref:e})},reportSourceFetchFailure(t,e){return se(t,{reason:e})},get cardStore(){return j$1[0]?.publicCardStore??{get(){return Promise.resolve({status:"fail",error:"no board context"})},set(){return Promise.resolve({status:"fail",error:"no board context"})}}}}}function Mr(c){let l=String(c.apiBasePath||"/api/boards").replace(/\/$/,""),y={...Te,...c.corsHeaders||{}},_=c.serverMetaStore,h=c.boardRuntimeFactory,x=new Map,I="boards-config.json";function O(){let B=_.getText(I);if(!B)return {boards:[{id:"default",label:"Default Board"}]};try{return JSON.parse(B)}catch{return {boards:[{id:"default",label:"Default Board"}]}}}function P(B){_.putText(I,JSON.stringify(B,null,2));}function W(B){let v=String(B||"").replace(/[^a-zA-Z0-9_-]/g,"_").replace(/^_+|_+$/g,"");return v.length>0&&v.length<=64?v:null}function ot(B){if(x.has(B))return x.get(B);let F=O().boards.find(D=>D.id===B)||{},M=h(B,F);return x.set(B,M),M}function z(B,v,F){let M=JSON.stringify(F),D=typeof Buffer<"u"?Buffer.byteLength(M):new TextEncoder().encode(M).length;B.writeHead(v,{...y,"Content-Type":"application/json; charset=utf-8","Content-Length":D}),B.end(M);}async function mt(B,v,F){let M=B.method||"GET",D=F.pathname;if(M==="GET"&&D===l)return z(v,200,{ok:true,boards:O().boards}),true;if(M==="POST"&&D===l){let Z=[];for await(let tt of B)Z.push(tt);let j=typeof Buffer<"u"?Buffer.concat(Z).toString("utf-8").trim():new TextDecoder().decode(vt(Z)).trim(),U={};try{U=j?JSON.parse(j):{};}catch{U={};}let X=W(U.id);if(!X)return z(v,400,{error:"board id must be 1-64 alphanumeric/dash/underscore characters"}),true;let ft=O();if(ft.boards.some(tt=>tt.id===X))return z(v,409,{error:`Board "${X}" is already registered`}),true;let yt=typeof U.label=="string"&&U.label.trim()?U.label.trim():X,Y={id:X,label:yt};for(let[tt,pt]of Object.entries(U))tt==="id"||tt==="label"||pt!=null&&(Y[tt]=pt);return ft.boards.push(Y),P(ft),z(v,200,{ok:true,board:Y}),true}return false}async function Bt(B,v,F){let D=F.pathname.match(new RegExp(`^${V(l)}/([^/]+)(/|$)`));if(!D)return false;let Z=W(decodeURIComponent(D[1]));return Z?O().boards.some(X=>X.id===Z)?!!await ot(Z).handleRuntimeApi(B,v,F):(z(v,404,{error:`Board "${Z}" not registered. POST ${l} with {id} to register it first.`}),true):(z(v,400,{error:"Invalid board id"}),true)}async function It(B,v,F){return !!(await mt(B,v,F)||await Bt(B,v,F))}function Ot(B){if(!O().boards.some(F=>F.id===B))throw Object.assign(new Error(`Board "${B}" not registered`),{statusCode:404});return {service:ot(B)}}return {get apiBasePath(){return l},get corsHeaders(){return y},handleApi:It,requireBoardService:Ot}}export{kr as a,qr as b,Mr as c};//# sourceMappingURL=chunk-OSWJKJLB.js.map
|
|
8
|
+
//# sourceMappingURL=chunk-OSWJKJLB.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';function f(r){function a(e){return {status:"success",data:e}}function s(e){return {status:"fail",error:e}}function u(e){return {status:"error",error:e instanceof Error?e.message:String(e)}}return {list(e){try{let t=e.params?.prefix??"";return a({artifacts:r.list(t)})}catch(t){return u(t)}},head(e){try{let t=e.params?.key;return t?a({artifact:r.head(t)}):s("head requires params.key")}catch(t){return u(t)}},put(e){try{let t=e.params?.key,i=e.params?.contentType;if(!t)return s("put requires params.key");let n=e.body;if(typeof n=="string")return a({artifact:r.putText(t,n,i)});if(n&&typeof n=="object"&&typeof n.text=="string")return a({artifact:r.putText(t,n.text,i)});if(n&&typeof n=="object"&&Array.isArray(n.bytes)){let o=n.bytes,m=new Uint8Array(o.map(c=>Math.max(0,Math.min(255,Number(c)||0))));return a({artifact:r.putBytes(t,m,i)})}return s("put requires body as string, {text}, or {bytes:number[]}")}catch(t){return u(t)}},get(e){try{let t=e.params?.key,i=e.params?.as??"base64";if(!t)return s("get requires params.key");let n=r.head(t);if(!n)return s(`artifact "${t}" not found`);if(i==="text"){let m=r.getText(t);return m===null?s(`artifact "${t}" not found`):a({key:t,contentType:n.contentType,size:n.size,text:m})}let o=r.getBytes(t);return o===null?s(`artifact "${t}" not found`):a({key:t,contentType:n.contentType,size:n.size,bytes:[...o]})}catch(t){return u(t)}},del(e){try{let t=e.params?.key;return t?(r.remove(t),a({ok:!0})):s("del requires params.key")}catch(t){return u(t)}}}}exports.a=f;//# sourceMappingURL=chunk-P7ZCDICS.cjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-P7ZCDICS.cjs.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';function g(n){return typeof n=="object"&&n!==null&&"then"in n&&typeof n.then=="function"}function i(n,s){return g(n)?n.then(s):s(n)}function u(n,s){let r={...n};for(let[e,t]of Object.entries(s))t!==null&&typeof t=="object"&&!Array.isArray(t)&&r[e]!==null&&typeof r[e]=="object"&&!Array.isArray(r[e])?r[e]=u(r[e],t):r[e]=t;return r}function c(n,s,r){if(s.length===0)return n;let[e,...t]=s;if(t.length===0)return {...n,[e]:r};let o=n[e]!==null&&typeof n[e]=="object"&&!Array.isArray(n[e])?n[e]:{};return {...n,[e]:c(o,t,r)}}function l(n){return {read:r=>n.read(r),get(r,e){return i(n.read(r),t=>{if(t===null)return null;let o=t;for(let a of e.split(".").filter(Boolean)){if(o===null||typeof o!="object"||Array.isArray(o))return null;o=o[a]??null;}return o??null})},write:(r,e)=>n.write(r,e),delete:r=>n.delete(r),listKeys:r=>n.listKeys(r),shallowMerge(r,e){return i(n.read(r),t=>n.write(r,{...t??{},...e}))},deepMerge(r,e){return i(n.read(r),t=>n.write(r,u(t??{},e)))},patch(r,e,t){return i(n.read(r),o=>{let a=e.split(".").filter(Boolean);return n.write(r,c(o??{},a,t))})}}}exports.a=c;exports.b=l;//# sourceMappingURL=chunk-PBCDDO4V.cjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-PBCDDO4V.cjs.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';var chunkSFVO2LB2_cjs=require('./chunk-SFVO2LB2.cjs'),module$1=require('module'),url=require('url'),path=require('path'),fs=require('fs');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;var f=path.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-PMUSJQSR.cjs', document.baseURI).href)))),E=module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-PMUSJQSR.cjs', document.baseURI).href)));function w(){let e=path.resolve(f,"./jsonata-sync.cjs");return fs.existsSync(e)?e:path.resolve(f,"../../card-compute/jsonata-sync.cjs")}var p=E(w());function u(e){e.registerFunction("fsPathRef",s=>chunkSFVO2LB2_cjs.a({kind:"fs-path",value:String(s)}),"<s:s>");}function R(e,s,c){if(!e||typeof e!="object")return {};let i={};if(Array.isArray(e.cmdTemplate)){let r=[];for(let n of e.cmdTemplate)try{let a=p(n);u(a),r.push(String(a.evaluate(s)));}catch(a){let t=a instanceof Error?a.message:String(a);throw new Error(`[${c}] argsMassaging.cmdTemplate failed on "${n}": ${t}`)}i.cmdArgs=r;}if(typeof e.stdinTemplate=="string")try{let r=p(e.stdinTemplate);u(r),i.stdin=r.evaluate(s);}catch(r){let n=r instanceof Error?r.message:String(r);throw new Error(`[${c}] argsMassaging.stdinTemplate failed: ${n}`)}if(typeof e.urlTemplate=="string")try{let r=p(e.urlTemplate);u(r),i.url=String(r.evaluate(s));}catch(r){let n=r instanceof Error?r.message:String(r);throw new Error(`[${c}] argsMassaging.urlTemplate failed: ${n}`)}if(typeof e.headerTemplate=="string")try{let r=p(e.headerTemplate);u(r);let n=r.evaluate(s);if(typeof n!="object"||n===null)throw new Error(`headerTemplate must produce an object, got: ${JSON.stringify(n)}`);i.headers=n;}catch(r){let n=r instanceof Error?r.message:String(r);throw new Error(`[${c}] argsMassaging.headerTemplate failed: ${n}`)}if(typeof e.bodyTemplate=="string")try{let r=p(e.bodyTemplate);u(r),i.body=r.evaluate(s);}catch(r){let n=r instanceof Error?r.message:String(r);throw new Error(`[${c}] argsMassaging.bodyTemplate failed: ${n}`)}return i}function _(e,s,c){if(!e||typeof e!="object")return s;let i={output:s},r=s.result,n=s.data,a=s.error;if(typeof e.resultExpr=="string")try{let t=p(e.resultExpr);u(t);let o=t.evaluate(i);if(typeof o!="string"||!o.trim())throw new Error(`resultExpr did not produce a non-empty string (got ${JSON.stringify(o)})`);r=o;}catch(t){let o=t instanceof Error?t.message:String(t);throw new Error(`[${c}] outputTransforms.resultExpr failed: ${o}`)}if(typeof e.dataTemplate=="string")try{let t=p(e.dataTemplate);u(t);let o=t.evaluate(i);if(!o||typeof o!="object"||Array.isArray(o))throw new Error(`dataTemplate did not produce an object (got ${JSON.stringify(o)})`);n=o;}catch(t){let o=t instanceof Error?t.message:String(t);throw new Error(`[${c}] outputTransforms.dataTemplate failed: ${o}`)}if(typeof e.errorExpr=="string")try{let t=p(e.errorExpr);u(t);let o=t.evaluate(i);a=o!=null?String(o):void 0;}catch(t){let o=t instanceof Error?t.message:String(t);throw new Error(`[${c}] outputTransforms.errorExpr failed: ${o}`)}return a!==void 0?{result:r,data:n,error:a}:{result:r,data:n}}exports.a=R;exports.b=_;//# sourceMappingURL=chunk-PMUSJQSR.cjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-PMUSJQSR.cjs.map
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
'use strict';var chunkH5KD3JPY_cjs=require('./chunk-H5KD3JPY.cjs'),chunkUJ7ZTV4J_cjs=require('./chunk-UJ7ZTV4J.cjs'),chunkGNFE24S7_cjs=require('./chunk-GNFE24S7.cjs'),L=require('ajv-formats');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var L__default=/*#__PURE__*/_interopDefault(L);function w(r,t,e,i){let s=r.steps[e];if(!s)throw new Error(`Step "${e}" not found in flow configuration`);if(i.result==="failure"&&s.retry){let o=t.retryCounts[e]??0;if(o<s.retry.max_attempts)return {newState:{...t,retryCounts:{...t.retryCounts,[e]:o+1},updatedAt:Date.now()},nextStep:e,isTerminal:false,isCircuitBroken:false,shouldRetry:true}}let n=s.failure_transitions?.[i.result]??s.transitions[i.result];if(!n)throw new Error(`No transition defined for result "${i.result}" in step "${e}"`);let p=!!r.terminal_states[n];return {newState:{...t,currentStep:n,stepHistory:[...t.stepHistory,e],retryCounts:{...t.retryCounts,[e]:0},updatedAt:Date.now()},nextStep:n,isTerminal:p,isCircuitBroken:false,shouldRetry:false}}function S(r,t,e){let i=r.steps[e];if(!i?.circuit_breaker)return {broken:false,newState:{...t,iterationCounts:{...t.iterationCounts,[e]:(t.iterationCounts[e]??0)+1},updatedAt:Date.now()}};let s=t.iterationCounts[e]??0;return s>=i.circuit_breaker.max_iterations?{broken:true,redirectStep:i.circuit_breaker.on_open,newState:{...t,currentStep:i.circuit_breaker.on_open,updatedAt:Date.now()}}:{broken:false,newState:{...t,iterationCounts:{...t.iterationCounts,[e]:s+1},updatedAt:Date.now()}}}function h(r,t,e){let i=r.steps[t];if(!i)throw new Error(`Step "${t}" not found`);if(i.expects_data){let s={};for(let n of i.expects_data)s[n]=e[n];return s}return {...e}}function g(r,t){if(r===false||r===void 0)return {};if(typeof r=="string")return {[r]:t[r]};if(Array.isArray(r)){let e={};for(let i of r)e[i]=t[i];return e}return {}}function y(r,t){let e=Date.now();return {runId:t,flowId:r.id??"unnamed",currentStep:r.settings.start_step,status:"running",stepHistory:[],iterationCounts:{},retryCounts:{},startedAt:e,updatedAt:e}}function $(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let t=Math.random()*16|0;return (r==="x"?t:t&3|8).toString(16)})}var u=class{flow;handlers;store;components;options;listeners=new Map;aborted=false;constructor(t,e,i={}){this.flow=t,this.handlers=new Map(Object.entries(e)),this.store=i.store??new chunkH5KD3JPY_cjs.a,this.components=i.components??{},this.options=i,i.signal&&i.signal.addEventListener("abort",()=>{this.aborted=true;}),this.validateFlow();}validateFlow(){let{settings:t,steps:e,terminal_states:i}=this.flow;if(!t?.start_step)throw new Error("Flow must have settings.start_step defined");if(!e||Object.keys(e).length===0)throw new Error("Flow must have at least one step defined");if(!i||Object.keys(i).length===0)throw new Error("Flow must have at least one terminal_state defined");if(!e[t.start_step]&&!i[t.start_step])throw new Error(`Start step "${t.start_step}" not found`);for(let[s,n]of Object.entries(e)){for(let[p,o]of Object.entries(n.transitions))if(!e[o]&&!i[o])throw new Error(`Step "${s}" transition "${p}" points to unknown step "${o}"`);if(n.failure_transitions){for(let[p,o]of Object.entries(n.failure_transitions))if(!e[o]&&!i[o])throw new Error(`Step "${s}" failure_transition "${p}" points to unknown step "${o}"`)}}}on(t,e){this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(e);}off(t,e){this.listeners.get(t)?.delete(e);}emit(t){let e=this.listeners.get(t.type);if(e)for(let i of e)try{i(t);}catch{}}sleep(t){return new Promise(e=>setTimeout(e,t))}async run(t){let e=$(),i=y(this.flow,e);if(await this.store.saveRunState(e,i),t)for(let[s,n]of Object.entries(t))await this.store.setData(e,s,n);this.emit({type:"flow:start",runId:e,timestamp:i.startedAt,data:{initialData:t??{}}});try{return await this.executeLoop(e,i)}catch(s){let n=s instanceof Error?s:new Error(String(s));return this.emit({type:"flow:error",runId:e,timestamp:Date.now(),data:{error:n.message}}),this.options.onError?.(n),i={...i,status:"failed",updatedAt:Date.now()},await this.store.saveRunState(e,i),{runId:e,status:"failed",data:await this.store.getAllData(e),finalStep:i.currentStep,stepHistory:i.stepHistory,durationMs:Date.now()-i.startedAt,error:n}}}async resume(t){let e=await this.store.loadRunState(t);if(!e)throw new Error(`No run found with ID: ${t}`);if(e.status==="completed"||e.status==="failed")throw new Error(`Cannot resume a ${e.status} run`);let i={...e,status:"running",pausedAt:void 0,updatedAt:Date.now()};return await this.store.saveRunState(t,i),this.emit({type:"flow:resumed",runId:t,timestamp:Date.now(),data:{currentStep:i.currentStep}}),this.executeLoop(t,i)}async pause(t){let e=await this.store.loadRunState(t);if(!e)throw new Error(`No run found with ID: ${t}`);let i={...e,status:"paused",pausedAt:Date.now(),updatedAt:Date.now()};await this.store.saveRunState(t,i),this.emit({type:"flow:paused",runId:t,timestamp:Date.now(),data:{currentStep:i.currentStep}});}async executeLoop(t,e){let i=this.flow.settings.max_total_steps??1e6,s=this.flow.settings.timeout_ms,n=e,p=0;for(;p<i;){if(this.aborted)return n={...n,status:"cancelled",updatedAt:Date.now()},await this.store.saveRunState(t,n),{runId:t,status:"cancelled",data:await this.store.getAllData(t),finalStep:n.currentStep,stepHistory:n.stepHistory,durationMs:Date.now()-n.startedAt};if(s&&Date.now()-n.startedAt>s)return n={...n,status:"completed",updatedAt:Date.now()},await this.store.saveRunState(t,n),{runId:t,status:"timeout",intent:"timeout",data:await this.store.getAllData(t),finalStep:n.currentStep,stepHistory:n.stepHistory,durationMs:Date.now()-n.startedAt};let o=n.currentStep,d=this.flow.terminal_states[o];if(d){n={...n,status:"completed",updatedAt:Date.now()},await this.store.saveRunState(t,n);let a=await this.store.getAllData(t),c={runId:t,status:"completed",intent:d.return_intent,data:g(d.return_artifacts,a),finalStep:o,stepHistory:n.stepHistory,durationMs:Date.now()-n.startedAt};return this.emit({type:"flow:complete",runId:t,timestamp:Date.now(),data:{...c}}),this.options.onComplete?.(c),c}let m=S(this.flow,n,o);if(m.broken){n=m.newState,await this.store.saveRunState(t,n),p++;continue}n=m.newState;let F=await this.store.getAllData(t),_=h(this.flow,o,F),j={runId:t,stepName:o,components:this.components,store:this.store,signal:this.options.signal,emit:(a,c)=>{this.emit({type:"step:complete",runId:t,timestamp:Date.now(),data:{event:a,payload:c}});}};this.emit({type:"step:start",runId:t,timestamp:Date.now(),data:{step:o,input:_}});let l;try{let a=this.handlers.get(o);if(!a)throw new Error(`No handler registered for step "${o}"`);l=await a(_,j);}catch(a){let c=a instanceof Error?a:new Error(String(a));this.emit({type:"step:error",runId:t,timestamp:Date.now(),data:{step:o,error:c.message}}),l={result:"failure",data:{error:c.message}};}if(l.data)for(let[a,c]of Object.entries(l.data))await this.store.setData(t,a,c);this.emit({type:"step:complete",runId:t,timestamp:Date.now(),data:{step:o,result:l.result}}),this.options.onStep?.(o,l);let b=w(this.flow,n,o,l);if(n=b.newState,b.shouldRetry){await this.store.saveRunState(t,n);let a=this.flow.steps[o];if(a.retry?.delay_ms){let c=n.retryCounts[o]??0,D=a.retry.backoff_multiplier?a.retry.delay_ms*Math.pow(a.retry.backoff_multiplier,c-1):a.retry.delay_ms;await this.sleep(D);}p++;continue}await this.store.saveRunState(t,n),this.emit({type:"transition",runId:t,timestamp:Date.now(),data:{from:o,to:n.currentStep,result:l.result}}),this.options.onTransition?.(o,n.currentStep),p++;}return n={...n,status:"completed",updatedAt:Date.now()},await this.store.saveRunState(t,n),{runId:t,status:"max_iterations",intent:"max_iterations",data:await this.store.getAllData(t),finalStep:n.currentStep,stepHistory:n.stepHistory,durationMs:Date.now()-n.startedAt}}};function A(r,t,e){return new u(r,t,e)}async function x(r){return (await import('yaml')).parse(r)}async function P(r){let t=await fetch(r);if(!t.ok)throw new Error(`Failed to load flow from ${r}: ${t.statusText}`);let e=t.headers.get("content-type")??"",i=await t.text();return e.includes("json")||r.endsWith(".json")?JSON.parse(i):x(i)}async function H(r){let e=await(await import('fs/promises')).readFile(r,"utf-8");return r.endsWith(".json")?JSON.parse(e):x(e)}function k(r){let t=[];if(!r||typeof r!="object")return ["Flow must be an object"];let e=r;if(!e.settings||typeof e.settings!="object"?t.push('Flow must have a "settings" object'):typeof e.settings.start_step!="string"&&t.push("settings.start_step must be a string"),!e.steps||typeof e.steps!="object")t.push('Flow must have a "steps" object');else {let i=e.steps;for(let[s,n]of Object.entries(i)){if(!n||typeof n!="object"){t.push(`Step "${s}" must be an object`);continue}let p=n;(!p.transitions||typeof p.transitions!="object")&&t.push(`Step "${s}" must have a "transitions" object`),p.failure_transitions!==void 0&&typeof p.failure_transitions!="object"&&t.push(`Step "${s}" failure_transitions must be an object when provided`);}}if(!e.terminal_states||typeof e.terminal_states!="object")t.push('Flow must have a "terminal_states" object');else {let i=e.terminal_states;for(let[s,n]of Object.entries(i)){if(!n||typeof n!="object"){t.push(`Terminal state "${s}" must be an object`);continue}typeof n.return_intent!="string"&&t.push(`Terminal state "${s}" must have a "return_intent" string`);}}return t}async function O(r){let t;typeof r=="string"?r.startsWith("http://")||r.startsWith("https://")?t=await P(r):r.includes("{")?t=JSON.parse(r):t=await H(r):t=r;let e=k(t);if(e.length>0)throw new Error(`Invalid step flow configuration:
|
|
2
|
+
- ${e.join(`
|
|
3
|
+
- `)}`);return t}var C={$schema:"http://json-schema.org/draft-07/schema#",$id:"https://github.com/yaml-flow/schema/flow.json",title:"YamlFlow Configuration",description:"Schema for yaml-flow workflow definitions",type:"object",required:["settings","steps","terminal_states"],properties:{id:{type:"string",description:"Optional flow identifier"},settings:{type:"object",description:"Flow-level settings",required:["start_step"],properties:{start_step:{type:"string",description:"Step to start execution from"},max_total_steps:{type:"integer",minimum:1,default:1e6,description:"Maximum steps before forced termination"},timeout_ms:{type:"integer",minimum:0,description:"Flow timeout in milliseconds"},invoke_timeout_ms:{type:"integer",minimum:0,description:"Per-ref invocation timeout in milliseconds"}},additionalProperties:false},steps:{type:"object",description:"Step definitions",minProperties:1,additionalProperties:{$ref:"#/definitions/step"}},terminal_states:{type:"object",description:"Terminal state definitions",minProperties:1,additionalProperties:{$ref:"#/definitions/terminal_state"}}},additionalProperties:false,definitions:{step:{type:"object",description:"Individual step configuration",required:["transitions"],properties:{description:{type:"string",description:"Human-readable description"},expects_data:{type:"array",items:{type:"string"},description:"Data keys this step expects as input"},produces_data:{type:"array",items:{type:"string"},description:"Data keys this step produces as output"},transitions:{type:"object",description:"Mapping of result -> next step name",additionalProperties:{type:"string"},minProperties:1},failure_transitions:{type:"object",description:"Mapping of failure-like results (e.g. failure, timeout) -> next step name",additionalProperties:{type:"string"}},retry:{$ref:"#/definitions/retry_config"},circuit_breaker:{$ref:"#/definitions/circuit_breaker_config"}},additionalProperties:false},terminal_state:{type:"object",description:"Terminal state configuration",required:["return_intent"],properties:{description:{type:"string",description:"Human-readable description"},return_intent:{type:"string",description:"Intent/status to return (e.g., 'success', 'error')"},return_artifacts:{oneOf:[{type:"string"},{type:"array",items:{type:"string"}},{type:"boolean",const:false}],description:"Data key(s) to include in result, or false to exclude"},expects_data:{type:"array",items:{type:"string"},description:"Data keys this terminal state expects"}},additionalProperties:false},retry_config:{type:"object",description:"Retry configuration for step failures",required:["max_attempts"],properties:{max_attempts:{type:"integer",minimum:1,description:"Maximum retry attempts"},delay_ms:{type:"integer",minimum:0,description:"Delay between retries in ms"},backoff_multiplier:{type:"number",minimum:1,description:"Backoff multiplier (e.g., 2 for exponential)"}},additionalProperties:false},circuit_breaker_config:{type:"object",description:"Circuit breaker configuration for loops",required:["max_iterations","on_open"],properties:{max_iterations:{type:"integer",minimum:1,description:"Maximum iterations before circuit opens"},on_open:{type:"string",description:"Step to transition to when circuit opens"}},additionalProperties:false}}};var R=chunkGNFE24S7_cjs.b(chunkUJ7ZTV4J_cjs.q(),1);var f=null;function B(){if(f)return f;let r=new R.default({allErrors:true});return L__default.default(r),f=r.compile(C),f}function q(r){let t=B();return t(r)?{ok:true,errors:[]}:{ok:false,errors:(t.errors??[]).map(s=>`${s.instancePath||"/"}: ${s.message??"unknown error"}`)}}
|
|
4
|
+
exports.a=w;exports.b=S;exports.c=h;exports.d=g;exports.e=y;exports.f=u;exports.g=A;exports.h=x;exports.i=k;exports.j=O;exports.k=q;//# sourceMappingURL=chunk-Q6H7NINN.cjs.map
|
|
5
|
+
//# sourceMappingURL=chunk-Q6H7NINN.cjs.map
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import {a}from'./chunk-JM5EKT57.js';import {q as q$1}from'./chunk-MNEOJWPS.js';import {b}from'./chunk-FW4363Y4.js';import L from'ajv-formats';function w(r,t,e,i){let s=r.steps[e];if(!s)throw new Error(`Step "${e}" not found in flow configuration`);if(i.result==="failure"&&s.retry){let o=t.retryCounts[e]??0;if(o<s.retry.max_attempts)return {newState:{...t,retryCounts:{...t.retryCounts,[e]:o+1},updatedAt:Date.now()},nextStep:e,isTerminal:false,isCircuitBroken:false,shouldRetry:true}}let n=s.failure_transitions?.[i.result]??s.transitions[i.result];if(!n)throw new Error(`No transition defined for result "${i.result}" in step "${e}"`);let p=!!r.terminal_states[n];return {newState:{...t,currentStep:n,stepHistory:[...t.stepHistory,e],retryCounts:{...t.retryCounts,[e]:0},updatedAt:Date.now()},nextStep:n,isTerminal:p,isCircuitBroken:false,shouldRetry:false}}function S(r,t,e){let i=r.steps[e];if(!i?.circuit_breaker)return {broken:false,newState:{...t,iterationCounts:{...t.iterationCounts,[e]:(t.iterationCounts[e]??0)+1},updatedAt:Date.now()}};let s=t.iterationCounts[e]??0;return s>=i.circuit_breaker.max_iterations?{broken:true,redirectStep:i.circuit_breaker.on_open,newState:{...t,currentStep:i.circuit_breaker.on_open,updatedAt:Date.now()}}:{broken:false,newState:{...t,iterationCounts:{...t.iterationCounts,[e]:s+1},updatedAt:Date.now()}}}function h(r,t,e){let i=r.steps[t];if(!i)throw new Error(`Step "${t}" not found`);if(i.expects_data){let s={};for(let n of i.expects_data)s[n]=e[n];return s}return {...e}}function g(r,t){if(r===false||r===void 0)return {};if(typeof r=="string")return {[r]:t[r]};if(Array.isArray(r)){let e={};for(let i of r)e[i]=t[i];return e}return {}}function y(r,t){let e=Date.now();return {runId:t,flowId:r.id??"unnamed",currentStep:r.settings.start_step,status:"running",stepHistory:[],iterationCounts:{},retryCounts:{},startedAt:e,updatedAt:e}}function $(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let t=Math.random()*16|0;return (r==="x"?t:t&3|8).toString(16)})}var u=class{flow;handlers;store;components;options;listeners=new Map;aborted=false;constructor(t,e,i={}){this.flow=t,this.handlers=new Map(Object.entries(e)),this.store=i.store??new a,this.components=i.components??{},this.options=i,i.signal&&i.signal.addEventListener("abort",()=>{this.aborted=true;}),this.validateFlow();}validateFlow(){let{settings:t,steps:e,terminal_states:i}=this.flow;if(!t?.start_step)throw new Error("Flow must have settings.start_step defined");if(!e||Object.keys(e).length===0)throw new Error("Flow must have at least one step defined");if(!i||Object.keys(i).length===0)throw new Error("Flow must have at least one terminal_state defined");if(!e[t.start_step]&&!i[t.start_step])throw new Error(`Start step "${t.start_step}" not found`);for(let[s,n]of Object.entries(e)){for(let[p,o]of Object.entries(n.transitions))if(!e[o]&&!i[o])throw new Error(`Step "${s}" transition "${p}" points to unknown step "${o}"`);if(n.failure_transitions){for(let[p,o]of Object.entries(n.failure_transitions))if(!e[o]&&!i[o])throw new Error(`Step "${s}" failure_transition "${p}" points to unknown step "${o}"`)}}}on(t,e){this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(e);}off(t,e){this.listeners.get(t)?.delete(e);}emit(t){let e=this.listeners.get(t.type);if(e)for(let i of e)try{i(t);}catch{}}sleep(t){return new Promise(e=>setTimeout(e,t))}async run(t){let e=$(),i=y(this.flow,e);if(await this.store.saveRunState(e,i),t)for(let[s,n]of Object.entries(t))await this.store.setData(e,s,n);this.emit({type:"flow:start",runId:e,timestamp:i.startedAt,data:{initialData:t??{}}});try{return await this.executeLoop(e,i)}catch(s){let n=s instanceof Error?s:new Error(String(s));return this.emit({type:"flow:error",runId:e,timestamp:Date.now(),data:{error:n.message}}),this.options.onError?.(n),i={...i,status:"failed",updatedAt:Date.now()},await this.store.saveRunState(e,i),{runId:e,status:"failed",data:await this.store.getAllData(e),finalStep:i.currentStep,stepHistory:i.stepHistory,durationMs:Date.now()-i.startedAt,error:n}}}async resume(t){let e=await this.store.loadRunState(t);if(!e)throw new Error(`No run found with ID: ${t}`);if(e.status==="completed"||e.status==="failed")throw new Error(`Cannot resume a ${e.status} run`);let i={...e,status:"running",pausedAt:void 0,updatedAt:Date.now()};return await this.store.saveRunState(t,i),this.emit({type:"flow:resumed",runId:t,timestamp:Date.now(),data:{currentStep:i.currentStep}}),this.executeLoop(t,i)}async pause(t){let e=await this.store.loadRunState(t);if(!e)throw new Error(`No run found with ID: ${t}`);let i={...e,status:"paused",pausedAt:Date.now(),updatedAt:Date.now()};await this.store.saveRunState(t,i),this.emit({type:"flow:paused",runId:t,timestamp:Date.now(),data:{currentStep:i.currentStep}});}async executeLoop(t,e){let i=this.flow.settings.max_total_steps??1e6,s=this.flow.settings.timeout_ms,n=e,p=0;for(;p<i;){if(this.aborted)return n={...n,status:"cancelled",updatedAt:Date.now()},await this.store.saveRunState(t,n),{runId:t,status:"cancelled",data:await this.store.getAllData(t),finalStep:n.currentStep,stepHistory:n.stepHistory,durationMs:Date.now()-n.startedAt};if(s&&Date.now()-n.startedAt>s)return n={...n,status:"completed",updatedAt:Date.now()},await this.store.saveRunState(t,n),{runId:t,status:"timeout",intent:"timeout",data:await this.store.getAllData(t),finalStep:n.currentStep,stepHistory:n.stepHistory,durationMs:Date.now()-n.startedAt};let o=n.currentStep,d=this.flow.terminal_states[o];if(d){n={...n,status:"completed",updatedAt:Date.now()},await this.store.saveRunState(t,n);let a=await this.store.getAllData(t),c={runId:t,status:"completed",intent:d.return_intent,data:g(d.return_artifacts,a),finalStep:o,stepHistory:n.stepHistory,durationMs:Date.now()-n.startedAt};return this.emit({type:"flow:complete",runId:t,timestamp:Date.now(),data:{...c}}),this.options.onComplete?.(c),c}let m=S(this.flow,n,o);if(m.broken){n=m.newState,await this.store.saveRunState(t,n),p++;continue}n=m.newState;let F=await this.store.getAllData(t),_=h(this.flow,o,F),j={runId:t,stepName:o,components:this.components,store:this.store,signal:this.options.signal,emit:(a,c)=>{this.emit({type:"step:complete",runId:t,timestamp:Date.now(),data:{event:a,payload:c}});}};this.emit({type:"step:start",runId:t,timestamp:Date.now(),data:{step:o,input:_}});let l;try{let a=this.handlers.get(o);if(!a)throw new Error(`No handler registered for step "${o}"`);l=await a(_,j);}catch(a){let c=a instanceof Error?a:new Error(String(a));this.emit({type:"step:error",runId:t,timestamp:Date.now(),data:{step:o,error:c.message}}),l={result:"failure",data:{error:c.message}};}if(l.data)for(let[a,c]of Object.entries(l.data))await this.store.setData(t,a,c);this.emit({type:"step:complete",runId:t,timestamp:Date.now(),data:{step:o,result:l.result}}),this.options.onStep?.(o,l);let b=w(this.flow,n,o,l);if(n=b.newState,b.shouldRetry){await this.store.saveRunState(t,n);let a=this.flow.steps[o];if(a.retry?.delay_ms){let c=n.retryCounts[o]??0,D=a.retry.backoff_multiplier?a.retry.delay_ms*Math.pow(a.retry.backoff_multiplier,c-1):a.retry.delay_ms;await this.sleep(D);}p++;continue}await this.store.saveRunState(t,n),this.emit({type:"transition",runId:t,timestamp:Date.now(),data:{from:o,to:n.currentStep,result:l.result}}),this.options.onTransition?.(o,n.currentStep),p++;}return n={...n,status:"completed",updatedAt:Date.now()},await this.store.saveRunState(t,n),{runId:t,status:"max_iterations",intent:"max_iterations",data:await this.store.getAllData(t),finalStep:n.currentStep,stepHistory:n.stepHistory,durationMs:Date.now()-n.startedAt}}};function A(r,t,e){return new u(r,t,e)}async function x(r){return (await import('yaml')).parse(r)}async function P(r){let t=await fetch(r);if(!t.ok)throw new Error(`Failed to load flow from ${r}: ${t.statusText}`);let e=t.headers.get("content-type")??"",i=await t.text();return e.includes("json")||r.endsWith(".json")?JSON.parse(i):x(i)}async function H(r){let e=await(await import('fs/promises')).readFile(r,"utf-8");return r.endsWith(".json")?JSON.parse(e):x(e)}function k(r){let t=[];if(!r||typeof r!="object")return ["Flow must be an object"];let e=r;if(!e.settings||typeof e.settings!="object"?t.push('Flow must have a "settings" object'):typeof e.settings.start_step!="string"&&t.push("settings.start_step must be a string"),!e.steps||typeof e.steps!="object")t.push('Flow must have a "steps" object');else {let i=e.steps;for(let[s,n]of Object.entries(i)){if(!n||typeof n!="object"){t.push(`Step "${s}" must be an object`);continue}let p=n;(!p.transitions||typeof p.transitions!="object")&&t.push(`Step "${s}" must have a "transitions" object`),p.failure_transitions!==void 0&&typeof p.failure_transitions!="object"&&t.push(`Step "${s}" failure_transitions must be an object when provided`);}}if(!e.terminal_states||typeof e.terminal_states!="object")t.push('Flow must have a "terminal_states" object');else {let i=e.terminal_states;for(let[s,n]of Object.entries(i)){if(!n||typeof n!="object"){t.push(`Terminal state "${s}" must be an object`);continue}typeof n.return_intent!="string"&&t.push(`Terminal state "${s}" must have a "return_intent" string`);}}return t}async function O(r){let t;typeof r=="string"?r.startsWith("http://")||r.startsWith("https://")?t=await P(r):r.includes("{")?t=JSON.parse(r):t=await H(r):t=r;let e=k(t);if(e.length>0)throw new Error(`Invalid step flow configuration:
|
|
2
|
+
- ${e.join(`
|
|
3
|
+
- `)}`);return t}var C={$schema:"http://json-schema.org/draft-07/schema#",$id:"https://github.com/yaml-flow/schema/flow.json",title:"YamlFlow Configuration",description:"Schema for yaml-flow workflow definitions",type:"object",required:["settings","steps","terminal_states"],properties:{id:{type:"string",description:"Optional flow identifier"},settings:{type:"object",description:"Flow-level settings",required:["start_step"],properties:{start_step:{type:"string",description:"Step to start execution from"},max_total_steps:{type:"integer",minimum:1,default:1e6,description:"Maximum steps before forced termination"},timeout_ms:{type:"integer",minimum:0,description:"Flow timeout in milliseconds"},invoke_timeout_ms:{type:"integer",minimum:0,description:"Per-ref invocation timeout in milliseconds"}},additionalProperties:false},steps:{type:"object",description:"Step definitions",minProperties:1,additionalProperties:{$ref:"#/definitions/step"}},terminal_states:{type:"object",description:"Terminal state definitions",minProperties:1,additionalProperties:{$ref:"#/definitions/terminal_state"}}},additionalProperties:false,definitions:{step:{type:"object",description:"Individual step configuration",required:["transitions"],properties:{description:{type:"string",description:"Human-readable description"},expects_data:{type:"array",items:{type:"string"},description:"Data keys this step expects as input"},produces_data:{type:"array",items:{type:"string"},description:"Data keys this step produces as output"},transitions:{type:"object",description:"Mapping of result -> next step name",additionalProperties:{type:"string"},minProperties:1},failure_transitions:{type:"object",description:"Mapping of failure-like results (e.g. failure, timeout) -> next step name",additionalProperties:{type:"string"}},retry:{$ref:"#/definitions/retry_config"},circuit_breaker:{$ref:"#/definitions/circuit_breaker_config"}},additionalProperties:false},terminal_state:{type:"object",description:"Terminal state configuration",required:["return_intent"],properties:{description:{type:"string",description:"Human-readable description"},return_intent:{type:"string",description:"Intent/status to return (e.g., 'success', 'error')"},return_artifacts:{oneOf:[{type:"string"},{type:"array",items:{type:"string"}},{type:"boolean",const:false}],description:"Data key(s) to include in result, or false to exclude"},expects_data:{type:"array",items:{type:"string"},description:"Data keys this terminal state expects"}},additionalProperties:false},retry_config:{type:"object",description:"Retry configuration for step failures",required:["max_attempts"],properties:{max_attempts:{type:"integer",minimum:1,description:"Maximum retry attempts"},delay_ms:{type:"integer",minimum:0,description:"Delay between retries in ms"},backoff_multiplier:{type:"number",minimum:1,description:"Backoff multiplier (e.g., 2 for exponential)"}},additionalProperties:false},circuit_breaker_config:{type:"object",description:"Circuit breaker configuration for loops",required:["max_iterations","on_open"],properties:{max_iterations:{type:"integer",minimum:1,description:"Maximum iterations before circuit opens"},on_open:{type:"string",description:"Step to transition to when circuit opens"}},additionalProperties:false}}};var R=b(q$1(),1);var f=null;function B(){if(f)return f;let r=new R.default({allErrors:true});return L(r),f=r.compile(C),f}function q(r){let t=B();return t(r)?{ok:true,errors:[]}:{ok:false,errors:(t.errors??[]).map(s=>`${s.instancePath||"/"}: ${s.message??"unknown error"}`)}}
|
|
4
|
+
export{w as a,S as b,h as c,g as d,y as e,u as f,A as g,x as h,k as i,O as j,q as k};//# sourceMappingURL=chunk-QWBNDVUA.js.map
|
|
5
|
+
//# sourceMappingURL=chunk-QWBNDVUA.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';var chunkG4XXRHL2_cjs=require('./chunk-G4XXRHL2.cjs'),chunkIXZG74EW_cjs=require('./chunk-IXZG74EW.cjs');function b(e){return JSON.parse(JSON.stringify(e))}function E(e){let r=e.provides&&e.provides.length>0?e.provides.map(n=>n.bindTo):[e.id];return {requires:e.requires&&e.requires.length>0?[...e.requires]:void 0,provides:r,taskHandlers:[e.id],description:e.meta?.title??e.id}}function I(e){let r=new Map;for(let[n,u]of e.entries()){let o=u.provides&&u.provides.length>0?u.provides:[{bindTo:n,ref:"card_data"}];for(let h of o)r.set(h.bindTo,n);}return r}function O(e,r){let n=I(e),u=e.get(r);if(u){for(let o of u.requires??[])if(!n.has(o))throw new Error(`Card "${r}" requires token "${o}" but no card provides it`)}}var F={CARD_PREFIX:"yf:cards:",RUNTIME_OUT_PREFIX:"yf:runtime-out:cards:",STATUS_KEY:"yf:runtime-out:status",writeCard(e,r){try{localStorage.setItem(this.CARD_PREFIX+e,JSON.stringify(r));}catch(n){console.warn(`Failed to write card ${e} to localStorage:`,n);}},readCard(e){try{let r=localStorage.getItem(this.CARD_PREFIX+e);return r?JSON.parse(r):null}catch(r){return console.warn(`Failed to read card ${e} from localStorage:`,r),null}},readAllCards(e){let r={};for(let n of e){let u=this.readCard(n);u&&(r[n]=u);}return r},writeComputedArtifact(e){if(!(!e||!e.card_id))try{localStorage.setItem(this.RUNTIME_OUT_PREFIX+String(e.card_id),JSON.stringify(e));}catch(r){console.warn(`Failed to write computed artifact ${e.card_id}:`,r);}},readComputedArtifact(e){try{let r=localStorage.getItem(this.RUNTIME_OUT_PREFIX+e);return r?JSON.parse(r):null}catch(r){return console.warn(`Failed to read computed artifact ${e}:`,r),null}},readAllComputedArtifacts(e){let r={};for(let n of e){let u=this.readComputedArtifact(n);u&&(r[n]=u);}return r},writeStatusSnapshot(e){try{localStorage.setItem(this.STATUS_KEY,JSON.stringify(e));}catch(r){console.warn("Failed to write status snapshot to localStorage:",r);}},readStatusSnapshot(){try{let e=localStorage.getItem(this.STATUS_KEY);return e?JSON.parse(e):null}catch(e){return console.warn("Failed to read status snapshot from localStorage:",e),null}},clear(){let e=[];for(let r=0;r<localStorage.length;r++){let n=localStorage.key(r);n&&(n.startsWith(this.CARD_PREFIX)||n.startsWith(this.RUNTIME_OUT_PREFIX)||n===this.STATUS_KEY)&&e.push(n);}for(let r of e)localStorage.removeItem(r);}};function H(e,r={}){let n=Array.isArray(e)?{}:{id:e.id,title:e.title,mode:e.mode,positions:e.positions,settings:e.settings},u=Array.isArray(e)?e:e.nodes,o=new Map;for(let t of u){if(o.has(t.id))throw new Error(`Duplicate card ID: "${t.id}"`);o.set(t.id,b(t));}let h=new Set,S=r.taskExecutor,L=r.sourceAdapters??{},d=r.defaultSourceAdapter,m=null,A=(t,g)=>{let a={events:t,graph:g,nodes:v()};for(let w of h)w(a);},_=t=>async g=>{let a=o.get(t);if(!a)return "task-initiate-failure";let w={};for(let R of a.requires??[]){let y=g.state[R];if(!y||typeof y!="object")continue;let k=y.provides_data;!k||typeof k!="object"||Object.prototype.hasOwnProperty.call(k,R)&&(w[R]=k[R]);}let p={};if(a.source_defs&&a.source_defs.length>0){let R=L[t]??d,y=S?await S({card:a,input:g}):R?await R({card:a,input:g}):void 0;if(y&&typeof y=="object")for(let k of a.source_defs)Object.prototype.hasOwnProperty.call(y,k.bindTo)?p[k.bindTo]=y[k.bindTo]:a.source_defs.length===1&&(p[k.bindTo]=y);}let c={id:a.id,card_data:b(a.card_data??{}),requires:w,source_defs:a.source_defs,compute:a.compute};c._sourcesData=p,c.compute&&c.compute.length>0&&await chunkIXZG74EW_cjs.a.run(c,{sourcesData:p});let T={};if(a.provides&&a.provides.length>0)for(let{bindTo:R,ref:y}of a.provides)T[R]=chunkIXZG74EW_cjs.a.resolve(c,y);else T[a.id]={...c.card_data??{},...c.computed_values??{},...c._sourcesData??{}};let B={provides_data:T,card_data:c.card_data??{},computed_values:c.computed_values??{},fetched_sources:p,requires:w};return m?.resolveCallback(g.callbackToken,B),"task-initiated"},s={},f={};for(let[t,g]of o.entries())O(o,t),s[t]=E(g),f[t]=_(t);let l={id:n.id??`browser-board-${Date.now()}`,settings:{completion:"manual",execution_mode:"eligibility-mode",...n.settings??{},...r.graphSettings??{}},tasks:s},C=r.reactiveOptions?.onDrain,i=chunkG4XXRHL2_cjs.u(l,{...r.reactiveOptions??{},handlers:f,onDrain:(t,g,a)=>{C?.(t,g,a),A(t,g);}},r.executionId);m=i;function v(){let t=i.getState(),g=[];for(let[a,w]of o.entries()){let p=t.state.tasks[a]?.data,c=t.state.tasks[a],T={...w.card_data??{},...p&&typeof p.card_data=="object"?p.card_data:{}},B=c?.status==="running"?"loading":c?.status,R={...T,...B?{status:B}:{},...c?.lastUpdated?{lastRun:c.lastUpdated}:{},...c?.status==="failed"&&c.error?{error:c.error}:{}};g.push({id:a,card:b(w),card_data:R,requires:p&&typeof p.requires=="object"?b(p.requires):{},computed_values:p&&typeof p.computed_values=="object"?b(p.computed_values):{},runtime_state:c?b(c):{}});}return g}return {getGraph:()=>i,getState:()=>i.getState(),getSchedule:()=>i.getSchedule(),getNodes:()=>v(),getBoard:()=>({...n,nodes:v()}),subscribe(t){return h.add(t),t({events:[],graph:i.getState(),nodes:v()}),()=>h.delete(t)},addCard(t){if(o.has(t.id))throw new Error(`Card "${t.id}" already exists`);o.set(t.id,b(t)),O(o,t.id),i.registerHandler(t.id,_(t.id)),i.addNode(t.id,E(t));},upsertCard(t){o.set(t.id,b(t)),O(o,t.id),i.registerHandler(t.id,_(t.id)),i.addNode(t.id,E(t));},removeCard(t){o.delete(t),i.unregisterHandler(t),i.removeNode(t);},patchCardState(t,g){let a=o.get(t);if(!a)throw new Error(`Card "${t}" not found`);a.card_data={...a.card_data??{},...g},i.retrigger(t);},retrigger(t){i.retrigger(t);},retriggerAll(){i.retriggerAll(Array.from(o.keys()));},push(t){i.push(t);},pushAll(t){i.pushAll(t);},dispose(){h.clear(),i.dispose();}}}function G(e){return e==="running"||e==="in-progress"?"loading":e==="failed"?"error":"fresh"}function D(e){return e==="loading"?"in-progress":e==="error"?"failed":e==="stale"?"pending":e==="fresh"?"completed":"pending"}function M(e,r){let n=r&&typeof r=="object"&&!Array.isArray(r)?r:{};return {schema_version:n.schema_version||"v1",card_id:typeof n.card_id=="string"?n.card_id:e,card_data:n.card_data&&typeof n.card_data=="object"&&!Array.isArray(n.card_data)?structuredClone(n.card_data):{},computed_values:n.computed_values&&typeof n.computed_values=="object"&&!Array.isArray(n.computed_values)?structuredClone(n.computed_values):{}}}function P(e,r){if(!e||typeof e!="object")throw new Error("payload must be an object");if(!r)throw new Error("cardId is required");let u=(Array.isArray(e.cardDefinitions)?e.cardDefinitions:[]).find(t=>t.id===r);if(!u)throw new Error(`cardDefinitions has no entry with id ${r}`);let o=e.statusSnapshot&&typeof e.statusSnapshot=="object"?e.statusSnapshot:{},h=e.cardRuntimeById&&typeof e.cardRuntimeById=="object"?e.cardRuntimeById:{},S=e.dataObjectsByToken&&typeof e.dataObjectsByToken=="object"?e.dataObjectsByToken:{},d=(Array.isArray(o.cards)?o.cards:[]).find(t=>t.name===r),m=structuredClone(u),A=M(r,h[r]),s={...m.card_data&&typeof m.card_data=="object"&&!Array.isArray(m.card_data)?m.card_data:{},...A.card_data||{},status:G(d?.status),lastRun:d?.runtime?.last_transition_at??null};d?.error?.message&&(s.error=d.error.message);let f=d?{task_status:d.status??null,card_status:G(d.status),runtime:structuredClone(d.runtime??{}),error:d.error?structuredClone(d.error):null,blocked_by:Array.isArray(d.blocked_by)?structuredClone(d.blocked_by):[],requires_missing:Array.isArray(d.requires_missing)?structuredClone(d.requires_missing):[]}:{task_status:null,card_status:s.status??"fresh",runtime:{last_transition_at:s.lastRun??null},error:s.error?{message:s.error}:null,blocked_by:[],requires_missing:[]},l=Array.isArray(m.requires)?m.requires:[],C={};for(let[t,g]of Object.entries(S))C[t]=structuredClone(g);for(let t of l)Object.prototype.hasOwnProperty.call(C,t)||(C[t]=null);let v=(e.cardChatsByCardId&&typeof e.cardChatsByCardId=="object"?e.cardChatsByCardId:{})[r],q=v?{messages:Array.isArray(v.messages)?v.messages:[],receiving:!!v.receiving,processing:!!v.processing}:null;return {id:r,card:m,card_data:s,requires:C,computed_values:A.computed_values,runtime_state:f,card_chats:q}}function $(e){if(!e||typeof e!="object")throw new Error("payload must be an object");return (Array.isArray(e.cardDefinitions)?e.cardDefinitions:[]).map(n=>P(e,n.id))}function J({boardPath:e,cardDefinitions:r,runtimeModels:n,graphState:u}){let o=Array.isArray(r)?r:[],h=Array.isArray(n)?n:[],S=new Map(h.map(s=>[s.id,s])),d=u.state?.tasks??{},m={};for(let s of h)s?.id&&(m[s.id]={schema_version:"v1",card_id:s.id,card_data:structuredClone(s.card_data??{}),computed_values:structuredClone(s.computed_values??{})});let A={};for(let s of Object.keys(d)){let f=d[s]?.data?.provides_data;if(f&&typeof f=="object")for(let l of Object.keys(f))A[l]=structuredClone(f[l]);}let _=o.map(s=>{let f=S.get(s.id)??{},l=d[s.id],C=typeof l?.status=="string"?l.status:D(f.card_data?.status),i=typeof l?.error=="string"?l.error:typeof f.card_data?.error=="string"?f.card_data.error:null;return {name:s.id,status:C,...i?{error:{message:i,code:"TASK_FAILED",at:l?.failedAt??null,source:"browser-runtime"}}:{},requires:Array.isArray(s.requires)?s.requires:[],requires_satisfied:[],requires_missing:[],provides_declared:Array.isArray(s.provides)?s.provides.map(v=>v.bindTo):[s.id],provides_runtime:Object.keys(l?.data?.provides_data??{}).sort(),blocked_by:[],unblocks:[],runtime:{attempt_count:l?.executionCount??0,restart_count:l?.retryCount??0,in_progress_since:C==="in-progress"?l?.startedAt??null:null,last_transition_at:l?.lastUpdated??f.card_data?.lastRun??null,last_completed_at:l?.completedAt??null,last_restarted_at:l?.startedAt??null,status_age_ms:null}}});return {cardDefinitions:structuredClone(o),cardRuntimeById:m,dataObjectsByToken:A,statusSnapshot:{schema_version:"v1",meta:{board:{path:e??"browser-runtime"}},summary:{card_count:_.length,completed:_.filter(s=>s.status==="completed").length,eligible:0,pending:_.filter(s=>s.status==="pending").length,blocked:0,unresolved:0,failed:_.filter(s=>s.status==="failed").length,in_progress:_.filter(s=>s.status==="in-progress").length,orphan_cards:0,topology:{edge_count:0,max_fan_out_card:null,max_fan_out:0}},cards:_}}}exports.a=F;exports.b=H;exports.c=P;exports.d=$;exports.e=J;//# sourceMappingURL=chunk-S6DRP2HX.cjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-S6DRP2HX.cjs.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {a}from'./chunk-JMDHDY6M.js';function h(a,i){if(a?.status==="success")return Object.prototype.hasOwnProperty.call(a,"data")?a.data:void 0;throw a?.status==="fail"||a?.status==="error"?new Error(a.error||`${i} failed`):new Error(`${i} returned an unexpected response`)}function K(a,i){if(a?.status==="success"&&Object.prototype.hasOwnProperty.call(a,"data"))return a.data;throw a?.status==="success"?new Error(`${i} returned success without data`):a?.status==="fail"||a?.status==="error"?new Error(a.error||`${i} failed`):new Error(`${i} returned an unexpected response`)}function t(a){return a&&typeof a=="object"&&!Array.isArray(a)?a:{}}function y(a){return Array.isArray(a)?a:[]}function V(a,i){if(typeof i!="string"||i.length===0)return;let u=a,m=i;m.startsWith("fetched_sources.")&&(u=t(a).fetched_sources,m=m.slice(16));for(let k of m.split(".")){if(u==null||typeof u!="object")return;u=u[k];}return u}function N(a,i){let u=t(a.view),m=y(u.elements);return {layout:u.layout,features:u.features,elements:m.map((k,x)=>{let v=t(k),I=t(v.data),B=typeof v.visible=="string"?!!V(i,v.visible):true,U=typeof I.bind=="string"?I.bind:void 0,M=typeof I.maxRows=="number"?I.maxRows:void 0,L=U?V(i,U):void 0,E={id:typeof v.id=="string"&&v.id?v.id:`element-${x}`,kind:v.kind,label:v.label,visible:B};return L!==void 0&&(E.resolved=Array.isArray(L)&&typeof M=="number"?L.slice(0,M):L),E})}}function W(a,i){let u=typeof a.id=="string"&&a.id?a.id:"card",m=y(a.provides),k=m.length>0?m:[{bindTo:u,ref:"card_data"}],x={};for(let v of k){let I=t(v),B=typeof I.bindTo=="string"?I.bindTo:"",U=typeof I.ref=="string"?I.ref:"";if(!B||!U)continue;let M=V(i,U);M!==void 0&&(x[B]=M);}return x}function ie(a){if(typeof a!="string"||!a.trim())return null;let i=/^(file uploaded|AI generated|AI geneterated):\s*.*?#(\d+)\s*$/i.exec(a.trim());if(!i)return null;let u=Number.parseInt(i[2],10);return !Number.isInteger(u)||u<0?null:u}function ce(a){return {"card-content":a}}function F(a){let{meta:i,...u}=a;return u}function ue(a,i){return Object.prototype.hasOwnProperty.call(a,i)}function J(a){return t(a.meta).__visible_controlplane_only===true}async function T(a,i){let u=await S(a.get({params:{id:i}}),"cardStore.get"),m=Array.isArray(u?.cards)?u.cards:[];if(m.length===0)throw new Error(`Card "${i}" not found`);return m[0]}function me(a$1){let{board:i,nonCore:u,cardStore:m,chatStore:k,uploadCardFile:x,buildFileDownloadUrl:v,readFetchedSourceJsonByRef:I}=a$1;function B(r){if(Array.isArray(r.bytes))return new Uint8Array(r.bytes.map(e=>Math.max(0,Math.min(255,Number(e)||0))));if(typeof r.text=="string")return new TextEncoder().encode(r.text);if(typeof r.base64=="string"){let e=String(r.base64).replace(/-/g,"+").replace(/_/g,"/"),n=e+"=".repeat((4-e.length%4)%4),s=atob(n);return Uint8Array.from(s,o=>o.charCodeAt(0))}throw new Error("file entry requires bytes, text, or base64")}async function U(){let r=t(await S(u.describeTaskExecutorCapabilities({}),"describeTaskExecutorCapabilities"));return {version:r.version,commonSourceFields:t(r.commonSourceDefFields),sourceKinds:t(r.sourceKinds)}}async function M(){let r=t(await S(i.status({}),"status")),e=t(r.summary),n=y(r.cards);return {meta:t(r.meta),summary:{card_count:typeof e.card_count=="number"?e.card_count:0,completed:typeof e.completed=="number"?e.completed:0,eligible:typeof e.eligible=="number"?e.eligible:0,pending:typeof e.pending=="number"?e.pending:0,blocked:typeof e.blocked=="number"?e.blocked:0,in_progress:typeof e.in_progress=="number"?e.in_progress:0,failed:typeof e.failed=="number"?e.failed:0,unresolved:typeof e.unresolved=="number"?e.unresolved:0},cards:n.map(s=>{let o=t(s);return {"card-id":typeof o.name=="string"?o.name:null,status:o.status??null,error:o.error??null,requires:y(o.requires),requires_satisfied:y(o.requires_satisfied),requires_missing:y(o.requires_missing),provides_declared:y(o.provides_declared),provides_runtime:y(o.provides_runtime)}})}}async function L(r){let e=String(r.cardId||"").trim();if(!e)throw new Error("inspectCardDefinitionAndRuntime requires cardId");let n=t(await S(i.status({}),"status")),o=y(n.cards).map(t).find(p=>p.name===e);if(!o)throw new Error(`card "${e}" not found in board status`);let d=t(await T(m,e));if(J(d))throw Object.assign(new Error(`card "${e}" not found`),{statusCode:404});let f=F(d),c=y(o.requires_satisfied).filter(p=>typeof p=="string"&&!!p),g=y(o.provides_runtime).filter(p=>typeof p=="string"&&!!p),b=Object.fromEntries(await Promise.all(c.map(async p=>[p,await S(i.getOutputsDataObject({params:{key:p}}),`getOutputsDataObject(${p})`)]))),R=Object.fromEntries(await Promise.all(g.map(async p=>[p,await S(i.getOutputsDataObject({params:{key:p}}),`getOutputsDataObject(${p})`)]))),C=t(await S(i.getOutputsComputedValues({params:{key:e}}),"getOutputsComputedValues")),l=await S(i.getOutputsFetchedSources({params:{key:e}}),"getOutputsFetchedSources"),_=y(d.source_defs).map(t),w={};for(let p of _)typeof p.bindTo=="string"&&typeof p.outputFile=="string"&&(w[p.outputFile]=p.bindTo);let A={};for(let[p,j]of Object.entries(l)){let q=w[p]??p;if(!I||typeof j!="string"){A[q]=null;continue}try{A[q]=I({cardId:e,ref:j});}catch{A[q]=null;}}let P={card_data:t(d.card_data),requires:b,fetched_sources:A,computed_values:C};return {cardId:e,card_status_in_board:o,card_definition_and_static_data:f,refs_for_fetched_source_files:l,runtime_data:{requires:b,provides:R,computed_values:C,rendered_view:N(d,P)}}}async function E(r){let e=String(r.cardId||"").trim();if(!e)throw new Error("inspectChatMessagesOnCards requires cardId");let n=typeof r.turnId=="string"?r.turnId:"",s=r.allTurns===true,o=typeof r.tailTurnsBeforeId=="string"?r.tailTurnsBeforeId:"",d=s?void 0:r.lastUserTurns??(n?void 0:1),f=r.tail,c={...d===void 0?{}:{tailTurns:d},...n?{turnId:n}:{},...s?{allTurns:true}:{},...o?{tailTurnsBeforeId:o}:{}},g=Object.keys(c).length>0?{params:{cardId:e},body:c}:{params:{cardId:e}},b=h(k.readAll(g),"chatStore.readAll"),R=t(await T(m,e)),C=y(t(R.card_data).files).map((w,A)=>({idx:A,stored_name:t(w).stored_name})).filter(w=>typeof w.stored_name=="string"&&w.stored_name.length>0),_=(Array.isArray(b.records)?b.records:[]).map(w=>{let P=t(w.payload),p={...w},j=typeof w?.role=="string"?w.role:typeof P.role=="string"?String(P.role):"",q=typeof w?.text=="string"?w.text:typeof P.text=="string"?String(P.text):"";if(j==="system"){let $=ie(q);if($!==null&&C.some(O=>O.idx===$)){let O=`Retrieve using inspect-file-contents --card-id ${e} --file-idx ${$}`;p.retrieval_hint=O,Object.keys(P).length>0&&typeof w.role!="string"&&(p.payload={...P,retrieval_hint:O});}}return p});return {cardId:e,messages:typeof f=="number"&&f>=0?_.slice(-f):_}}async function H(r){let e=String(r.cardId||"").trim(),n=Number(r.fileIdx);if(!e)throw new Error("inspectFileContents requires cardId");if(!Number.isInteger(n)||n<0)throw new Error("inspectFileContents requires fileIdx to be a non-negative integer");let s=t(await T(m,e)),o=y(t(s.card_data).files).map(t);if(n>=o.length)throw new Error(`attachment index ${n} is out of range for card "${e}"`);let d=o[n],f=typeof d.stored_name=="string"?d.stored_name:null;return {cardId:e,fileIdx:n,downloadUrl:v({cardId:e,fileIdx:n,storedName:f}),...typeof d.name=="string"?{name:d.name}:{},...typeof d.stored_name=="string"?{stored_name:d.stored_name}:{},...typeof d.mime_type=="string"?{mime_type:d.mime_type}:{},...typeof d.size=="number"?{size:d.size}:{},...typeof d.uploaded_at=="string"?{uploaded_at:d.uploaded_at}:{}}}async function D(r){return await u.validateCardPreflight({body:ce(r.candidateCardContent)})}function G(r){if(!r.mockRequires||typeof r.mockRequires!="object"||Array.isArray(r.mockRequires))throw new Error("preflightMaterializeCandidateCard requires mockRequires");if(!r.mockFetchedSources||typeof r.mockFetchedSources!="object"||Array.isArray(r.mockFetchedSources))throw new Error("preflightMaterializeCandidateCard requires mockFetchedSources");let e=u.evalCardCompute({body:{"card-content":r.candidateCardContent,"mock-requires":r.mockRequires,"mock-fetched-sources":r.mockFetchedSources}});if(e.status!=="success")return e;let n=t(K(e,"evalCardCompute")),s=t(r.candidateCardContent),o={card_data:t(s.card_data),requires:t(r.mockRequires),fetched_sources:t(r.mockFetchedSources),computed_values:t(n.computed_values)};return {status:"success",data:{cardId:typeof n.cardId=="string"?n.cardId:typeof s.id=="string"?s.id:"(unknown)",ok:n.ok===true,computed_values:t(n.computed_values),errors:y(n.errors).map(d=>{let f=t(d);return {bindTo:typeof f.bindTo=="string"?f.bindTo:"",error:typeof f.error=="string"?f.error:""}}),provides_outputs:W(s,o),rendered_view:N(s,o)}}}async function Q(r){return await u.probeSourcePreflight({params:{sourceIdx:r.sourceIdx},body:{"card-content":r.candidateCardContent,"mock-projections":r.mockProjections}})}async function X(r){return await u.runSourcePreflight({params:{sourceIdx:r.sourceIdx},body:{"card-content":r.candidateCardContent,"mock-projections":r.mockProjections}})}async function Y(r){let e=String(r.cardId||"").trim();if(!e)throw new Error("preflightRunSingleSourceInLiveCard requires cardId");if(!r.mockRequires||typeof r.mockRequires!="object"||Array.isArray(r.mockRequires))throw new Error("preflightRunSingleSourceInLiveCard requires mockRequires");let n=t(await T(m,e)),s=y(n.source_defs).filter(d=>!!d&&typeof d=="object"&&!Array.isArray(d)),o={};if(r.sourceIdx>=0&&r.sourceIdx<s.length){let d=s[r.sourceIdx],f=a.enrichSourcesSync([d],{card_data:t(n.card_data),requires:r.mockRequires});Array.isArray(f)&&f.length>0&&(o=t(f[0]._projections));}return await u.runSourcePreflight({params:{sourceIdx:r.sourceIdx},body:{"card-content":n,"mock-requires":r.mockRequires,"mock-projections":o}})}async function Z(r){let e=t(await S(u.simulateCardCycle({body:{"card-content":r.candidateCardContent,"mock-requires":r.mockRequires}}),"simulateCardCycle")),n=t(r.candidateCardContent),s=t(e.validation),o=y(e.source_probes),d=y(e.projection_errors),f=t(e.fetched_sources),c=y(e.compute_errors),g=t(e.computed_values),b={card_data:t(n.card_data),requires:r.mockRequires,fetched_sources:f,computed_values:g},R=[];for(let C of y(s.issues))typeof C=="string"&&C&&R.push(C);for(let C of o){let l=t(C),_=typeof l.bindTo=="string"?l.bindTo:"source",w=typeof l.error=="string"?l.error:"";w&&R.push(`${_}: ${w}`);}for(let C of d){let l=t(C),_=typeof l.bindTo=="string"?l.bindTo:"source",w=typeof l.key=="string"?l.key:"projection",A=typeof l.error=="string"?l.error:"projection failed";R.push(`${_}.${w}: ${A}`);}for(let C of c){let l=t(C),_=typeof l.bindTo=="string"?l.bindTo:"compute",w=typeof l.error=="string"?l.error:"compute failed";R.push(`${_}: ${w}`);}return {status:"success",data:{cardId:typeof e.cardId=="string"?e.cardId:"(unknown)",ok:e.ok===true,issues:R,provides_outputs:W(n,b),rendered_view:N(n,b)}}}async function ee(r){let e=String(r.cardId||"").trim();if(!e)throw new Error("manageReadCard requires cardId");let n=await S(m.get({params:{id:e}}),"cardStore.get"),s=Array.isArray(n.cards)?n.cards.map(t):[];if(s.some(J))throw Object.assign(new Error(`Card "${e}" not found`),{statusCode:404});return s.map(o=>F(o))}async function re(r){let e=String(r.cardId||"").trim(),n=String(r.role||"").trim(),s=typeof r.text=="string"?r.text:"",o=typeof r.turn=="string"?r.turn:"";if(!e)throw new Error("manageAddChatEntryAndAnyAttachments requires cardId");if(!n)throw new Error("manageAddChatEntryAndAnyAttachments requires role");if(n==="assistant"&&o){let c=h(k.readAll({params:{cardId:e},body:{turnId:o}}),"chatStore.readAll(existing turn messages)"),g=Array.isArray(c.records)?c.records.find(b=>b.role==="assistant"&&String(b.turn||"")===o):void 0;if(g)return {status:"success",data:{cardId:e,id:String(g.id),role:n,turn:o,files:Array.isArray(g.files)?g.files:[]}}}let d=await Promise.all(y(r.files).map(async c=>{let g=t(c),b=String(g.file_name??g.fileName??g.name??"").trim(),R=String(g.content_type??g.contentType??"application/octet-stream");if(!b)throw new Error("file entry requires file_name");return (await x({cardId:e,fileName:b,contentType:R,bytes:B(g)})).file}));d.forEach((c,g)=>{let b=n==="assistant"?`AI generated: ${String(c.name||"")} as ${String(c.stored_name||"")} #${g}`:`file uploaded: ${String(c.name||"")} as ${String(c.stored_name||"")} #${g}`;h(k.append({params:{cardId:e},body:{role:"system",text:b,files:[],turn:o}}),"chatStore.append(system attachment message)");});let f=h(k.append({params:{cardId:e},body:{role:n,text:s,files:d,turn:o}}),"chatStore.append");return {status:"success",data:{cardId:e,id:String(f.id),role:n,turn:o,files:d}}}async function te(r){let e=String(r.cardId||"").trim(),n=t(r.candidateCardContent),s=F(n);if(!e)throw new Error("manageUpsertCard requires cardId");if(typeof s.id!="string"||!s.id.trim())throw new Error("candidateCardContent.id must be a non-empty string");if(s.id!==e)throw new Error(`candidateCardContent.id must match cardId (${e})`);let o=await D({candidateCardContent:s}),d=t(o),f=t(d.data);if(d.status!=="success"||f.isValid!==true)return {status:"fail",step:"validate",validation:o};let c=null;try{c=await T(m,e);}catch{c=null;}let g=c&&ue(t(c),"meta")?{...s,meta:t(c).meta}:s,b=await m.set({body:g});h(b,"cardStore.set");let R;try{R=await i.upsertCard({params:{cardId:e,restart:!0}}),h(R,"upsertCard");}catch(l){try{c&&await m.set({body:c});}catch{}throw l}let C=null;try{C=await i.cardRefreshedNotify({params:{cardId:e}}),h(C,"cardRefreshedNotify");}catch{C=null;}return {status:"success",data:{validation:o,card_saved:null,board_result:R,refresh_notify:C}}}async function ne(r){let e=String(r.cardId||"").trim();if(!e)throw new Error("manageRemoveCard requires cardId");let n=await i.removeCard({params:{id:e}});h(n,"removeCard");let s=await m.del({params:{id:e}});return h(s,"cardStore.del"),{status:"success",data:{board_result:n,store_result:s}}}async function ae(r){let e=String(r.cardId||"").trim();if(!e)throw new Error("adminReadCard requires cardId");let n=await S(m.get({params:{id:e}}),"cardStore.get");return Array.isArray(n.cards)?n.cards.map(s=>t(s)):[]}async function oe(r){let e=String(r.cardId||"").trim(),n=t(r.candidateCardContent),s=F(n);if(!e)throw new Error("adminUpsertCard requires cardId");if(typeof s.id!="string"||!s.id.trim())throw new Error("candidateCardContent.id must be a non-empty string");if(s.id!==e)throw new Error(`candidateCardContent.id must match cardId (${e})`);let o=await D({candidateCardContent:s}),d=t(o),f=t(d.data);if(d.status!=="success"||f.isValid!==true)return {status:"fail",step:"validate",validation:o};let c=null;try{c=await T(m,e);}catch{c=null;}let g=c?t(t(c).meta):{},b={...s,meta:{...g,__visible_controlplane_only:true}},R=await m.set({body:b});h(R,"cardStore.set");let C;try{C=await i.upsertCard({params:{cardId:e,restart:!0}}),h(C,"upsertCard");}catch(_){try{c&&await m.set({body:c});}catch{}throw _}let l=null;try{l=await i.cardRefreshedNotify({params:{cardId:e}}),h(l,"cardRefreshedNotify");}catch{l=null;}return {status:"success",data:{validation:o,card_saved:null,board_result:C,refresh_notify:l}}}function se(r){let e=String(r.cardId||"").trim();if(!e)throw new Error("getChatProcessing requires cardId");let n=K(k.isProcessing({params:{cardId:e}}),"chatStore.isProcessing");return {cardId:e,active:!!n.active}}function de(r){let e=String(r.cardId||"").trim();if(!e)throw new Error("setChatProcessing requires cardId");if(typeof r.active!="boolean")throw new Error("setChatProcessing requires boolean active");return h(k.setProcessing({params:{cardId:e},body:{active:r.active}}),"chatStore.setProcessing"),{cardId:e,active:r.active}}return {discoverSourceKinds:U,inspectBoardRuntimeStatus:M,inspectCardDefinitionAndRuntime:L,inspectChatMessagesOnCards:E,inspectFileContents:H,preflightValidateCandidateCardDefinition:D,preflightMaterializeCandidateCard:G,preflightProbeSingleSourceInCandidateCard:Q,preflightRunSingleSourceInCandidateCard:X,preflightRunSingleSourceInLiveCard:Y,preflightRunOneCycleWithCandidateCard:Z,manageReadCard:ee,manageAddChatEntryAndAnyAttachments:re,manageUpsertCard:te,manageRemoveCard:ne,adminReadCard:ae,adminUpsertCard:oe,getChatProcessing:se,setChatProcessing:de}}async function S(a,i){return h(await a,i)}export{me as a};//# sourceMappingURL=chunk-SCWHDI3I.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-SCWHDI3I.js.map
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
'use strict';var s="b64:";function a(e){let n=new TextEncoder().encode(e),r=globalThis.Buffer,t;if(r)t=r.from(n).toString("base64");else if(typeof btoa=="function"){let o="";for(let i of n)o+=String.fromCharCode(i);t=btoa(o);}else throw new Error("No base64 encoder available in this runtime");return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function g(e){let n=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-e.length%4)%4),r=globalThis.Buffer;if(r)return r.from(n,"base64").toString("utf8");if(typeof atob=="function"){let t=atob(n),o=new Uint8Array(t.length);for(let i=0;i<t.length;i+=1)o[i]=t.charCodeAt(i);return new TextDecoder().decode(o)}throw new Error("No base64 decoder available in this runtime")}function l(e){return `${s}${a(JSON.stringify(e))}`}function u(e){if(!e.startsWith(s))throw new Error(`Invalid ref format (expected ${s}<base64url(json)>): ${e}`);let n;try{n=JSON.parse(g(e.slice(s.length)));}catch{throw new Error(`Invalid ref format (malformed base64url/json): ${e}`)}if(!n||typeof n!="object")throw new Error(`Invalid ref format (expected object payload): ${e}`);let r=n;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}}async function f(e,n,r){let t=e.tryAcquire();if(!t)return false;try{await n();}finally{t();}return r?.(),true}
|
|
2
|
+
exports.a=l;exports.b=u;exports.c=f;//# sourceMappingURL=chunk-SFVO2LB2.cjs.map
|
|
3
|
+
//# sourceMappingURL=chunk-SFVO2LB2.cjs.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';var chunkSFVO2LB2_cjs=require('./chunk-SFVO2LB2.cjs');function i(e,t){let n;return /\.m?js$/i.test(e)?n="local-node":/\.py$/i.test(e)?n="local-python":n="local-process",{meta:"task-executor",howToRun:n,whatToRun:chunkSFVO2LB2_cjs.a({kind:"fs-path",value:e}),...t?{extra:t}:{}}}function s(e){return JSON.stringify(e)}function a(e){let t;try{t=JSON.parse(e);}catch{throw new Error(`parseExecutionRef: invalid JSON \u2014 ${e}`)}if(typeof t!="object"||t===null||typeof t.howToRun!="string"||typeof t.whatToRun!="string")throw new Error(`parseExecutionRef: missing required fields howToRun/whatToRun \u2014 ${e}`);return t}exports.a=i;exports.b=s;exports.c=a;//# sourceMappingURL=chunk-U2N6MCD5.cjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-U2N6MCD5.cjs.map
|