yaml-flow 8.5.0 → 8.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/browser/asset-integrity.json +3 -3
- package/browser/board-livecards-client.js +1 -1
- package/cli/browser-api/board-live-cards-browser-adapter.d.ts +1 -1
- package/cli/bundled/board-live-cards-cli.mjs +13 -13
- package/cli/bundled/chat-store-cli.mjs +13 -13
- package/cli/{types-D2s3VzyY.d.ts → types-H3EMBPY2.d.ts} +7 -2
- package/examples/board/demo-shell-with-server.html +2 -2
- package/examples/board/doc.html +2 -2
- package/examples/board/server/README-mcp-api.md +680 -0
- package/examples/board/test/server-http-mcp-test.js +391 -34
- package/examples/board-local/demo-shell-localstorage.html +3 -3
- package/lib/artifacts-store-public.d.cts +1 -1
- package/lib/artifacts-store-public.d.ts +1 -1
- package/lib/board-live-cards-mcp.cjs +1 -1
- package/lib/board-live-cards-mcp.d.cts +42 -5
- package/lib/board-live-cards-mcp.d.ts +42 -5
- package/lib/board-live-cards-mcp.js +1 -1
- package/lib/board-live-cards-node.cjs +14 -14
- package/lib/board-live-cards-node.d.cts +4 -4
- package/lib/board-live-cards-node.d.ts +4 -4
- package/lib/board-live-cards-node.js +14 -14
- package/lib/{board-live-cards-public-CvkDfZQ7.d.cts → board-live-cards-public-B13InXhC.d.cts} +7 -2
- package/lib/{board-live-cards-public-DdVhH4M-.d.ts → board-live-cards-public-BGS22cMb.d.ts} +7 -2
- package/lib/board-live-cards-public.cjs +1 -1
- package/lib/board-live-cards-public.d.cts +1 -1
- package/lib/board-live-cards-public.d.ts +1 -1
- package/lib/board-live-cards-public.js +1 -1
- package/lib/board-live-cards-server-runtime.cjs +4 -4
- package/lib/board-live-cards-server-runtime.d.cts +2 -2
- package/lib/board-live-cards-server-runtime.d.ts +2 -2
- package/lib/board-live-cards-server-runtime.js +4 -4
- package/lib/card-store-public.d.cts +1 -1
- package/lib/card-store-public.d.ts +1 -1
- package/lib/chat-store-public.cjs +1 -1
- package/lib/chat-store-public.d.cts +6 -1
- package/lib/chat-store-public.d.ts +6 -1
- package/lib/chat-store-public.js +1 -1
- package/lib/server-runtime/index.cjs +4 -4
- package/lib/server-runtime/index.d.cts +3 -3
- package/lib/server-runtime/index.d.ts +3 -3
- package/lib/server-runtime/index.js +4 -4
- package/lib/{types-QNI__eAf.d.ts → types-30R357js.d.ts} +1 -1
- package/lib/{types-NM_d_1oZ.d.cts → types-CIgsh56O.d.cts} +1 -1
- package/package.json +1 -1
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import {createRequire}from'module';import'ajv-formats';var vt="b64:";function Zr(e){let t=new TextEncoder().encode(e),r=globalThis.Buffer,s;if(r)s=r.from(t).toString("base64");else if(typeof btoa=="function"){let a="";for(let i of t)a+=String.fromCharCode(i);s=btoa(a);}else throw new Error("No base64 encoder available in this runtime");return s.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function Qr(e){let t=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-e.length%4)%4),r=globalThis.Buffer;if(r)return r.from(t,"base64").toString("utf8");if(typeof atob=="function"){let s=atob(t),a=new Uint8Array(s.length);for(let i=0;i<s.length;i+=1)a[i]=s.charCodeAt(i);return new TextDecoder().decode(a)}throw new Error("No base64 decoder available in this runtime")}function Ne(e){return `${vt}${Zr(JSON.stringify(e))}`}function ut(e){if(!e.startsWith(vt))throw new Error(`Invalid ref format (expected ${vt}<base64url(json)>): ${e}`);let t;try{t=JSON.parse(Qr(e.slice(vt.length)));}catch{throw new Error(`Invalid ref format (malformed base64url/json): ${e}`)}if(!t||typeof t!="object")throw new Error(`Invalid ref format (expected object payload): ${e}`);let r=t;if(typeof r.kind!="string"||typeof r.value!="string")throw new Error(`Invalid ref format (payload must contain string kind/value): ${e}`);return {kind:r.kind,value:r.value}}async function Wt(e,t,r){let s=e.tryAcquire();if(!s)return false;try{await t();}finally{s();}return r?.(),true}var Qe={RUNNING:"running",COMPLETED:"completed",FAILED:"failed",INACTIVATED:"inactivated"};function Pe(e){return e?Array.isArray(e.provides)?e.provides:[]:[]}function et(e){return e?Array.isArray(e.requires)?e.requires:[]:[]}function Yt(e){return e.tasks??{}}function Ut(e){return e?e.status===Qe.FAILED||e.status===Qe.INACTIVATED:false}function Xt(e,t){return e.refreshStrategy??t?.refreshStrategy??"data-changed"}function Zt(e){return e.maxExecutions}function Qt(e,t){let r=new Set;for(let[s,a]of Object.entries(t))if(a.status===Qe.COMPLETED){let i=e.tasks[s];i&&Pe(i).forEach(u=>r.add(u));}return Array.from(r)}function er(e,t){let r={};return e.forEach(s=>{let a=t[s];if(!a)return;Pe(a).forEach(c=>{r[c]||(r[c]=[]),r[c].push(s);});}),r}function tr(e,t,r){let s=e.tasks[t]??xt(),a={};if(r){let c=r.tasks[t],u=et(c);for(let m of u)for(let[h,b]of Object.entries(r.tasks))if(Pe(b).includes(m)){let v=e.tasks[h];v?.lastDataHash&&(a[m]=v.lastDataHash);break}}let i={...s,status:"running",startedAt:new Date().toISOString(),lastUpdated:new Date().toISOString(),progress:0,error:void 0,startConsumedHashes:a};return {...e,tasks:{...e.tasks,[t]:i},lastUpdated:new Date().toISOString()}}function rr(e,t,r,s,a,i){let c=e.tasks[r]??xt(),u=t.tasks[r];if(!u)throw new Error(`Task "${r}" not found in graph`);let m;s&&u.on&&u.on[s]?m=u.on[s]:m=Pe(u);let h=c.startConsumedHashes?{...c.startConsumedHashes}:{...c.lastConsumedHashes};if(!c.startConsumedHashes){let M=u.requires??[];for(let J of M)for(let[A,B]of Object.entries(t.tasks))if(Pe(B).includes(J)){let E=e.tasks[A];E?.lastDataHash&&(h[J]=E.lastDataHash);break}}let b={...c,status:"completed",completedAt:new Date().toISOString(),lastUpdated:new Date().toISOString(),executionCount:c.executionCount+1,lastEpoch:c.executionCount+1,lastDataHash:a,data:i,lastConsumedHashes:h,error:void 0},v=[...new Set([...e.availableOutputs,...m])];return {...e,tasks:{...e.tasks,[r]:b},availableOutputs:v,lastUpdated:new Date().toISOString()}}function nr(e,t,r,s){let a=e.tasks[r]??xt(),i=t.tasks[r];if(i?.retry){let m=a.retryCount+1;if(m<=i.retry.max_attempts){let h={...a,status:"not-started",retryCount:m,lastUpdated:new Date().toISOString(),error:s};return {...e,tasks:{...e.tasks,[r]:h},lastUpdated:new Date().toISOString()}}}let c={...a,status:"failed",failedAt:new Date().toISOString(),lastUpdated:new Date().toISOString(),error:s,executionCount:a.executionCount+1},u=e.availableOutputs;if(i?.on_failure&&i.on_failure.length>0&&(u=[...new Set([...e.availableOutputs,...i.on_failure])]),i?.circuit_breaker&&c.executionCount>=i.circuit_breaker.max_executions){let m=i.circuit_breaker.on_break;u=[...new Set([...u,...m])];}return {...e,tasks:{...e.tasks,[r]:c},availableOutputs:u,lastUpdated:new Date().toISOString()}}function or(e,t,r,s){let a=e.tasks[t]??xt(),i={...a,progress:typeof s=="number"?s:a.progress,messages:[...a.messages??[],...r?[{message:r,timestamp:new Date().toISOString(),status:a.status}]:[]],lastUpdated:new Date().toISOString()};return {...e,tasks:{...e.tasks,[t]:i},lastUpdated:new Date().toISOString()}}function sr(e,t){let r=e.tasks[t];if(!r)return e;let s={...r,status:"not-started",startedAt:void 0,completedAt:void 0,failedAt:void 0,error:void 0,data:void 0,progress:null,lastUpdated:new Date().toISOString()};return {...e,tasks:{...e.tasks,[t]:s},lastUpdated:new Date().toISOString()}}function xt(){return {status:"not-started",executionCount:0,retryCount:0,lastEpoch:0,messages:[],progress:null}}function At(e,t){let r=`live-${Date.now()}`,s={};for(let i of Object.keys(e.tasks))s[i]=ir();let a={status:"running",tasks:s,availableOutputs:[],stuckDetection:{is_stuck:false,stuck_description:null,outputs_unresolvable:[],tasks_blocked:[]},lastUpdated:new Date().toISOString(),executionId:r,executionConfig:{executionMode:e.settings.execution_mode??"eligibility-mode",conflictStrategy:e.settings.conflict_strategy??"alphabetical",completionStrategy:e.settings.completion}};return {config:e,state:a}}function en(e,t){let{config:r,state:s}=e;if("executionId"in t&&t.executionId&&t.executionId!==s.executionId)return e;switch(t.type){case "task-started":return {config:r,state:tr(s,t.taskName,r)};case "task-completed":return {config:r,state:rr(s,r,t.taskName,t.result,t.dataHash,t.data)};case "task-failed":return {config:r,state:nr(s,r,t.taskName,t.error)};case "task-progress":return {config:r,state:or(s,t.taskName,t.message,t.progress)};case "task-restart":return {config:r,state:sr(s,t.taskName)};case "inject-tokens":return {config:r,state:{...s,availableOutputs:[...new Set([...s.availableOutputs,...t.tokens])],lastUpdated:new Date().toISOString()}};case "agent-action":return {config:r,state:dn(s,t.action)};case "task-upsert":return tn(e,t.taskName,t.taskConfig);case "task-removal":return rn(e,t.taskName);case "node-requires-add":return nn(e,t.nodeName,t.tokens);case "node-requires-remove":return on(e,t.nodeName,t.tokens);case "node-provides-add":return sn(e,t.nodeName,t.tokens);case "node-provides-remove":return an(e,t.nodeName,t.tokens);default:return e}}function ar(e,t){return t.reduce((r,s)=>en(r,s),e)}function tn(e,t,r){let s=!!e.config.tasks[t];return {config:{...e.config,tasks:{...e.config.tasks,[t]:r}},state:{...e.state,tasks:{...e.state.tasks,[t]:s?e.state.tasks[t]:ir()},lastUpdated:new Date().toISOString()}}}function rn(e,t){if(!e.config.tasks[t])return e;let{[t]:r,...s}=e.config.tasks,{[t]:a,...i}=e.state.tasks;return {config:{...e.config,tasks:s},state:{...e.state,tasks:i,lastUpdated:new Date().toISOString()}}}function nn(e,t,r){let s=e.config.tasks[t];if(!s)return e;let a=et(s),i=r.filter(c=>!a.includes(c));return i.length===0?e:{config:{...e.config,tasks:{...e.config.tasks,[t]:{...s,requires:[...a,...i]}}},state:e.state}}function on(e,t,r){let s=e.config.tasks[t];if(!s)return e;let a=et(s),i=a.filter(c=>!r.includes(c));return i.length===a.length?e:{config:{...e.config,tasks:{...e.config.tasks,[t]:{...s,requires:i}}},state:e.state}}function sn(e,t,r){let s=e.config.tasks[t];if(!s)return e;let a=Pe(s),i=r.filter(c=>!a.includes(c));return i.length===0?e:{config:{...e.config,tasks:{...e.config.tasks,[t]:{...s,provides:[...a,...i]}}},state:e.state}}function an(e,t,r){let s=e.config.tasks[t];if(!s)return e;let a=Pe(s),i=a.filter(c=>!r.includes(c));return i.length===a.length?e:{config:{...e.config,tasks:{...e.config.tasks,[t]:{...s,provides:i}}},state:e.state}}function Ct(e){return {version:1,config:e.config,state:e.state,snapshotAt:new Date().toISOString()}}function It(e){if(!e||typeof e!="object")throw new Error("Invalid snapshot: expected an object");let t=e;if(!t.config||typeof t.config!="object")throw new Error('Invalid snapshot: missing or invalid "config"');if(!t.state||typeof t.state!="object")throw new Error('Invalid snapshot: missing or invalid "state"');let r=t.config,s=t.state;if(!r.settings||typeof r.settings!="object")throw new Error("Invalid snapshot: config.settings missing");if(!r.tasks||typeof r.tasks!="object")throw new Error("Invalid snapshot: config.tasks missing");if(!s.tasks||typeof s.tasks!="object")throw new Error("Invalid snapshot: state.tasks missing");if(!Array.isArray(s.availableOutputs))throw new Error("Invalid snapshot: state.availableOutputs must be an array");return {config:r,state:s}}function ir(){return {status:"not-started",executionCount:0,retryCount:0,lastEpoch:0,messages:[],progress:null}}function dn(e,t){let r=new Date().toISOString();switch(t){case "stop":return {...e,status:"stopped",lastUpdated:r};case "pause":return {...e,status:"paused",lastUpdated:r};case "resume":return {...e,status:"running",lastUpdated:r};default:return e}}function kt(e){let{config:t,state:r}=e,s=Yt(t);if(Object.keys(s).length===0)return {eligible:[],pending:[],unresolved:[],blocked:[],conflicts:{}};let i=cn(s),c=Qt(t,r.tasks),u=new Set([...c,...r.availableOutputs]),m=[],h=[],b=[],v=[];for(let[J,A]of Object.entries(s)){let B=r.tasks[J],E=Xt(A,t.settings),V=E!=="once";if(B?.status===Qe.RUNNING||Ut(B))continue;let Y=Zt(A);if(Y!==void 0&&B&&B.executionCount>=Y||A.circuit_breaker&&B&&B.executionCount>=A.circuit_breaker.max_executions||!V&&B?.status===Qe.COMPLETED)continue;if(V&&B?.status===Qe.COMPLETED){let l=et(A),f=false;switch(E){case "data-changed":{l.length>0&&l.some(T=>{for(let[w,_]of Object.entries(s))if(Pe(_).includes(T)){let F=r.tasks[w];if(!F)continue;let oe=B.lastConsumedHashes?.[T];return F.lastDataHash==null?F.executionCount>B.lastEpoch:F.lastDataHash!==oe}return false})||(f=true);break}case "epoch-changed":{l.length>0&&l.some(T=>{for(let[w,_]of Object.entries(s))if(Pe(_).includes(T)){let F=r.tasks[w];if(F&&F.executionCount>B.lastEpoch)return true}return false})||(f=true);break}case "time-based":{let R=A.refreshInterval??0;if(R<=0){f=true;break}let T=B.completedAt;if(!T){f=true;break}(Date.now()-Date.parse(T))/1e3<R&&(f=true);break}case "manual":f=true;break}if(f)continue}let x=et(A);if(x.length===0){m.push(J);continue}let L=[],k=[],y=[];for(let l of x){if(u.has(l))continue;let f=i[l]||[];f.length===0?L.push(l):f.every(T=>Ut(r.tasks[T]))?y.push({token:l,failedProducer:f[0]}):k.push(l);}L.length>0?b.push({taskName:J,missingTokens:L}):y.length>0?v.push({taskName:J,failedTokens:y.map(l=>l.token),failedProducers:[...new Set(y.map(l=>l.failedProducer))]}):k.length>0?h.push({taskName:J,waitingOn:k}):m.push(J);}let M={};if(m.length>1){let J=er(m,s);for(let[A,B]of Object.entries(J))B.length>1&&(M[A]=B);}return {eligible:m,pending:h,unresolved:b,blocked:v,conflicts:M}}function cn(e){let t={};for(let[r,s]of Object.entries(e)){for(let a of Pe(s))t[a]||(t[a]=[]),t[a].push(r);if(s.on)for(let a of Object.values(s.on))for(let i of a)t[i]||(t[i]=[]),t[i].includes(r)||t[i].push(r);if(s.on_failure)for(let a of s.on_failure)t[a]||(t[a]=[]),t[a].includes(r)||t[a].push(r);}return t}var Rt=class{buffer=[];append(t){this.buffer.push(t);}drain(){let t=this.buffer;return this.buffer=[],t}get size(){return this.buffer.length}};function Gt(e){let t=Vt(e);return un(t)}function Vt(e){if(e==null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return "["+e.map(Vt).join(",")+"]";let t=e;return "{"+Object.keys(t).sort().map(s=>JSON.stringify(s)+":"+Vt(t[s])).join(",")+"}"}function un(e){let t=0xcbf29ce484222325n,r=0x100000001b3n,s=0xffffffffffffffffn;for(let a=0;a<e.length;a++)t^=BigInt(e.charCodeAt(a)),t=t*r&s;return t.toString(16).padStart(16,"0")}function ln(e){if(typeof Buffer<"u")return Buffer.from(e,"utf8").toString("base64url");if(typeof btoa=="function"){let t=new TextEncoder().encode(e),r="";for(let s of t)r+=String.fromCharCode(s);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}throw new Error("No base64 encoder available in this runtime")}function fn(e){if(typeof Buffer<"u")return Buffer.from(e,"base64url").toString("utf8");if(typeof atob=="function"){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r=t+"=".repeat((4-t.length%4)%4),s=atob(r),a=new Uint8Array(s.length);for(let i=0;i<s.length;i++)a[i]=s.charCodeAt(i);return new TextDecoder().decode(a)}throw new Error("No base64 decoder available in this runtime")}function dr(e){let t=JSON.stringify({t:e,n:Date.now().toString(36)+Math.random().toString(36).slice(2,6)});return ln(t)}function pn(e){try{let t=JSON.parse(fn(e));return typeof t?.t=="string"?{taskName:t.t}:null}catch{return null}}function cr(e,t,r){let{handlers:s,onNodeRemoved:a,onDrain:i}=t,c=new Rt,u="state"in e&&"config"in e?e:At(e),m=false,h=new Set,b=new Map(Object.entries(s)),v=new Rt,M=false,J=false;function A(){if(!m){if(M){J=true;return}M=true;try{do J=!1,B();while(J)}finally{M=false;}}}function B(){let x=v.drain(),L=c.drain(),k=[...x,...L];if(k.length>0&&(u=ar(u,k),a)){for(let l of k)if(l.type==="task-removal")try{a(l.taskName);}catch(f){console.warn("[reactive] onNodeRemoved failed:",f instanceof Error?f.message:String(f));}}let y=kt(u);k.length>0&&i?.(k,u,y);for(let l of y.eligible)Y(l);for(let l of k)if(l.type==="task-progress"){let{taskName:f,update:R}=l;if(!u.config.tasks[f])continue;let w=u.state.tasks[f];if(!w||w.status!=="running")continue;let _=dr(f),F=V(f,_,R).catch(oe=>{m||(v.append({type:"task-failed",taskName:f,error:oe.message??String(oe),timestamp:new Date().toISOString()}),A());}).finally(()=>{h.delete(F);});h.add(F);}}function E(x){let k=u.config.tasks[x].requires??[],y=new Map;for(let[f,R]of Object.entries(u.config.tasks))for(let T of R.provides??[])y.set(T,f);let l={};for(let f of k){let R=y.get(f);R?l[f]=u.state.tasks[R]?.data:l[f]=void 0;}return l}async function V(x,L,k){let y=u.config.tasks[x],l=y.taskHandlers??[],f=E(x);for(let R of l){let T=b.get(R);if(!T)throw new Error(`Handler '${R}' not found in registry (task '${x}')`);let w={nodeId:x,state:f,taskState:u.state.tasks[x],config:y,callbackToken:L,update:k};if(await T(w)==="task-initiate-failure")throw new Error(`Handler '${R}' returned task-initiate-failure (task '${x}')`)}}function Y(x){let k=u.config.tasks[x]?.taskHandlers;if(!k||k.length===0)return;v.append({type:"task-started",taskName:x,timestamp:new Date().toISOString()}),A();let y=dr(x),l=V(x,y).catch(f=>{m||(v.append({type:"task-failed",taskName:x,error:f.message??String(f),timestamp:new Date().toISOString()}),A());}).finally(()=>{h.delete(l);});h.add(l);}return {push(x){m||(x.type==="task-completed"&&x.data&&!x.dataHash&&(x={...x,dataHash:Gt(x.data)}),c.append(x),A());},pushAll(x){if(!m){for(let L of x)L.type==="task-completed"&&L.data&&!L.dataHash?c.append({...L,dataHash:Gt(L.data)}):c.append(L);A();}},resolveCallback(x,L,k){if(m)return;let y=pn(x);if(!y)return;let{taskName:l}=y;if(u.config.tasks[l]){if(k&&k.length>0)c.append({type:"task-failed",taskName:l,error:k.join("; "),timestamp:new Date().toISOString()});else {let f=L&&Object.keys(L).length>0?Gt(L):void 0;c.append({type:"task-completed",taskName:l,data:L,dataHash:f,timestamp:new Date().toISOString()});}A();}},addNode(x,L){m||(c.append({type:"task-upsert",taskName:x,taskConfig:L,timestamp:new Date().toISOString()}),A());},removeNode(x){m||(c.append({type:"task-removal",taskName:x,timestamp:new Date().toISOString()}),A());},addRequires(x,L){m||(c.append({type:"node-requires-add",nodeName:x,tokens:L,timestamp:new Date().toISOString()}),A());},removeRequires(x,L){m||(c.append({type:"node-requires-remove",nodeName:x,tokens:L,timestamp:new Date().toISOString()}),A());},addProvides(x,L){m||(c.append({type:"node-provides-add",nodeName:x,tokens:L,timestamp:new Date().toISOString()}),A());},removeProvides(x,L){m||(c.append({type:"node-provides-remove",nodeName:x,tokens:L,timestamp:new Date().toISOString()}),A());},registerHandler(x,L){b.set(x,L);},unregisterHandler(x){b.delete(x);},retrigger(x){m||u.config.tasks[x]&&(c.append({type:"task-restart",taskName:x,timestamp:new Date().toISOString()}),A());},retriggerAll(x){if(!m){for(let L of x)u.config.tasks[L]&&c.append({type:"task-restart",taskName:L,timestamp:new Date().toISOString()});A();}},snapshot(){return Ct(u)},getState(){return u},getSchedule(){return kt(u)},async waitForHandlers(){h.size>0&&await Promise.allSettled([...h]);},async dispose(x){x?.wait&&h.size>0&&await Promise.allSettled([...h]),m=true;}}}var mn=createRequire(import.meta.url);mn("./jsonata-sync.cjs");var yn=createRequire(import.meta.url),_t=yn("./jsonata-sync.cjs"),fr=_t;function ur(e,t){if(!t||!e)return;let r=t.split("."),s=e;for(let a=0;a<r.length;a++){if(s==null)return;s=s[r[a]];}return s}function pr(e,t,r){let s=t.split("."),a=e;for(let i=0;i<s.length-1;i++)(a[s[i]]==null||typeof a[s[i]]!="object")&&(a[s[i]]={}),a=a[s[i]];a[s[s.length-1]]=r;}async function Cn(e,t){if(!e?.compute?.length)return e;e.card_data||(e.card_data={}),e.computed_values={},e._sourcesData=t?.sourcesData??{};let r=e.requires??{},s={card_data:e.card_data,requires:r,expects_data:r,fetched_sources:e._sourcesData,data:e.computed_values,computed_values:e.computed_values};for(let a of e.compute)try{let i=await _t(a.expr).evaluate(s);pr(e.computed_values,a.bindTo,i),s.computed_values=e.computed_values;}catch{}return e}function kn(e,t){if(!e?.compute?.length)return {ok:true,node:e};e.card_data||(e.card_data={}),e.computed_values={},e._sourcesData=t?.sourcesData??{};let r=e.requires??{},s={card_data:e.card_data,requires:r,expects_data:r,fetched_sources:e._sourcesData,data:e.computed_values,computed_values:e.computed_values},a=[];for(let i of e.compute)try{let c=fr(i.expr).evaluate(s);pr(e.computed_values,i.bindTo,c),s.computed_values=e.computed_values;}catch(c){let u=c instanceof Error?c.message:String(c);a.push({bindTo:i.bindTo,error:u});}return a.length>0?{ok:true,node:e,errors:a}:{ok:true,node:e}}async function Rn(e,t,r){let s={...r??{},card_data:t.card_data??{},requires:t.requires??{},fetched_sources:t._sourcesData??{},computed_values:t.computed_values??{}};return _t(e).evaluate(s)}function bn(e,t){return t.startsWith("fetched_sources.")?ur(e._sourcesData??{},t.slice(16)):ur(e,t)}var lr=new Set(["metric","table","editable-table","chart","form","filter","list","notes","todo","alert","narrative","badge","text","markdown","ref","custom","actions"]),Sn=new Set(["id","meta","requires","provides","view","card_data","compute","source_defs"]);function wn(e){let t=[];if(!e||typeof e!="object"||Array.isArray(e))return {ok:false,errors:["Node must be a non-null object"]};let r=e;(typeof r.id!="string"||!r.id)&&t.push("id: required, must be a non-empty string");for(let s of Object.keys(r))Sn.has(s)||t.push(`Unknown top-level key: "${s}"`);if((r.card_data==null||typeof r.card_data!="object"||Array.isArray(r.card_data))&&t.push("card_data: required, must be an object"),r.meta!=null)if(typeof r.meta!="object"||Array.isArray(r.meta))t.push("meta: must be an object");else {let s=r.meta;s.title!=null&&typeof s.title!="string"&&t.push("meta.title: must be a string"),s.tags!=null&&!Array.isArray(s.tags)&&t.push("meta.tags: must be an array");}if(r.requires!=null&&!Array.isArray(r.requires)&&t.push("requires: must be an array of strings"),r.provides!=null&&(Array.isArray(r.provides)?r.provides.forEach((s,a)=>{if(!s||typeof s!="object"||Array.isArray(s))t.push(`provides[${a}]: must be an object with bindTo and ref`);else {let i=s;(typeof i.bindTo!="string"||!i.bindTo)&&t.push(`provides[${a}]: missing required "bindTo" string`),(typeof i.ref!="string"||!i.ref)&&t.push(`provides[${a}]: missing required "ref" string`);}}):t.push("provides: must be an array of { bindTo, ref } bindings")),r.compute!=null&&(Array.isArray(r.compute)?r.compute.forEach((s,a)=>{if(!s||typeof s!="object"||Array.isArray(s))t.push(`compute[${a}]: must be a compute step object`);else {let i=s;(typeof i.bindTo!="string"||!i.bindTo)&&t.push(`compute[${a}]: missing required "bindTo" property`),(typeof i.expr!="string"||!i.expr)&&t.push(`compute[${a}]: missing required "expr" string (JSONata expression)`);}}):t.push("compute: must be an array of compute steps")),r.source_defs!=null)if(!Array.isArray(r.source_defs))t.push("source_defs: must be an array");else {let s=new Set,a=new Set;r.source_defs.forEach((i,c)=>{if(!i||typeof i!="object"||Array.isArray(i))t.push(`source_defs[${c}]: must be an object`);else {let u=i;typeof u.bindTo!="string"||!u.bindTo?t.push(`source_defs[${c}]: missing required "bindTo" property`):(s.has(u.bindTo)&&t.push(`source_defs[${c}]: bindTo "${u.bindTo}" is not unique across source_defs`),s.add(u.bindTo)),typeof u.outputFile!="string"||!u.outputFile?t.push(`source_defs[${c}]: missing required "outputFile" property`):(a.has(u.outputFile)&&t.push(`source_defs[${c}]: outputFile "${u.outputFile}" is not unique across source_defs`),a.add(u.outputFile)),u.optionalForCompletionGating!=null&&typeof u.optionalForCompletionGating!="boolean"&&t.push(`source_defs[${c}]: optionalForCompletionGating must be a boolean`);}});}if(r.view!=null)if(typeof r.view!="object"||Array.isArray(r.view))t.push("view: must be an object");else {let s=r.view;!Array.isArray(s.elements)||s.elements.length===0?t.push("view.elements: required, must be a non-empty array"):s.elements.forEach((a,i)=>{if(!a||typeof a!="object"){t.push(`view.elements[${i}]: must be an object`);return}!a.kind||typeof a.kind!="string"?t.push(`view.elements[${i}].kind: required, must be a string`):lr.has(a.kind)||t.push(`view.elements[${i}].kind: unknown kind "${a.kind}". Valid: ${[...lr].join(", ")}`),a.data!=null&&(typeof a.data!="object"||Array.isArray(a.data))&&t.push(`view.elements[${i}].data: must be an object`);}),s.layout!=null&&(typeof s.layout!="object"||Array.isArray(s.layout))&&t.push("view.layout: must be an object"),s.features!=null&&(typeof s.features!="object"||Array.isArray(s.features))&&t.push("view.features: must be an object");}return {ok:t.length===0,errors:t}}async function vn(e,t){if(!e||e.length===0)return [];let r={card_data:t.card_data??{},requires:t.requires??{}};return Promise.all(e.map(async s=>{let a={};if(s.projections&&typeof s.projections=="object"&&!Array.isArray(s.projections)){for(let[i,c]of Object.entries(s.projections))if(typeof c=="string"&&c.trim().length>0)try{a[i]=await _t(c).evaluate(r);}catch{a[i]=void 0;}}return {...s,_projections:a}}))}function xn(e,t){if(!e||e.length===0)return [];let r={card_data:t.card_data??{},requires:t.requires??{}};return e.map(s=>{let a={};if(s.projections&&typeof s.projections=="object"&&!Array.isArray(s.projections)){for(let[i,c]of Object.entries(s.projections))if(typeof c=="string"&&c.trim().length>0)try{a[i]=fr(c).evaluate(r);}catch{a[i]=void 0;}}return {...s,_projections:a}})}var tt={run:Cn,runSync:kn,eval:Rn,resolve:bn,validate:wn,enrichSources:vn,enrichSourcesSync:xn};function gr(e){return JSON.stringify(e)}function mr(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}function bt(e,t){function r(){return e.readIndex()??{}}function s(a,i,c){let u=String(i||"").split(".").filter(Boolean);if(u.length===0)return c&&typeof c=="object"&&!Array.isArray(c)?c:{value:c};let m={...a},h=m;for(let b=0;b<u.length-1;b++){let v=u[b],M=h[v],J=M&&typeof M=="object"&&!Array.isArray(M)?{...M}:{};h[v]=J,h=J;}return h[u[u.length-1]]=c,m}return {readCard(a){let i=r()[a];return !i||!e.cardExists(i.key)?null:e.readCard(i.key)},readCardKey(a){return r()[a]?.key??null},readAllCards(){let a=[];for(let[i,c]of Object.entries(r())){if(!e.cardExists(c.key))continue;let u=e.readCard(c.key);u?a.push(u):t?.(`[card-store] could not read card "${i}" at key "${c.key}"`);}return a},readChecksumIndex(){let a={};for(let[i,c]of Object.entries(r()))a[i]=c.checksum;return a},changedSince(a){let i=r(),c=[];for(let[u,m]of Object.entries(i))a[u]!==m.checksum&&c.push(u);for(let u of Object.keys(a))i[u]||c.push(u);return c},validateUpsert(a,i){let c=r(),u=c[a],m=Object.entries(c).find(([,h])=>h.key===i);return u&&u.key!==i?{ok:false,error:`Card id "${a}" is already mapped to key "${u.key}", cannot remap to "${i}"`}:m&&m[0]!==a?{ok:false,error:`Key "${i}" is already mapped to card id "${m[0]}", cannot remap to "${a}"`}:{ok:true}},writeCard(a,i,c){let u=r(),m=c??u[a]?.key??e.defaultCardKey(a),h=e.writeCard(m,i);u[a]={key:m,checksum:h,updatedAt:new Date().toISOString()},e.writeIndex(u);},patchCard(a,i,c){let u=r(),m=u[a];if(!m||!e.cardExists(m.key))throw new Error(`card "${a}" not found`);let h=e.readCard(m.key);if(!h||typeof h!="object"||Array.isArray(h))throw new Error(`card "${a}" is not patchable`);let b=s(h,i,c),v=e.writeCard(m.key,b);u[a]={key:m.key,checksum:v,updatedAt:new Date().toISOString()},e.writeIndex(u);},removeCard(a){let i=r(),c=i[a];c&&(e.removeCard(c.key),delete i[a],e.writeIndex(i));},readIndex(){return r()}}}function Et(e,t){return {readSourceData(r,s){let a=e.read(`${r}/${s}`);if(a==null)return null;let i=a.trim();if(!i)return null;try{return JSON.parse(i)}catch{return i}},ingestSourceDataStaged(r,s,a,i){let c=t(a);e.write(`${r}/.staged/${i}/${s}`,c);},commitSourceData(r,s,a){let i=`${r}/.staged/${a}/${s}`,c=e.read(i);return c==null?false:(e.write(`${r}/${s}`,c),e.remove(i),true)},hasSource(r,s){return e.exists(`${r}/${s}`)},listSources(r){return e.listKeys(`${r}/`).filter(s=>!s.includes("/.staged/")).map(s=>s.slice(`${r}/`.length))}}}function Rr(e){function t(r){let s=e.readAllEntries();if(!r)return s;let a=s.findIndex(i=>i.id===r);return a===-1?s:s.slice(a+1)}return {readEntriesAfterCursor(r){let s=t(r);return s.length===0?{events:[],newCursor:r}:{events:s.map(a=>a.event),newCursor:s[s.length-1].id}},pendingCount(r){return t(r).length},appendEvent(r){e.appendEntry({id:e.generateId(),event:r});}}}function br(e,t){return {appendEntries(r,s){if(!r||s.length===0)return;let a=e.read(r)??[];e.write(r,[...a,...s]);},dispatchEntriesForJournalId(r,s){if(!r)return;let a=e.read(r);if(!(!a||a.length===0)){for(let i of a)try{s(i);}catch(c){let u=c instanceof Error?c.message:String(c);try{t(i,u);}catch{}}e.delete(r);}}}}var Tt="v1",ot="board/graph",Sr="board/lastJournalProcessedId";function hr(e){return `cards/${e}/runtime`}function wr(e){return {readRuntime(t){return e.read(hr(t))??{_sources:{}}},writeRuntime(t,r){e.write(hr(t),r);}}}function An(e,t){let r={...e};for(let s of t.deleteKeys)delete r[s];return {...r,...t.shallowMerge}}function vr(e){return {readSnapshot(t){return e.readValues(t)},commitSnapshot(t,r){if(r.schemaVersion!==Tt)throw new Error(`Unsupported snapshot schema version: ${r.schemaVersion}`);let s=e.readValues(t);if(s.version!==r.expectedVersion)return {ok:false,reason:"version-mismatch",currentVersion:s.version};let a=An(s.values,r);return {ok:true,newVersion:e.writeValues(t,a,r.deleteKeys)}}}}function Kt(e){function t(r){let s=e.read(r);return s==null?null:typeof s=="string"?s:JSON.stringify(s)}return {readTaskExecutorRef(){let r=t("task-executor");if(r?.trim())return mr(r.trim())},writeTaskExecutorRef(r){e.write("task-executor",gr(r));},readChatHandlerFlow(){return e.read("chat-handler-flow")},writeChatHandlerFlow(r){e.write("chat-handler-flow",r);},readCardStoreRef(){return t("card-store-ref")},writeCardStoreRef(r){e.write("card-store-ref",r);},readOutputsStoreRef(){return t("outputs-store-ref")},writeOutputsStoreRef(r){e.write("outputs-store-ref",r);},readScratchStoreRef(){return t("scratch-store-ref")},writeScratchStoreRef(r){e.write("scratch-store-ref",r);},readArchiveStoreRef(){return t("archive-store-ref")},writeArchiveStoreRef(r){e.write("archive-store-ref",r);},readChatStoreRef(){return t("chat-store-ref")},writeChatStoreRef(r){e.write("chat-store-ref",r);},readArtifactsStoreRef(){return t("artifacts-store-ref")},writeArtifactsStoreRef(r){e.write("artifacts-store-ref",r);}}}function xr(e){return {writeComputedValues(t,r){e.write(`cards/${t}/computed_values`,r);},readComputedValues(t){return e.read(`cards/${t}/computed_values`)},readAllComputedValues(){let t={};for(let r of e.listKeys("cards/")){let s=r.match(/^cards\/([^/]+)\/computed_values$/);s&&(t[s[1]]=e.read(r));}return t},writeDataObjects(t){for(let[r,s]of Object.entries(t))r&&e.write(`data-objects/${r}`,s);},readDataObject(t){return e.read(`data-objects/${t}`)},readAllDataObjects(){let t={};for(let r of e.listKeys("data-objects/"))t[r.slice(13)]=e.read(r);return t},writeStatusSnapshot(t){e.write("status",t);},readStatusSnapshot(){return e.read("status")}}}function yr(e){return e?{lastRequestedToken:e.lastRequestedToken,lastCompletedToken:e.lastCompletedToken,lastCompletionStatus:e.lastCompletionStatus??(e.lastCompletedToken?"success":"not-started"),queueRequestedToken:e.queueRequestedToken}:{lastCompletionStatus:"not-started"}}function In(e){return e?.lastRequestedToken?e.lastCompletedToken!==e.lastRequestedToken:false}function Cr(e,t){return e?.lastRequestedToken?In(e)?"in-flight":!e.lastCompletedToken||e.lastCompletedToken<t?"dispatch":"idle":"dispatch"}function _n(e,t){return {...e,lastCompletedToken:t,lastCompletionStatus:"success"}}function kr(e,t){return {...e,lastCompletedToken:t,lastCompletionStatus:"failure"}}function Ot(e,t){let r=t.state.tasks,s=t.config.tasks,a=Object.keys(r),i=kt(t),c={completed:0,failed:0,in_progress:0,pending:0,blocked:0,unresolved:0},u=new Map;for(let A of i.pending)u.set(A.taskName,A.waitingOn);for(let A of i.unresolved)u.set(A.taskName,A.missingTokens);for(let A of i.blocked)u.set(A.taskName,A.failedTokens);let m=new Map;for(let[A,B]of Object.entries(s))for(let E of B.requires??[]){let V=m.get(E)??[];V.push(A),m.set(E,V);}let h=a.sort().map(A=>{let B=r[A],E=s[A]??{requires:[],provides:[]};B.status==="completed"?c.completed+=1:B.status==="failed"?c.failed+=1:B.status==="in-progress"&&(c.in_progress+=1);let V=E.requires??[],Y=E.provides??[],x=Object.keys(B.data??{}).sort(),L=V.filter(T=>t.state.availableOutputs.includes(T)),k=V.filter(T=>!t.state.availableOutputs.includes(T)),y=u.get(A)??k,l=new Set;for(let T of Y)for(let w of m.get(T)??[])w!==A&&l.add(w);let f=B.failedAt,R=B.error?{message:B.error,code:"TASK_FAILED",at:f,source:"task-runtime"}:void 0;return {name:A,status:B.status,error:R,requires:V,requires_satisfied:L,requires_missing:k,provides_declared:Y,provides_runtime:x,blocked_by:y,unblocks:Array.from(l).sort(),runtime:{attempt_count:B.executionCount??0,restart_count:B.retryCount??0,in_progress_since:B.status==="in-progress"?B.startedAt??null:null,last_transition_at:B.lastUpdated??null,last_completed_at:B.completedAt??null,last_restarted_at:B.startedAt??null,status_age_ms:B.lastUpdated?0:null}}});c.pending=i.pending.length,c.blocked=i.blocked.length,c.unresolved=i.unresolved.length;let b=h.map(A=>({name:A.name,fanOut:A.unblocks.length})).sort((A,B)=>B.fanOut-A.fanOut||A.name.localeCompare(B.name)),v=b.length>0?b[0]:{name:null,fanOut:0},M=new Set;for(let A of Object.values(s))for(let B of A.requires??[])M.add(B);let J=0;for(let[A,B]of Object.entries(s)){let E=(B.requires??[]).length===0,Y=(B.provides??[]).some(x=>(m.get(x)??[]).some(L=>L!==A));E&&!Y&&(J+=1);}return {schema_version:"v1",meta:{board:{path:e}},summary:{card_count:a.length,completed:c.completed,eligible:i.eligible.length,pending:c.pending,blocked:c.blocked,unresolved:c.unresolved,failed:c.failed,in_progress:c.in_progress,orphan_cards:J,topology:{edge_count:Array.from(M).length,max_fan_out_card:v.name,max_fan_out:v.fanOut}},cards:h}}function En(){return new Date().toISOString()}function Ar(e,t,r,s,a,i,c){return async u=>{let m=[],h=r.cardStore.readCard(u.nodeId);if(!h)return "task-initiate-failure";let b=h.id,v=h.card_data??{},M=h.source_defs??[],J=M.filter(N=>N.optionalForCompletionGating!==true),A=r.cardRuntimeStore.readRuntime(b),B=false,E=()=>{B&&(r.cardRuntimeStore.writeRuntime(b,A),B=false);},V=N=>yr(A._sources[N]),Y=(N,$)=>{A._sources[N]=yr($),B=true;},x=u.taskState?.executionCount??0;if(A._lastExecutionCount!==x&&(A._sources={},A._lastExecutionCount=x,B=true),u.update){let N=u.update,$=N.outputFile;if($){let D=V($);if(N.failure){let se=N.rqt??D.lastRequestedToken??D.queueRequestedToken;se&&Y($,kr(D,se));}else {let se=N.rqt;if(!D.lastCompletedToken||se>D.lastCompletedToken){let te=typeof N.deliveryToken=="string"?N.deliveryToken:void 0,Z=false;te&&(Z=r.fetchedSourcesStore.commitSourceData(b,$,te)),Z?Y($,_n(D,se)):Y($,kr(D,se));}}E();}}let k={};for(let N of M)if(N.outputFile){let $=r.fetchedSourcesStore.readSourceData(b,N.outputFile);$!==null&&(k[N.bindTo]=$);}let y={};for(let[N,$]of Object.entries(u.state??{}))if($!==null&&typeof $=="object"&&!Array.isArray($)){let D=$[N];y[N]=D!==void 0?D:$;}else y[N]=$;let l={id:b,card_data:{...v},requires:y,source_defs:M,compute:h.compute};l._sourcesData=k,h.compute&&tt.runSync(l,{sourcesData:k}),(i??r.outputStore.writeComputedValues.bind(r.outputStore))(b,l.computed_values??{});let f={...h},R=tt.enrichSourcesSync(Array.isArray(h.source_defs)?h.source_defs:void 0,{card_data:h.card_data,requires:y}),T=e.value;f.source_defs=Array.isArray(R)?R.map(N=>({...N,boardDir:typeof N.boardDir=="string"&&N.boardDir?N.boardDir:T})):R;let w=En(),_=u.update?void 0:w,F=J.filter(N=>{let $=N.outputFile;if(typeof $!="string"||!$)return true;let D=V($);_&&(D={...D,queueRequestedToken:_},Y($,D));let se=D.queueRequestedToken??D.lastRequestedToken??w,te=Cr(D,se);return te==="in-flight"?false:te==="dispatch"});if(E(),F.length>0){let N=false,$=w;for(let D of F){let se=D.outputFile;if(typeof se!="string"||!se)continue;let te=V(se),Z=te.queueRequestedToken??w;Y(se,{...te,lastRequestedToken:Z}),$=Z,N=true;}return N&&E(),N&&(m.push({taskKind:"source-fetch",payload:{boardRef:Ne(e),enrichedCard:f,callbackToken:u.callbackToken,rqt:$}}),r.executionRequestStore.appendEntries(t,m)),"task-initiated"}if(J.some(N=>{let $=N.outputFile;if(typeof $!="string"||!$)return false;let D=V($),se=D.queueRequestedToken??D.lastRequestedToken??w;return Cr(D,se)==="in-flight"}))return "task-initiated";let X=h.provides??[],ce={};for(let{bindTo:N,ref:$}of X)ce[N]=tt.resolve(l,$);return (c??r.outputStore.writeDataObjects.bind(r.outputStore))(ce),M.filter(N=>{if(N.optionalForCompletionGating!==true)return false;let $=V(N.outputFile);return !$.lastRequestedToken||!$.lastCompletedToken?true:$.lastCompletedToken<=$.lastRequestedToken}).length>0&&m.push({taskKind:"source-fetch",payload:{boardRef:Ne(e),enrichedCard:f,callbackToken:u.callbackToken,rqt:w}}),s(u.nodeId,ce),m.length>0&&r.executionRequestStore.appendEntries(t,m),"task-initiated"}}var Ht={settings:{completion:"manual",refreshStrategy:"data-changed"},tasks:{}};function Ir(e){return {[ot]:e.graph,[Sr]:e.lastDrainedJournalId}}function _r(e){let t=e[ot],r=e[Sr];if(!t||typeof t!="object")throw new Error(`State snapshot is missing required key: ${ot}`);return {graph:t,lastDrainedJournalId:typeof r=="string"?r:""}}function Er(e){let t=e.requires,r=e.provides?.map(s=>s.bindTo)??[];return {requires:t&&t.length>0?t:void 0,provides:r,taskHandlers:["card-handler"],description:e.meta?.title??e.id}}function jt(e){function t(i){return {status:"success",data:i}}function r(i){return {status:"fail",error:i}}function s(i){return {status:"error",error:i instanceof Error?i.message:String(i)}}function a(i){if(Array.isArray(i))return i;if(i&&typeof i=="object"){let c=i;return Array.isArray(c.files)?c.files:[i]}return null}return {get(i){try{let c=i.params?.id;if(c){let u=e.readCard(c);return u?t({cards:[u]}):r(`card "${c}" not found`)}return t({cards:e.readAllCards()})}catch(c){return s(c)}},set(i){try{let c=i.body;if(c==null)return r("set requires a body (card object or array of cards)");let u=Array.isArray(c)?c:[c];for(let m of u){if(typeof m.id!="string")return r("each card must have a string `id` field");e.writeCard(m.id,m);}return t({count:u.length})}catch(c){return s(c)}},del(i){try{let c=i.body?.ids??[],u=i.params?.id,m=u?[...c,u]:c;if(m.length===0)return r("del requires body.ids (string[]) or params.id");for(let h of m)e.removeCard(h);return t({count:m.length})}catch(c){return s(c)}},patch(i){try{let c=i.params?.id,u=i.params?.path;if(!c)return r("patch requires params.id");if(!u)return r("patch requires params.path");let m=i.body,h=m&&Object.prototype.hasOwnProperty.call(m,"value")?m.value:i.body;return e.patchCard(c,u,h),t({count:1})}catch(c){return s(c)}},appendFiles(i){try{let c=i.params?.id;if(!c)return r("appendFiles requires params.id");let u=e.readCard(c);if(!u)return r(`card "${c}" not found`);let m=a(i.body);if(!m||m.length===0)return r("appendFiles requires a file metadata object, array, or body.files array");let h=u.card_data&&typeof u.card_data=="object"&&!Array.isArray(u.card_data)?u.card_data:{},b=Array.isArray(h.files)?h.files:[],v=[...b,...m],M=m.map((A,B)=>({idx:b.length+B,entry:A})),J=this.patch({params:{id:c,path:"card_data.files"},body:{value:v}});return J.status!=="success"?J:t({files_added:M})}catch(c){return s(c)}}}}function re(e){return e!==void 0?{status:"success",data:e}:{status:"success"}}function H(e){return {status:"fail",error:e}}function ne(e){return {status:"error",error:e instanceof Error?e.message:String(e)}}function Tn(e){let t=new TextEncoder().encode(e),r=Array.from(t,s=>String.fromCharCode(s)).join("");return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Or(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r=t+"=".repeat((4-t.length%4)%4),s=atob(r),a=Uint8Array.from(s,i=>i.charCodeAt(0));return new TextDecoder().decode(a)}function Bt(e){try{let t=JSON.parse(Or(e));return typeof t?.t=="string"?{taskName:t.t}:null}catch{return null}}function On(e){return Tn(JSON.stringify(e))}function Tr(e){try{let t=JSON.parse(Or(e));return typeof t?.cbk=="string"&&typeof t?.cid=="string"&&typeof t?.b=="string"&&typeof t?.d=="string"?t:null}catch{return null}}function _e(){return new Date().toISOString()}function jr(e,t){let r=t.onWarn??(()=>{}),s=Ne(e);function a(I){if(I.length!==0)try{let g=t.publishBoardChangeNotifications?.(I);g&&typeof g.catch=="function"&&g.catch(j=>r(`[board-live-cards-public] publishBoardChangeNotifications failed: ${j instanceof Error?j.message:String(j)}`));}catch(g){r(`[board-live-cards-public] publishBoardChangeNotifications failed: ${g instanceof Error?g.message:String(g)}`);}}function i(){let I=u().readCardStoreRef();if(!I)throw new Error(`Board at ${e.value} has no card store configured. Run: init --base-ref <ref> --store-ref <b64-ref>`);let g=t.kvStorageForRef(I);return {readIndex(){return g.read("_index")},writeIndex(j){g.write("_index",j);},readCard(j){return g.read(j)},writeCard(j,U){return g.write(j,U),t.hashFn(U)},removeCard(j){g.delete(j);},cardExists(j){return g.read(j)!==null},defaultCardKey(j){return j}}}let c={readValues(I){let g=t.kvStorage("state-snapshot"),j=g.listKeys().sort();if(j.length===0)return {version:null,values:{}};let U={};for(let Q of j)U[Q]=g.read(Q);return {version:t.hashFn(U),values:U}},writeValues(I,g,j){let U=t.kvStorage("state-snapshot");for(let Q of j)U.delete(Q);for(let[Q,ie]of Object.entries(g))U.write(Q,ie);return t.hashFn(g)}},u=()=>Kt(t.kvStorage("config")),m=()=>vr(c),h=()=>Rr(t.journalAdapter()),b=()=>bt(i(),r),v=()=>{let I=u().readOutputsStoreRef();if(!I)throw new Error(`Board at ${e.value} has no outputs store configured. Run: init --outputs-store-ref <b64-ref>`);return xr(t.kvStorageForRef(I))},M=()=>{let I=u().readArchiveStoreRef();return I?t.archiveFactoryForRef(I):t.archiveFactory()};function J(){return !!m().readSnapshot(e.value).values[ot]}function A(){let I=m().readSnapshot(e.value);if(!I.values[ot])throw new Error(`Board not initialized at ${e.value}`);return _r(I.values)}function B(I,g){let j=m().commitSnapshot(e.value,{schemaVersion:Tt,expectedVersion:g,commitId:t.genId(),committedAt:_e(),deleteKeys:[],shallowMerge:Ir(I)});if(!j.ok)throw new Error(`Snapshot commit failed (version mismatch): expected=${g??"null"} current=${j.currentVersion??"null"}`)}function E(I){h().appendEvent(I);}async function V(){let I=(P,z)=>{let fe=P.payload,je=(fe?.enrichedCard??{}).id??fe?.cardId??"unknown";E({type:"task-failed",taskName:je,error:z,timestamp:_e()});},g=br(t.kvStorage("execution-requests"),I),j=wr(t.kvStorage("card-runtime")),U=Et(t.blobStorage("sources"),P=>t.resolveBlob(P)),Q=new Map,ie={readRuntime(P){return Q.get(P)??j.readRuntime(P)},writeRuntime(P,z){Q.set(P,z);}},Ie=[],he=new Map,Te={readSourceData(P,z){let fe=`${P}/${z}`;return he.has(fe)?he.get(fe):U.readSourceData(P,z)},ingestSourceDataStaged(P,z,fe,Fe){U.ingestSourceDataStaged(P,z,fe,Fe);},commitSourceData(P,z,fe){let Fe=`${P}/.staged/${fe}/${z}`,Ye=t.blobStorage("sources").read(Fe);if(Ye==null)return false;let Xe=`${P}/${z}`,pt=Ye.trim();try{he.set(Xe,JSON.parse(pt));}catch{he.set(Xe,pt);}return Ie.push({cardId:P,outputFile:z,deliveryToken:fe}),true},hasSource(P,z){let fe=`${P}/${z}`;return he.has(fe)?true:U.hasSource(P,z)},listSources(P){let z=U.listSources(P),fe=new Set;for(let je of he.keys())je.startsWith(`${P}/`)&&fe.add(je.slice(`${P}/`.length));let Fe=new Set([...z,...fe]);return Array.from(Fe)}},Ae={cardStore:b(),cardRuntimeStore:ie,fetchedSourcesStore:Te,outputStore:v(),executionRequestStore:g},Ue=A(),Ge=It(Ue.graph),{events:We,newCursor:qe}=h().readEntriesAfterCursor(Ue.lastDrainedJournalId),Ve=[],lt=[],rt=[],st=new Map,St=new Set,Pt=(P,z)=>{Ve.push({type:"task-completed",taskName:P,data:z,timestamp:_e()});try{M().stream("exec-history").append({taskName:P,status:"completed",completedAt:_e()});}catch{}},ee=(P,z)=>{E({type:"task-failed",taskName:P,error:z,timestamp:_e()});try{M().stream("exec-history").append({taskName:P,status:"failed",error:z,completedAt:_e()});}catch{}},at=cr(Ge,{handlers:{"card-handler":Ar(e,qe,Ae,Pt,ee,(P,z)=>{lt.push({cardId:P,values:z});},P=>{rt.push(P);})},onNodeRemoved:P=>{st.delete(P),Q.delete(P),St.add(P);}});for(Ve=We;Ve.length>0;){let P=Ve;Ve=[];for(let z of P)if(z.type==="task-restart"){let fe=Ae.cardStore.readCard(z.taskName);fe&&st.set(z.taskName,fe);}at.pushAll(P),await at.waitForHandlers();}let ft=at.getState();await at.dispose({wait:true});let $e=m().readSnapshot(e.value).version;B({lastDrainedJournalId:qe,graph:Ct(ft)},$e);for(let{cardId:P,values:z}of lt)Ae.outputStore.writeComputedValues(P,z);for(let P of rt)Ae.outputStore.writeDataObjects(P);for(let[P,z]of Q)j.writeRuntime(P,z);for(let{cardId:P,outputFile:z,deliveryToken:fe}of Ie)U.commitSourceData(P,z,fe);let it;try{it=Ot(s,ft),Ae.outputStore.writeStatusSnapshot(it);}catch(P){r(`[board-live-cards-public] status publish failed: ${P instanceof Error?P.message:String(P)}`);}let Ke=[];for(let{cardId:P,values:z}of lt)Ke.push({kind:"computed_values",cardId:P,values:z});for(let P of rt)for(let[z,fe]of Object.entries(P))z&&Ke.push({kind:"data_object",key:z,payload:fe});for(let[P,z]of st)Ke.push({kind:"card_refreshed",cardId:P,card:z});for(let P of St)Ke.push({kind:"card_removed",cardId:P});it!==void 0&&Ke.push({kind:"status",status:it}),a(Ke);let wt=u().readTaskExecutorRef()??{howToRun:"built-in",whatToRun:Ne({kind:"built-in",value:"source-cli-task-executor"})};g.dispatchEntriesForJournalId(qe,P=>{if(P.taskKind!=="source-fetch"){r(`[process-accumulated-events] unknown taskKind "${P.taskKind}" \u2014 skipping`);return}let z=P.payload,fe=z.enrichedCard?.id??"unknown",Fe=z.enrichedCard?.source_defs??[];for(let je of Fe){if(!je.outputFile){r(`[dispatch] source "${je.bindTo}" has no outputFile \u2014 skipping`);continue}let Ye=On({cbk:z.callbackToken,rg:e.value,br:Ne(e),cid:fe,b:je.bindTo,d:je.outputFile,cs:void 0,rqt:z.rqt});t.dispatchExecution(wt,{source_def:je,base_ref:Ne(e),callback:{token:Ye,via:t.selfRef}}).catch(Xe=>ee(fe,Xe instanceof Error?Xe.message:String(Xe)));}});}async function Y(){try{let I=()=>{let j=A(),{events:U}=h().readEntriesAfterCursor(j.lastDrainedJournalId);U.length<=0||(Y(),t.requestProcessAccumulated?.());},g=await Wt(t.lock,V,I);return re({ran:g!==!1})}catch(I){return ne(I)}}function x(){Y(),t.requestProcessAccumulated?.();}function L(I){try{let g=I.params?.cardStoreRef;if(!g)return H("init requires params.cardStoreRef \u2014 create a card store with card-store-cli and pass its ref here");if(!J()){let Ae=At(Ht);B({lastDrainedJournalId:"",graph:Ct(Ae)},null);}let j=I.params?.outputsStoreRef;if(!j)return H("init requires params.outputsStoreRef \u2014 pass the outputs store ref here");let U=I.params?.scratchStoreRef,Q=I.params?.archiveStoreRef,ie=I.params?.chatStoreRef,Ie=I.params?.artifactsStoreRef,he=u();he.writeCardStoreRef(g),he.writeOutputsStoreRef(j),U&&he.writeScratchStoreRef(U),Q&&he.writeArchiveStoreRef(Q),ie&&he.writeChatStoreRef(ie),Ie&&he.writeArtifactsStoreRef(Ie);let Te=I.body??{};Te["task-executor-ref"]&&he.writeTaskExecutorRef(Te["task-executor-ref"]),Object.prototype.hasOwnProperty.call(Te,"chat-handler-flow")&&he.writeChatHandlerFlow(Te["chat-handler-flow"]);try{v().writeStatusSnapshot(Ot(s,It(A().graph)));}catch{}return re()}catch(g){return ne(g)}}function k(I){try{let g=v().readStatusSnapshot();if(!g){g=Ot(s,It(A().graph));try{v().writeStatusSnapshot(g);}catch{}}return re(g)}catch(g){return ne(g)}}function y(I){try{let g=I.params?.id;return g?(E({type:"task-removal",taskName:g,timestamp:_e()}),x(),re()):H("removeCard requires params.id")}catch(g){return ne(g)}}function l(I){try{let g=I.params?.cardId;if(!g)return H("addCardFiles requires params.cardId");let j=jt(b()).appendFiles({params:{id:g},body:I.body});if(j.status!=="success")return j;let U=f({params:{cardId:g}});return U.status!=="success"?U:re({cardId:g,files_added:j.data.files_added,notified:!0})}catch(g){return ne(g)}}function f(I){try{let g=I.params?.cardId;if(!g)return H("cardRefreshedNotify requires params.cardId");let j=b().readCard(g);return j?(a([{kind:"card_refreshed",cardId:g,card:j}]),re({cardId:g,notified:!0})):H(`Card "${g}" not found in board at ${e.value}`)}catch(g){return ne(g)}}function R(I){try{let g=I.params?.id;return g?(E({type:"task-restart",taskName:g,timestamp:_e()}),x(),re()):H("retrigger requires params.id")}catch(g){return ne(g)}}async function T(I){return Y()}function w(I){try{let g=I.params?.cardId,j=I.params?.all,U=!!I.params?.restart;if(!g&&!j)return H("upsertCard requires --card-id <id> or --all");let Q=j?b().readAllCards().map(ie=>ie.id):[g];for(let ie of Q)if(!b().readCard(ie))return H(`Card "${ie}" not found in board at ${e.value}`);for(let ie of Q){let Ie=b().readCard(ie),he=Er(Ie),Te=t.hashFn(he),Ae=t.kvStorage("card-upsert"),Ue=Ae.read(ie),Ge=Ue?.taskConfigHash!==Te;if(!(!Ge&&!U)){if(Ge){let We=Ue?.blobRef??b().readCardKey(ie)??ie;E({type:"task-upsert",taskName:ie,taskConfig:he,timestamp:_e()}),Ae.write(ie,{blobRef:We,taskConfigHash:Te,updatedAt:_e()});}U&&E({type:"task-restart",taskName:ie,timestamp:_e()});}}return x(),re()}catch(g){return ne(g)}}function _(I){try{let g=I.params?.token;if(!g)return H("taskFailed requires params.token");let j=I.params?.error??"unknown error",U=Bt(g);if(!U)return H("Invalid callback token");E({type:"task-failed",taskName:U.taskName,error:j,timestamp:_e()});try{M().stream("exec-history").append({taskName:U.taskName,status:"failed",error:j,completedAt:_e()});}catch{}return x(),re()}catch(g){return ne(g)}}function F(I){try{let g=I.params?.token;if(!g)return H("taskProgress requires params.token");let U=(I.body??{}).update??{},Q=Bt(g);return Q?(E({type:"task-progress",taskName:Q.taskName,update:U,timestamp:_e()}),x(),re()):H("Invalid callback token")}catch(g){return ne(g)}}function oe(I){try{let g=I.params?.token,j=I.params?.ref;if(!g)return H("sourceDataFetched requires params.token");if(!j)return H("sourceDataFetched requires params.ref");let U=Tr(g);if(!U)return H("Invalid source token");let{cbk:Q,cid:ie,b:Ie,d:he,cs:Te,rqt:Ae}=U,Ue=Et(t.blobStorage("sources"),Ve=>t.resolveBlob(Ve)),Ge=t.genId();Ue.ingestSourceDataStaged(ie,he,ut(j),Ge);let We=Bt(Q);if(!We)return H("Invalid callback token embedded in source token");let qe=_e();return E({type:"task-progress",taskName:We.taskName,update:{bindTo:Ie,outputFile:he,fetchedAt:qe,deliveryToken:Ge,sourceChecksum:Te,rqt:Ae},timestamp:qe}),x(),re()}catch(g){return ne(g)}}function X(I){try{let g=I.params?.token,j=I.params?.reason??"unknown";if(!g)return H("sourceDataFetchFailure requires params.token");let U=Tr(g);if(!U)return H("Invalid source token");let{cbk:Q,b:ie,d:Ie,cs:he,rqt:Te}=U,Ae=Bt(Q);return Ae?(E({type:"task-progress",taskName:Ae.taskName,update:{bindTo:ie,outputFile:Ie,failure:!0,reason:j,sourceChecksum:he,rqt:Te},timestamp:_e()}),x(),re()):H("Invalid callback token embedded in source token")}catch(g){return ne(g)}}function ce(I){try{let g=u().readCardStoreRef();return g?re({storeRef:g}):H(`Board at ${e.value} has no card store configured`)}catch(g){return ne(g)}}function ye(I){try{let g=u().readOutputsStoreRef();return g?re({storeRef:g}):H(`Board at ${e.value} has no outputs store configured`)}catch(g){return ne(g)}}function N(I){try{let g=u().readScratchStoreRef();return re({storeRef:g})}catch(g){return ne(g)}}function $(I){try{let g=u().readArchiveStoreRef();return re({storeRef:g})}catch(g){return ne(g)}}function D(I){try{let g=u().readChatStoreRef();return re({storeRef:g})}catch(g){return ne(g)}}function se(I){try{let g=u().readArtifactsStoreRef();return re({storeRef:g})}catch(g){return ne(g)}}function te(I){try{let g=I.params?.key;if(!g)return H("getConfig requires params.key");let j=u(),U;switch(g){case "task-executor":U=j.readTaskExecutorRef()??null;break;case "chat-handler-flow":U=j.readChatHandlerFlow()??null;break;case "card-store-ref":U=j.readCardStoreRef();break;case "outputs-store-ref":U=j.readOutputsStoreRef();break;case "scratch-store-ref":U=j.readScratchStoreRef();break;case "archive-store-ref":U=j.readArchiveStoreRef();break;case "chat-store-ref":U=j.readChatStoreRef();break;case "artifacts-store-ref":U=j.readArtifactsStoreRef();break;default:return H(`getConfig: unknown key "${g}"`)}return re({value:U})}catch(g){return ne(g)}}function Z(I){try{let g=I.params?.key;if(!g)return H("getOutputsDataObject requires params.key");let j=v().readDataObject(g);return re(j)}catch(g){return ne(g)}}function Ce(I){try{return re(v().readAllDataObjects())}catch(g){return ne(g)}}function pe(I){try{let g=I.params?.key;if(!g)return H("getOutputsComputedValues requires params.key");let j=v().readComputedValues(g);return re(j)}catch(g){return ne(g)}}function Se(I){try{return re(v().readAllComputedValues())}catch(g){return ne(g)}}function me(){return Et(t.blobStorage("sources"),I=>t.resolveBlob(I))}function ke(I){let g=t.blobStorage("sources").keyRef?.(I);return g?Ne(g):I}function ve(I){try{let g=I.params?.key;if(!g)return H("getOutputsFetchedSources requires params.key");let j=me().listSources(g),U={};for(let Q of j)U[Q]=ke(`${g}/${Q}`);return re(U)}catch(g){return ne(g)}}function Nt(I){try{let g=me(),j=new Set;for(let Q of t.blobStorage("sources").listKeys()){let ie=Q.indexOf("/");ie>0&&!Q.includes("/.staged/")&&j.add(Q.slice(0,ie));}let U={};for(let Q of j){let ie=g.listSources(Q);if(ie.length>0){U[Q]={};for(let Ie of ie)U[Q][Ie]=ke(`${Q}/${Ie}`);}}return re(U)}catch(g){return ne(g)}}return {init:L,status:k,getCardStoreRef:ce,getOutputsStoreRef:ye,getScratchStoreRef:N,getArchiveStoreRef:$,getChatStoreRef:D,getArtifactsStoreRef:se,getConfig:te,getOutputsDataObject:Z,getAllOutputsDataObjects:Ce,getOutputsComputedValues:pe,getAllOutputsComputedValues:Se,getOutputsFetchedSources:ve,getAllOutputsFetchedSources:Nt,removeCard:y,addCardFiles:l,cardRefreshedNotify:f,retrigger:R,processAccumulatedEvents:T,upsertCard:w,taskFailed:_,taskProgress:F,sourceDataFetched:oe,sourceDataFetchFailure:X}}function Br(e,t){let r=()=>Kt(t.kvStorage("config"));function s(){let k=r().readCardStoreRef();if(!k)throw new Error(`Board at ${e.value} has no card store configured. Run: init --base-ref <ref> --store-ref <b64-ref>`);let y=t.kvStorageForRef(k);return {readIndex(){return y.read("_index")},writeIndex(l){y.write("_index",l);},readCard(l){return y.read(l)},writeCard(l,f){return y.write(l,f),t.hashFn(f)},removeCard(l){y.delete(l);},cardExists(l){return y.read(l)!==null},defaultCardKey(l){return l}}}let a=()=>bt(s(),t.onWarn??(()=>{})),i=()=>{let k=r().readScratchStoreRef();return k?t.scratchStorageForRef(k):t.scratchStorage()};function c(k,y){let l=t.validateSchema(y),f=[],R=r().readTaskExecutorRef();if(R&&Array.isArray(y.source_defs))for(let w of y.source_defs){let _=typeof w.bindTo=="string"?w.bindTo:"(unknown)";try{let F;try{F=t.invokeExecutorSync(R,"validate-source-def",[],{timeout:t.executorTimeouts?.validationMs??1e4,input:JSON.stringify(w)});}catch(X){let ce=X;if(F=typeof ce?.stdout=="string"?ce.stdout:"",!F.trim()){f.push(`source "${_}": executor validate-source-def failed \u2014 ${X instanceof Error?X.message:String(X)}`);continue}}let oe=JSON.parse(F.trim());if(!oe.ok&&Array.isArray(oe.errors))for(let X of oe.errors)f.push(`source "${_}": ${X}`);}catch(F){f.push(`source "${_}": executor validate-source-def failed \u2014 ${F instanceof Error?F.message:String(F)}`);}}let T=[...l.errors,...f];return re({cardId:k,isValid:T.length===0,issues:T})}function u(k,y){let l=r().readTaskExecutorRef();if(!l)throw new Error("No task-executor registered for this board");let f=typeof k.bindTo=="string"?k.bindTo:"source",R=i(),T={...k,boardDir:e.value,_projections:y},w=R.create(JSON.stringify(T,null,2),`probe-in-${f}`,".json"),_=R.getUniqueKey(`probe-out-${f}`,".json"),F=R.getUniqueKey(`probe-err-${f}`,".txt"),oe=Ne(R.keyRef(w)),X=Ne(R.keyRef(_)),ce=Ne(R.keyRef(F)),ye=null;try{if(t.invokeExecutorSync(l,"run-source-fetch",["--in-ref",oe,"--out-ref",X,"--err-ref",ce],{timeout:k.timeout??t.executorTimeouts?.probeMs??6e4}),ye=R.read(_),ye===null)throw new Error("Executor produced no output file")}catch(N){let $=R.read(F)?.trim()??(N instanceof Error?N.message:String(N));throw new Error(`Probe failed: ${$}`)}finally{try{R.remove(w);}catch{}try{R.remove(F);}catch{}}return {bindTo:f,result:ye}}function m(k,y,l){let f;try{f=u(k,y);}catch(R){return H(R instanceof Error?R.message:String(R))}if(l){let R=ut(l);t.absoluteBlob.write(R.value,f.result);}return re({bindTo:f.bindTo,resultSizeBytes:f.result.length})}function h(k,y){let l=k.params?.sourceIdx,f=k.params?.outRef;if(l===void 0)return H(`${y} requires params.sourceIdx`);if(!k.body||typeof k.body!="object"||Array.isArray(k.body))return H(`${y} requires card JSON object in body`);let R=k.body,T=R["card-content"]??R,w=R["mock-projections"]??{},_=T.source_defs??[];if(l<0||l>=_.length)return H(`sourceIdx ${l} out of range (card has ${_.length} source(s))`);let F=_[l],oe=typeof F.bindTo=="string"?F.bindTo:"source";return {src:F,bindTo:oe,outRef:f,mockProjections:w}}function b(k){try{let y=k.params?.cardId,l=k.params?.all;if(!y&&!l)return H("validateCard requires --card-id <id> or --all");let f=l?a().readAllCards().map(T=>T.id):[y],R=[];for(let T of f){let w=a().readCard(T);if(!w){R.push({cardId:T,isValid:!1,issues:[`Card "${T}" not found`]});continue}let _=c(T,w);if(_.status!=="success")return _;R.push(_.data);}return re(R)}catch(y){return ne(y)}}function v(k){try{if(!k.body||typeof k.body!="object"||Array.isArray(k.body))return H("validateCardPreflight requires card JSON object in body");let y=k.body,l=y["card-content"]??y,f=typeof l.id=="string"?l.id:"(unknown)";return c(f,l)}catch(y){return ne(y)}}function M(k){try{let y=k.params?.cardId,l=k.params?.sourceIdx,f=k.params?.outRef;if(!y)return H("probeSource requires params.cardId");if(l===void 0)return H("probeSource requires params.sourceIdx");let T=(k.body??{})["mock-projections"]??{},w=a().readCard(y);if(!w)return H(`Card "${y}" not found`);let _=w.source_defs??[];return l<0||l>=_.length?H(`sourceIdx ${l} out of range (card has ${_.length} source(s))`):m(_[l],T,f)}catch(y){return ne(y)}}function J(k){try{let y=k.params?.outRef,l=k.body;if(!l)return H('probeTmpSource requires body with "source-def" and "mock-projections"');let f=l["source-def"],R=l["mock-projections"]??{};return f?m(f,R,y):H('probeTmpSource body requires "source-def"')}catch(y){return ne(y)}}function A(k){try{let y=h(k,"probeSourcePreflight");if("status"in y)return y;let l=r().readTaskExecutorRef();if(!l)return H("No task-executor registered for this board");try{let f={...y.src,_projections:y.mockProjections},R=t.invokeExecutorSync(l,"probe-source-preflight",[],{timeout:y.src.timeout??t.executorTimeouts?.preflightMs??6e4,input:JSON.stringify(f)}),T=JSON.parse(R.trim());return T.ok?re({bindTo:y.bindTo,reachable:T.reachable,latencyMs:T.latencyMs,note:T.note}):H(T.error??"Preflight probe failed")}catch{return H("Executor does not support probe-source-preflight")}}catch(y){return ne(y)}}function B(k){try{let y=h(k,"runSourcePreflight");if("status"in y)return y;let l=r().readTaskExecutorRef();if(l)try{let w={...y.src,_projections:y.mockProjections},_=t.invokeExecutorSync(l,"run-source-preflight",[],{timeout:y.src.timeout??t.executorTimeouts?.preflightMs??6e4,input:JSON.stringify(w)}),F=JSON.parse(_.trim());return F.ok?re({bindTo:F.bindTo??y.bindTo,reachable:F.reachable,latencyMs:F.latencyMs,kind:F.kind,resultValue:F.resultValue,note:F.note}):H(F.error??"Source preflight failed")}catch{}let f=Date.now(),R=u(y.src,y.mockProjections);if(y.outRef){let w=ut(y.outRef);t.absoluteBlob.write(w.value,R.result);}let T=R.result;try{T=JSON.parse(R.result);}catch{}return re({bindTo:R.bindTo,reachable:!0,latencyMs:Date.now()-f,resultValue:T,note:"Actual fetch preflight passed"})}catch(y){return ne(y)}}function E(k){try{let y=r().readTaskExecutorRef();if(!y)return H("No task-executor registered for this board");let l=t.invokeExecutorSync(y,"describe-capabilities",[],{timeout:t.executorTimeouts?.describeMs??1e4});return re(JSON.parse(l.trim()))}catch(y){return ne(y)}}function V(k){try{let y=k.body;if(!y||!Array.isArray(y.ops))return H("updatesInCardStore requires body.ops array");let l=y.ops,f=a();for(let R of l){let T=R.op,w=R.id;if(!w)return H('op is missing "id"');if(T==="update"){let _=R["card-content"];if(!_)return H(`update op for "${w}" is missing "card-content"`);f.writeCard(w,_);}else return H(`Unknown op type: "${T??"(none)"}"`)}return re()}catch(y){return ne(y)}}function Y(k){try{let y=k.body;if(!y||!Array.isArray(y.ids))return H("readFromCardStore requires body.ids array");let l=y.ids,f=a(),R=l.map(T=>({id:T,"card-content":f.readCard(T)}));return re({cards:R})}catch(y){return ne(y)}}function x(k){try{if(!k.body||typeof k.body!="object"||Array.isArray(k.body))return H("evalCardCompute requires a JSON object in body");let y=k.body,l=y["card-content"]??y,f=typeof l.id=="string"?l.id:"(unknown)",R=y["mock-fetched-sources"]??{},T=y["mock-requires"]??{},w=l.compute;if(!w||!Array.isArray(w)||w.length===0)return re({cardId:f,ok:!0,computed_values:{},errors:[]});let _={id:f,card_data:l.card_data??{},requires:T,source_defs:l.source_defs,compute:w},F=tt.runSync(_,{sourcesData:R}),oe=F.node.computed_values??{},X=F.errors??[];return re({cardId:f,ok:X.length===0,computed_values:oe,errors:X})}catch(y){return ne(y)}}function L(k){try{if(!k.body||typeof k.body!="object"||Array.isArray(k.body))return H("simulateCardCycle requires a JSON object in body");let y=k.body,l=y["card-content"]??y,f=typeof l.id=="string"?l.id:"(unknown)",R=y["mock-fetched-sources"]??{},T=y["mock-requires"]??{},w=c(f,l),_=w.status==="success"?{isValid:w.data.isValid,issues:w.data.issues}:{isValid:!1,issues:[w.status==="fail"?w.error:"internal error"]},F=l.source_defs??[],oe=l.card_data??{},X=[],ce=[];if(F.length>0){X=tt.enrichSourcesSync(F,{card_data:oe,requires:T});for(let Ce of X){let pe=Ce.projections,Se=Ce._projections;if(pe&&Se){for(let me of Object.keys(pe))if(Se[me]===void 0){let ke=typeof Ce.bindTo=="string"?Ce.bindTo:"(unknown)";ce.push({bindTo:ke,key:me,error:`Projection "${me}" resolved to undefined`});}}}}let ye=[],N=y["task-executor-ref"],$=(N?.howToRun&&N?.whatToRun?N:void 0)??r().readTaskExecutorRef();for(let Ce=0;Ce<X.length;Ce++){let pe=X[Ce],Se=typeof pe.bindTo=="string"?pe.bindTo:`source_${Ce}`;if(!$){ye.push({bindTo:Se,skipped:!0,error:"No task executor configured"});continue}try{let me={...pe},ke=t.invokeExecutorSync($,"run-source-preflight",[],{timeout:pe.timeout??t.executorTimeouts?.preflightMs??6e4,input:JSON.stringify(me)}),ve=JSON.parse(ke.trim());ye.push({bindTo:Se,reachable:ve.reachable,latencyMs:ve.latencyMs,error:ve.ok?void 0:ve.error});}catch{ye.push({bindTo:Se,skipped:!0,error:"Executor does not support run-source-preflight"});}}let D=l.compute,se={},te=[];if(D&&Array.isArray(D)&&D.length>0){let Ce={id:f,card_data:oe,requires:T,source_defs:l.source_defs,compute:D},pe=tt.runSync(Ce,{sourcesData:R});se=pe.node.computed_values??{},te=pe.errors??[];}let Z=_.isValid&&ce.length===0&&te.length===0&&ye.every(Ce=>Ce.reachable!==!1);return re({cardId:f,ok:Z,validation:_,source_probes:ye,projection_errors:ce,computed_values:se,compute_errors:te})}catch(y){return ne(y)}}return {validateCard:b,validateCardPreflight:v,probeSource:M,probeTmpSource:J,probeSourcePreflight:A,runSourcePreflight:B,evalCardCompute:x,simulateCardCycle:L,describeTaskExecutorCapabilities:E,updatesInCardStore:V,readFromCardStore:Y}}function Ee(e,t){if(e?.status==="success")return Object.prototype.hasOwnProperty.call(e,"data")?e.data:void 0;throw e?.status==="fail"||e?.status==="error"?new Error(e.error||`${t} failed`):new Error(`${t} returned an unexpected response`)}function ge(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Be(e){return Array.isArray(e)?e:[]}function Fr(e,t){if(typeof t!="string"||t.length===0)return;let r=e,s=t;s.startsWith("fetched_sources.")&&(r=ge(e).fetched_sources,s=s.slice(16));for(let a of s.split(".")){if(r==null||typeof r!="object")return;r=r[a];}return r}function jn(e,t){let r=ge(e.view),s=Be(r.elements);return {layout:r.layout,features:r.features,elements:s.map((a,i)=>{let c=ge(a),u=ge(c.data),m=typeof c.visible=="string"?!!Fr(t,c.visible):true,h=typeof u.bind=="string"?u.bind:void 0,b=h?Fr(t,h):void 0,v={id:typeof c.id=="string"&&c.id?c.id:`element-${i}`,kind:c.kind,label:c.label,visible:m};return h&&(v.bind=h),Array.isArray(u.columns)&&(v.columns=u.columns),typeof u.maxRows=="number"&&(v.maxRows=u.maxRows),b!==void 0&&(v.resolved=Array.isArray(b)&&typeof v.maxRows=="number"?b.slice(0,v.maxRows):b),v})}}function Bn(e){if(typeof e!="string"||!e.trim())return null;let t=/^(file uploaded|AI generated|AI geneterated):\s*.*?#(\d+)\s*$/i.exec(e.trim());if(!t)return null;let r=Number.parseInt(t[2],10);return !Number.isInteger(r)||r<0?null:r}function Fn(e){return {"card-content":e}}function Ft(e,t){let r=Ee(e.get({params:{id:t}}),"cardStore.get"),s=Array.isArray(r?.cards)?r.cards:[];if(s.length===0)throw new Error(`Card "${t}" not found`);return s[0]}function Nr(e){let{board:t,nonCore:r,cardStore:s,chatStore:a,uploadCardFile:i,buildFileDownloadUrl:c,readFetchedSourceJsonByRef:u}=e;function m(l){if(Array.isArray(l.bytes))return new Uint8Array(l.bytes.map(f=>Math.max(0,Math.min(255,Number(f)||0))));if(typeof l.text=="string")return new TextEncoder().encode(l.text);if(typeof l.base64=="string"){let f=String(l.base64).replace(/-/g,"+").replace(/_/g,"/"),R=f+"=".repeat((4-f.length%4)%4),T=atob(R);return Uint8Array.from(T,w=>w.charCodeAt(0))}throw new Error("file entry requires bytes, text, or base64")}function h(){let l=ge(Ee(r.describeTaskExecutorCapabilities({}),"describeTaskExecutorCapabilities"));return {version:l.version,commonSourceFields:ge(l.commonSourceDefFields),sourceKinds:ge(l.sourceKinds)}}function b(){let l=ge(Ee(t.status({}),"status")),f=ge(l.summary),R=Be(l.cards);return {meta:ge(l.meta),summary:{card_count:typeof f.card_count=="number"?f.card_count:0,completed:typeof f.completed=="number"?f.completed:0,eligible:typeof f.eligible=="number"?f.eligible:0,pending:typeof f.pending=="number"?f.pending:0,blocked:typeof f.blocked=="number"?f.blocked:0,in_progress:typeof f.in_progress=="number"?f.in_progress:0,failed:typeof f.failed=="number"?f.failed:0,unresolved:typeof f.unresolved=="number"?f.unresolved:0},cards:R.map(T=>{let w=ge(T);return {"card-id":typeof w.name=="string"?w.name:null,status:w.status??null,error:w.error??null,requires:Be(w.requires),requires_satisfied:Be(w.requires_satisfied),requires_missing:Be(w.requires_missing),provides_declared:Be(w.provides_declared),provides_runtime:Be(w.provides_runtime)}})}}function v(l){let f=String(l.cardId||"").trim();if(!f)throw new Error("inspectCardDefinitionAndRuntime requires cardId");let R=ge(Ee(t.status({}),"status")),w=Be(R.cards).map(ge).find(Z=>Z.name===f);if(!w)throw new Error(`card "${f}" not found in board status`);let _=ge(Ft(s,f)),F=Be(w.requires_satisfied).filter(Z=>typeof Z=="string"&&!!Z),oe=Be(w.provides_runtime).filter(Z=>typeof Z=="string"&&!!Z),X=Object.fromEntries(F.map(Z=>[Z,Ee(t.getOutputsDataObject({params:{key:Z}}),`getOutputsDataObject(${Z})`)])),ce=Object.fromEntries(oe.map(Z=>[Z,Ee(t.getOutputsDataObject({params:{key:Z}}),`getOutputsDataObject(${Z})`)])),ye=ge(Ee(t.getOutputsComputedValues({params:{key:f}}),"getOutputsComputedValues")),N=Ee(t.getOutputsFetchedSources({params:{key:f}}),"getOutputsFetchedSources"),$=Be(_.source_defs).map(ge),D={};for(let Z of $)typeof Z.bindTo=="string"&&typeof Z.outputFile=="string"&&(D[Z.outputFile]=Z.bindTo);let se={};for(let[Z,Ce]of Object.entries(N)){let pe=D[Z]??Z;if(!u||typeof Ce!="string"){se[pe]=null;continue}try{se[pe]=u({cardId:f,ref:Ce});}catch{se[pe]=null;}}let te={card_data:ge(_.card_data),requires:X,fetched_sources:se,computed_values:ye};return {cardId:f,card_status_in_board:w,card_definition_and_static_data:_,refs_for_fetched_source_files:N,runtime_data:{requires:X,provides:ce,computed_values:ye,rendered_view:jn(_,te)}}}function M(l){let f=String(l.cardId||"").trim();if(!f)throw new Error("inspectChatMessagesOnCards requires cardId");let R=typeof l.turnId=="string"?l.turnId:"",T=l.allTurns===true,w=typeof l.tailTurnsBeforeId=="string"?l.tailTurnsBeforeId:"",_=T?void 0:l.lastUserTurns??(R?void 0:1),F=l.tail,oe=_===void 0?{params:{cardId:f}}:{params:{cardId:f},body:{lastUserTurns:_}},X=Ee(a.readAll(oe),"chatStore.readAll"),ce=ge(Ft(s,f)),ye=Be(ge(ce.card_data).files).map((D,se)=>({idx:se,stored_name:ge(D).stored_name})).filter(D=>typeof D.stored_name=="string"&&D.stored_name.length>0),N=(Array.isArray(X.records)?X.records:[]).filter(D=>R?typeof D?.turn=="string"?D.turn===R:R==="":true);if(w){if(_===void 0||!Number.isInteger(_)||_<=0)throw new Error("inspectChatMessagesOnCards requires tail-turns when tail-turns-before-id is provided");let D=new Map,se=[];for(let pe of Array.isArray(X.records)?X.records:[]){let Se=typeof pe?.turn=="string"?pe.turn:"";D.has(Se)||(D.set(Se,[]),se.push(Se)),D.get(Se).push(pe);}let te=se.findIndex(pe=>pe===w),Z=Math.max(0,te-_);N=(te===-1?[]:se.slice(Z,te)).flatMap(pe=>D.get(pe)??[]);}let $=N.map(D=>{let te=ge(D.payload),Z={...D},Ce=typeof D?.role=="string"?D.role:typeof te.role=="string"?String(te.role):"",pe=typeof D?.text=="string"?D.text:typeof te.text=="string"?String(te.text):"";if(Ce==="system"){let Se=Bn(pe);if(Se!==null&&ye.some(ke=>ke.idx===Se)){let ke=`Retrieve using inspect-file-contents --card-id ${f} --file-idx ${Se}`;Z.retrieval_hint=ke,Object.keys(te).length>0&&typeof D.role!="string"&&(Z.payload={...te,retrieval_hint:ke});}}return Z});return {cardId:f,messages:typeof F=="number"&&F>=0?$.slice(-F):$}}function J(l){let f=String(l.cardId||"").trim(),R=Number(l.fileIdx);if(!f)throw new Error("inspectFileContents requires cardId");if(!Number.isInteger(R)||R<0)throw new Error("inspectFileContents requires fileIdx to be a non-negative integer");let T=ge(Ft(s,f)),w=Be(ge(T.card_data).files).map(ge);if(R>=w.length)throw new Error(`attachment index ${R} is out of range for card "${f}"`);let _=w[R],F=typeof _.stored_name=="string"?_.stored_name:null;return {cardId:f,fileIdx:R,downloadUrl:c({cardId:f,fileIdx:R,storedName:F}),...typeof _.name=="string"?{name:_.name}:{},...typeof _.stored_name=="string"?{stored_name:_.stored_name}:{},...typeof _.mime_type=="string"?{mime_type:_.mime_type}:{},...typeof _.size=="number"?{size:_.size}:{},...typeof _.uploaded_at=="string"?{uploaded_at:_.uploaded_at}:{}}}function A(l){return r.validateCardPreflight({body:Fn(l.candidateCardContent)})}function B(l){return r.evalCardCompute({body:{"card-content":l.candidateCardContent,"mock-requires":l.mockRequires,"mock-fetched-sources":l.mockFetchedSources}})}function E(l){return r.probeSourcePreflight({params:{sourceIdx:l.sourceIdx},body:{"card-content":l.candidateCardContent,"mock-projections":l.mockProjections}})}function V(l){return r.runSourcePreflight({params:{sourceIdx:l.sourceIdx},body:{"card-content":l.candidateCardContent,"mock-projections":l.mockProjections}})}function Y(l){return r.simulateCardCycle({body:{"card-content":l.candidateCardContent,"mock-requires":l.mockRequires}})}function x(l){let f=String(l.cardId||"").trim();if(!f)throw new Error("manageReadCard requires cardId");let R=Ee(s.get({params:{id:f}}),"cardStore.get");return Array.isArray(R.cards)?R.cards:[]}function L(l){let f=String(l.cardId||"").trim(),R=String(l.role||"").trim(),T=typeof l.text=="string"?l.text:"",w=typeof l.turn=="string"?l.turn:"";if(!f)throw new Error("manageAddChatEntryAndAnyAttachments requires cardId");if(!R)throw new Error("manageAddChatEntryAndAnyAttachments requires role");let _=Be(l.files).map(oe=>{let X=ge(oe),ce=String(X.file_name??X.fileName??X.name??"").trim(),ye=String(X.content_type??X.contentType??"application/octet-stream");if(!ce)throw new Error("file entry requires file_name");return i({cardId:f,fileName:ce,contentType:ye,bytes:m(X)}).file});_.forEach((oe,X)=>{let ce=R==="assistant"?`AI generated: ${String(oe.name||"")} as ${String(oe.stored_name||"")} #${X}`:`file uploaded: ${String(oe.name||"")} as ${String(oe.stored_name||"")} #${X}`;Ee(a.append({params:{cardId:f},body:{role:"system",text:ce,files:[],turn:w}}),"chatStore.append(system attachment message)");});let F=Ee(a.append({params:{cardId:f},body:{role:R,text:T,files:_,turn:w}}),"chatStore.append");return {status:"success",data:{cardId:f,id:String(F.id),role:R,turn:w,files:_}}}function k(l){let f=String(l.cardId||"").trim(),R=ge(l.candidateCardContent);if(!f)throw new Error("manageUpsertCard requires cardId");if(typeof R.id!="string"||!R.id.trim())throw new Error("candidateCardContent.id must be a non-empty string");if(R.id!==f)throw new Error(`candidateCardContent.id must match cardId (${f})`);let T=A({candidateCardContent:R}),w=ge(T),_=ge(w.data);if(w.status!=="success"||_.isValid!==true)return {status:"fail",step:"validate",validation:T};let F=null;try{F=Ft(s,f);}catch{F=null;}let oe=s.set({body:R});Ee(oe,"cardStore.set");let X;try{X=t.upsertCard({params:{cardId:f,restart:!0}}),Ee(X,"upsertCard");}catch(ye){try{F&&s.set({body:F});}catch{}throw ye}let ce=null;try{ce=t.cardRefreshedNotify({params:{cardId:f}}),Ee(ce,"cardRefreshedNotify");}catch{ce=null;}return {status:"success",data:{validation:T,card_saved:null,board_result:X,refresh_notify:ce}}}function y(l){let f=String(l.cardId||"").trim();if(!f)throw new Error("manageDeprecate requires cardId");let R=t.removeCard({params:{id:f}});return Ee(R,"removeCard"),R}return {discoverSourceKinds:h,inspectBoardRuntimeStatus:b,inspectCardDefinitionAndRuntime:v,inspectChatMessagesOnCards:M,inspectFileContents:J,preflightValidateCandidateCardDefinition:A,preflightMaterializeCandidateCard:B,preflightProbeSingleSourceInCandidateCard:E,preflightRunSingleSourceInCandidateCard:V,preflightRunOneCycleWithCandidateCard:Y,manageReadCard:x,manageAddChatEntryAndAnyAttachments:L,manageUpsertCard:k,manageDeprecate:y}}function Pr(){return new Date().toISOString()}function $r(e){return new TextEncoder().encode(e).byteLength}function Nn(e){return e?{key:e.key,size:e.size,updatedAt:e.updatedAt,contentType:e.contentType}:null}function Pn(e){let t=String(e||"").match(/^(\d+)[-_]/);return t?parseInt(t[1],10):0}function $n(e){let t=String(e||"").trim();if(!t)return "upload.bin";let r=Math.max(t.lastIndexOf("/"),t.lastIndexOf("\\"));return (r>=0?t.slice(r+1):t)||"upload.bin"}function Dn(e){return String(e||"").toLowerCase().replace(/\s+/g,"_").replace(/[^a-z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_+|_+$/g,"")||"file"}function qn(e){if(!e||e===".")return "";let t=String(e).replace(/^\./,"").toLowerCase().replace(/[^a-z0-9]/g,"");return t?`.${t}`:""}function Ln(e){let t=$n(e),r=t.lastIndexOf(".");return r<=0||r===t.length-1?{stem:t,ext:""}:{stem:t.slice(0,r),ext:t.slice(r)}}function Mn(e){let t=e.lastIndexOf("/");return t>=0?e.slice(t+1):e}function Dr(e){function t(r){let s=e.stat?Nn(e.stat(r)):null;if(s)return s;if(!e.exists(r))return null;let a=e.read(r);return a===null?{key:r}:{key:r,size:$r(a)}}return {exists(r){return e.exists(r)},putText(r,s,a="text/plain; charset=utf-8"){e.write(r,s);let i=t(r)??{key:r};return i.contentType=a,i.updatedAt=i.updatedAt??Pr(),i.size=i.size??$r(s),i},putBytes(r,s,a="application/octet-stream"){if(e.writeBytes)e.writeBytes(r,s);else {let c=JSON.stringify({__kind:"bytes-array",data:[...s]});e.write(r,c);}let i=t(r)??{key:r};return i.contentType=a,i.updatedAt=i.updatedAt??Pr(),i.size=i.size??s.byteLength,i},getText(r){let s=e.read(r);if(s===null){if(!e.readBytes)return null;let a=e.readBytes(r);return a===null?null:Buffer.from(a).toString("utf-8")}try{let a=JSON.parse(s);if(a&&a.__kind==="bytes-array"&&Array.isArray(a.data))return new TextDecoder("utf-8").decode(new Uint8Array(a.data))}catch{}return s},getBytes(r){if(e.readBytes){let a=e.readBytes(r);if(a!==null)return a}let s=e.read(r);if(s===null)return null;try{let a=JSON.parse(s);if(a&&a.__kind==="bytes-array"&&Array.isArray(a.data))return new Uint8Array(a.data)}catch{}return new TextEncoder().encode(s)},head:t,list(r=""){return e.listKeys(r).map(s=>t(s)??{key:s}).sort((s,a)=>s.key.localeCompare(a.key))},remove(r){e.remove(r);}}}function qr(e){function t(a,i){let c=0,u=[];Array.isArray(i)&&u.push(...i);for(let m of e.list(`${a}/`))u.push(Mn(m.key));for(let m of u){let h=Pn(m);Number.isFinite(h)&&h>c&&(c=h);}return c+1}function r(a,i,c){let u=Number(c?.maxLen||32),{stem:m,ext:h}=Ln(a),b=qn(h),v=Dn(m),M=`${String(i).padStart(3,"0")}-`,J=b,A=u-M.length-J.length;A<1&&(J="",A=u-M.length);let B=v.slice(0,Math.max(1,A)),E=`${M}${B}${J}`;return E.length>u&&(E=E.slice(0,u).replace(/\.$/,"")),E}function s(a,i,c){let u=t(a,c?.seedNames),m=r(i,u,{maxLen:c?.maxLen});for(;e.exists(`${a}/${m}`);)u+=1,m=r(i,u,{maxLen:c?.maxLen});return m}return {nextSerial:t,buildStoredName:r,allocateStoredName:s}}function Lr(){function e(a,i){if(!Array.isArray(a))return [];let c=[];for(let u of a){if(!u||typeof u!="object")continue;let m=u;typeof m.stored_name=="string"&&c.push({name:typeof m.name=="string"?m.name:m.stored_name,stored_name:m.stored_name,size:typeof m.size=="number"&&Number.isFinite(m.size)?m.size:null,mime_type:typeof m.mime_type=="string"?m.mime_type:null,uploaded_at:typeof m.uploaded_at=="string"?m.uploaded_at:i||null,chat:m.chat===true});}return c}function t(a){return !a||typeof a!="object"?[]:e(a.files,void 0)}function r(a,i){let c=t(a);if(i.length===0)return a.files=c,c;let u=new Set(c.map(m=>m.stored_name));for(let m of i)u.has(m.stored_name)||(c.push(m),u.add(m.stored_name));return a.files=c,c}function s(a,i,c){let u=t(a);if(!Number.isInteger(i)||i<0||i>=u.length)return {ok:false,reason:"index_out_of_range"};let m=u[i];return !m||!m.stored_name?{ok:false,reason:"missing_stored_name"}:c&&c!==m.stored_name?{ok:false,reason:"stale_reference"}:{ok:true,file:m}}return {read:t,normalizeIncoming:e,merge:r,resolve:s}}function Un(){let e=globalThis.crypto;return typeof e?.randomUUID=="function"?String(e.randomUUID()):`id-${Date.now()}-${Math.random().toString(36).slice(2)}`}function Mr(){let e=new Map,t=new Map;function r(s){return e.has(s)||e.set(s,[]),e.get(s)}return {append(s,a,i,c=[],u=""){let m={id:Un(),role:a,text:i,files:c,turn:u,updated_at:new Date().toISOString()};return r(s).push(m),m.id},readAll(s){return r(s).slice()},readAfter(s,a){let i=r(s);if(!a)return {records:i.slice(),cursor:i.length>0?i[i.length-1].id:null};let c=i.findIndex(m=>m.id===a),u=c===-1?i.slice():i.slice(c+1);return {records:u,cursor:u.length>0?u[u.length-1].id:a}},clear(s){e.set(s,[]);},setProcessing(s,a){a?t.set(`p:${s}`,true):t.delete(`p:${s}`);},isProcessing(s){return t.get(`p:${s}`)===true},getConfig(s){return t.get(`c:${s}`)??{}},setConfig(s,a){let i=t.get(`c:${s}`)??{};t.set(`c:${s}`,{...i,...a});}}}function Ur(e){function t(h){let b=typeof h=="number"?h:Number(h);return Number.isInteger(b)&&b>0?b:null}function r(h,b){let v=b;for(let M=h.length-1;M>=0;M-=1)if(h[M]?.role==="user"&&(v-=1,v===0))return h.slice(M);return h}function s(h){return {status:"success",data:h}}function a(h){return {status:"fail",error:h}}function i(h){return {status:"error",error:h instanceof Error?h.message:String(h)}}function c(h,b="command envelope"){let v=typeof h.cardId=="string"?h.cardId:void 0;if(!h.command)return a(`chat-store: ${b} missing "command"`);if(!v)return a(`chat-store: ${b} missing "cardId"`);if(h.command==="append")return m.append({params:{cardId:v},body:{role:h.role,text:h.text,files:h.files,turn:h.turn}});if(h.command==="read-all")return m.readAll({params:{cardId:v},body:{lastUserTurns:h.lastUserTurns}});if(h.command==="read-after")return m.readAfter({params:{cardId:v},body:{cursor:h.cursor??null}});if(h.command==="clear")return m.clear({params:{cardId:v}});if(h.command==="set-processing")return m.setProcessing({params:{cardId:v},body:{active:h.active}});if(h.command==="is-processing")return m.isProcessing({params:{cardId:v}});if(h.command==="get-config")return m.getConfig({params:{cardId:v}});if(h.command==="set-config"){let{command:M,cardId:J,...A}=h;return m.setConfig({params:{cardId:v},body:A})}return a(`chat-store: unknown command "${String(h.command)}"`)}function u(h){if(!Array.isArray(h.commands)||h.commands.length===0)return a('chat-store: command envelope must include a non-empty "commands" array');let b=[];for(let v=0;v<h.commands.length;v+=1){let M=h.commands[v];if(!M||typeof M!="object"||Array.isArray(M))return a(`chat-store: command envelope entry ${v} must be an object`);let J={cardId:h.cardId,...M},A=c(J,`command envelope entry ${v}`);if(A.status!=="success")return A;b.push({index:v,command:String(J.command),data:A.data});}return s({results:b})}let m={append(h){try{let b=h.params?.cardId;if(!b)return a("append requires params.cardId");let v=h.body??{},M=typeof v.role=="string"?v.role:"",J=typeof v.text=="string"?v.text:"",A=Array.isArray(v.files)?v.files:[],B=typeof v.turn=="string"?v.turn:"";if(!M)return a("append requires body.role");let E=e.append(b,M,J,A,B);return s({id:E})}catch(b){return i(b)}},readAll(h){try{let b=h.params?.cardId;if(!b)return a("readAll requires params.cardId");let v=h.body??{},M=e.readAll(b);if(v.lastUserTurns===void 0)return s({records:M});let J=t(v.lastUserTurns);return J===null?a("readAll requires body.lastUserTurns (positive integer)"):s({records:r(M,J)})}catch(b){return i(b)}},readAfter(h){try{let b=h.params?.cardId;if(!b)return a("readAfter requires params.cardId");let M=(h.body??{}).cursor??null;return s(e.readAfter(b,M))}catch(b){return i(b)}},clear(h){try{let b=h.params?.cardId;return b?(e.clear(b),s({ok:!0})):a("clear requires params.cardId")}catch(b){return i(b)}},setProcessing(h){try{let b=h.params?.cardId;if(!b)return a("setProcessing requires params.cardId");let v=h.body??{};return typeof v.active!="boolean"?a("setProcessing requires body.active (boolean)"):(e.setProcessing(b,v.active),s({ok:!0}))}catch(b){return i(b)}},isProcessing(h){try{let b=h.params?.cardId;return b?s({active:e.isProcessing(b)}):a("isProcessing requires params.cardId")}catch(b){return i(b)}},getConfig(h){try{let b=h.params?.cardId;return b?s({config:e.getConfig(b)}):a("getConfig requires params.cardId")}catch(b){return i(b)}},setConfig(h){try{let b=h.params?.cardId;if(!b)return a("setConfig requires params.cardId");let v=h.body??{};return e.setConfig(b,v),s({ok:!0})}catch(b){return i(b)}},run:c,runBatch:u};return m}var Gr={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"content-type,x-file-name","Access-Control-Allow-Methods":"GET,POST,PATCH,OPTIONS"},Gn=32;function Vn(){return {status:null,computedValues:{},dataObjects:{},cards:{}}}function Vr(e){if(!e||typeof e!="object")return false;let t=e.summary;return !t||typeof t!="object"?false:Number(t.card_count||0)>0}function Kr(e,t){if(!t||typeof t!="object")return;let r=t;if(r.kind==="notification-batch"&&Array.isArray(r.notifications)){for(let s of r.notifications)Kr(e,s);return}r.kind==="status"&&Vr(r.status)&&(e.status=r.status),r.kind==="computed_values"&&r.cardId&&(e.computedValues[r.cardId]=r.values),r.kind==="data_object"&&r.key&&(e.dataObjects[r.key]=r.payload),r.kind==="card_refreshed"&&r.cardId&&(e.cards[r.cardId]=r.card),r.kind==="card_removed"&&r.cardId&&(delete e.cards[r.cardId],delete e.computedValues[r.cardId]);}function Yo(e){let t=String(e.apiBasePath||"/api/board").replace(/\/$/,""),r={...Gr,...e.corsHeaders||{}},s=e.boardId||"",a=e.logger||{info:console.log,warn:console.warn,error:console.error},i=e.invocationAdapter,c=e.chatFlowRunner||null,u=e.chatStorage??Mr(),m=Ur(u),h=e.notificationTransport||null,b=e.serverUrl||null,v=e.executionExtra||{},M=e.onSseClientConnected,J=e.onSseClientDisconnected,A=e.onChannelSubscribed,B=e.onChannelUnsubscribed,E=new Map,V=new Map,Y=new Map,x=null;function L(o){let n=jr(o.baseRef,o.boardAdapter),d=o.nonCoreAdapter??(f(o.boardAdapter)?o.boardAdapter:null),p=d?Br(o.baseRef,d):null,C=o.boardAdapter.kvStorageForRef(o.cardStoreRef),O=jt(bt({readIndex:()=>C.read("_index"),writeIndex:le=>C.write("_index",le),readCard:le=>C.read(le),writeCard:(le,xe)=>(C.write(le,xe),le),cardExists:le=>C.read(le)!==null,defaultCardKey:le=>le},a.warn)),q=o.artifactsAdapter||o.boardAdapter,G=o.filesArtifactsStore??null,ue=o.artifactsAdapter?q.blobStorage(""):q.blobStorage("files"),de=null;return {label:o.label,board:n,nonCore:p,cardStore:O,get filesArtifacts(){return de??=G??Dr(ue)},boardAdapter:o.boardAdapter,cardStoreRef:o.cardStoreRef,outputsStoreRef:o.outputsStoreRef,artifactsStoreRef:o.artifactsStoreRef,scratchStoreRef:o.scratchStoreRef,archiveStoreRef:o.archiveStoreRef,notifyRef:o.notifyRef,taskExecutorRef:o.taskExecutorRef,chatHandlerRef:o.chatHandlerRef,chatHandlerFlow:o.chatHandlerFlow,inferenceAdapterRef:o.inferenceAdapterRef,notification:Vn(),notificationTeardown:null,initialized:false,cardsBootstrapped:false}}let k=e.boards.map(L),y=new Map;function l(o){return y.get(o)??0}function f(o){let n=o;return typeof n.invokeExecutorSync=="function"&&typeof n.validateSchema=="function"}function R(o){let n=k[l(o)];return {files:n?n.filesArtifacts:null}}function T(o){let n=R(o);return n.files?qr(n.files):null}function w(){return Lr()}function _(o){return String(o||"").replace(/[^a-zA-Z0-9_-]/g,"_")||"unknown-card"}async function F(o){if(!o||o.notificationTeardown||!h||!o.notifyRef)return;let n=await h.subscribe(o.notifyRef,d=>{Kr(o.notification,d);let p=d.kind==="notification-batch"?d.notifications:[d];Jt(p);});o.notificationTeardown=n;}async function oe(o){if(!o||o.initialized)return;let n={cardStoreRef:o.cardStoreRef,outputsStoreRef:o.outputsStoreRef};o.artifactsStoreRef&&(n.artifactsStoreRef=o.artifactsStoreRef),o.scratchStoreRef&&(n.scratchStoreRef=o.scratchStoreRef),o.archiveStoreRef&&(n.archiveStoreRef=o.archiveStoreRef);let d={};o.taskExecutorRef&&(d["task-executor-ref"]=o.taskExecutorRef),o.chatHandlerFlow!==void 0&&(d["chat-handler-flow"]=o.chatHandlerFlow),o.inferenceAdapterRef&&(d["inference-adapter-ref"]=o.inferenceAdapterRef);let p=o.board.init({params:n,body:d});if(p.status!=="success")throw Object.assign(new Error(p.error||`init failed for ${o.label}`),{statusCode:500});if(await F(o),!o.chatHandlerFlow&&o.chatHandlerRef&&i.describe)try{let C=await i.describe(o.chatHandlerRef);C&&C.kind!=="chat-handler"?a.warn(`[init] chat-handler describe returned kind="${C.kind}", expected "chat-handler" for ${o.label}`):C&&a.info(`[init] chat-handler validated: ${C.name} (protocol ${C.protocolVersion}) for ${o.label}`);}catch(C){a.warn(`[init] chat-handler describe failed for ${o.label}: ${C?.message||String(C)}`);}o.initialized=true;}function X(o){if(!o.boardAdapter.publishBoardChangeNotifications)return;let n=[],d=o.board.status({});d.status==="success"&&d.data!=null&&Vr(d.data)&&n.push({kind:"status",status:d.data});let p=o.board.getAllOutputsDataObjects({});if(p.status==="success"&&p.data!=null)for(let[S,O]of Object.entries(p.data))S&&n.push({kind:"data_object",key:S,payload:O});let C=o.board.getAllOutputsComputedValues({});if(C.status==="success"&&C.data!=null)for(let[S,O]of Object.entries(C.data))S&&n.push({kind:"computed_values",cardId:S,values:O});n.length>0&&o.boardAdapter.publishBoardChangeNotifications(n);}function ce(o,n){if(!o||o.cardsBootstrapped)return;let d=o.cardStore.get({}),p=d.status==="success"&&Array.isArray(d.data?.cards)?d.data.cards:[];for(let C of p)typeof C.id=="string"&&(y.set(C.id,n),o.board.upsertCard({params:{cardId:C.id}}));o.cardsBootstrapped=true;}async function ye(){for(let o of k)await oe(o);}async function N(){await ye();for(let o=0;o<k.length;o++)X(k[o]),ce(k[o],o);}function $(o){return k[l(o)]??null}function D(o){let n=$(o);if(!n)return null;let d=n.cardStore.get({params:{id:o}});if(d.status!=="success")return null;let p=Array.isArray(d.data?.cards)?d.data.cards:[];return p.length>0?p[0]:null}function se(){let o=d=>{if(!d||!d.cardStore)return [];let p=d.cardStore.get({});return p.status!=="success"||!Array.isArray(p.data?.cards)?[]:p.data.cards},n=[];for(let d of k)n.push(...o(d));return n}function te(){return k[0]??null}function Z(){return {status(){let o=g();return o==null?{status:"fail",error:"Board status is unavailable"}:{status:"success",data:o}},getOutputsDataObject(o){let n=o?.params?.key;return n?{status:"success",data:U()[n]}:{status:"fail",error:"getOutputsDataObject requires params.key"}},getOutputsComputedValues(o){let n=o?.params?.key;return n?{status:"success",data:j()[n]?.computed_values}:{status:"fail",error:"getOutputsComputedValues requires params.key"}},getOutputsFetchedSources(o){let n=o?.params?.key;if(!n)return {status:"fail",error:"getOutputsFetchedSources requires params.key"};let d=$(n)??te();return d?d.board.getOutputsFetchedSources({params:{key:n}}):{status:"fail",error:"Board context is unavailable"}},removeCard(o){let n=o?.params?.id;if(!n)return {status:"fail",error:"removeCard requires params.id"};let d=$(n)??te();return d?d.board.removeCard({params:{id:n}}):{status:"fail",error:"Board context is unavailable"}},cardRefreshedNotify(o){let n=o?.params?.cardId;if(!n)return {status:"fail",error:"cardRefreshedNotify requires params.cardId"};let d=$(n)??te();return d?d.board.cardRefreshedNotify({params:{cardId:n}}):{status:"fail",error:"Board context is unavailable"}},upsertCard(o){let n=o?.params?.cardId;if(!n)return {status:"fail",error:"upsertCard requires params.cardId"};let d=$(n)??te();return d?d.board.upsertCard({params:{cardId:n,restart:o.params.restart===true}}):{status:"fail",error:"Board context is unavailable"}}}}function Ce(){let o=()=>{let n=te();if(!n?.nonCore)throw new Error("Board non-core adapter is not configured for MCP preflight/discovery tools");return n.nonCore};return {describeTaskExecutorCapabilities(n){return o().describeTaskExecutorCapabilities(n)},validateCardPreflight(n){return o().validateCardPreflight(n)},evalCardCompute(n){return o().evalCardCompute(n)},probeSourcePreflight(n){return o().probeSourcePreflight(n)},runSourcePreflight(n){return o().runSourcePreflight(n)},simulateCardCycle(n){return o().simulateCardCycle(n)}}}function pe(){return {get(o){let n=typeof o.params?.id=="string"?o.params.id:void 0;if(n){let d=D(n);return d?{status:"success",data:{cards:[d]}}:{status:"fail",error:`card "${n}" not found`}}return {status:"success",data:{cards:se()}}},set(o){let n=o.body;if(n==null)return {status:"fail",error:"set requires a body (card object or array of cards)"};let d=Array.isArray(n)?n:[n];for(let p of d){let C=p,S=typeof C.id=="string"?C.id:"";if(!S)return {status:"fail",error:"each card must have a string `id` field"};let O=y.get(S)??0,q=k[O]??te();if(!q)return {status:"fail",error:"Board context is unavailable"};let G=q.cardStore.set({body:C});if(G.status!=="success")return G;y.set(S,O);}return {status:"success",data:{count:d.length}}},del(o){let n=[o.params?.id,...o.body?.ids??[]].filter(d=>typeof d=="string"&&!!d);if(n.length===0)return {status:"fail",error:"del requires body.ids (string[]) or params.id"};for(let d of n){let p=$(d)??te();if(!p)return {status:"fail",error:"Board context is unavailable"};let C=p.cardStore.del({params:{id:d}});if(C.status!=="success")return C;y.delete(d);}return {status:"success",data:{count:n.length}}},patch(o){let n=typeof o.params?.id=="string"?o.params.id:void 0,d=typeof o.params?.path=="string"?o.params.path:void 0;if(!n||!d)return {status:"fail",error:"patch requires params.id and params.path"};let p=$(n)??te();return p?p.cardStore.patch(o):{status:"fail",error:"Board context is unavailable"}},appendFiles(o){let n=typeof o.params?.id=="string"?o.params.id:void 0;if(!n)return {status:"fail",error:"appendFiles requires params.id"};let d=$(n)??te();return d?d.cardStore.appendFiles(o):{status:"fail",error:"Board context is unavailable"}}}}function Se(){return Nr({board:Z(),nonCore:Ce(),cardStore:pe(),chatStore:m,uploadCardFile({cardId:o,fileName:n,contentType:d,bytes:p}){return rt(o,n,d,p,{inChat:false})},buildFileDownloadUrl({cardId:o,fileIdx:n,storedName:d}){let p=`${b||""}${t}/cards/${encodeURIComponent(o)}/files/${n}`;return d?`${p}?sn=${encodeURIComponent(d)}`:p},readFetchedSourceJsonByRef({cardId:o,ref:n}){let d=$(o)??te();if(!d)return null;let C=d.boardAdapter.resolveBlob(ut(n)).trim();return C?JSON.parse(C):null}})}function me(o,...n){for(let d of n)if(typeof o[d]=="string")return String(o[d]);return ""}function ke(o,...n){for(let d of n)if(o[d]!==void 0)return Number(o[d])}function ve(o,...n){for(let d of n){let p=o[d];if(p&&typeof p=="object"&&!Array.isArray(p))return p}return {}}function Nt(o){return {"discover.source-kinds":()=>o.discoverSourceKinds(),"inspect.board-runtime-status":()=>o.inspectBoardRuntimeStatus(),"inspect.card-definition-and-runtime":n=>o.inspectCardDefinitionAndRuntime({cardId:me(n,"card_id","cardId")}),"inspect.chat-messages-on-cards":n=>{let d=ke(n,"tail-turns"),p=ke(n,"tail"),C=me(n,"turn-id"),S=n["all-turns"]===true,O=me(n,"tail-turns-before-id");return o.inspectChatMessagesOnCards({cardId:me(n,"card_id","cardId"),...d!==void 0?{lastUserTurns:d}:{},...p!==void 0?{tail:p}:{},...C?{turnId:C}:{},...S?{allTurns:true}:{},...O?{tailTurnsBeforeId:O}:{}})},"inspect.file-contents":n=>o.inspectFileContents({cardId:me(n,"card_id","cardId"),fileIdx:Number(ke(n,"file_idx","fileIdx"))}),"preflight.validate-candidate-card-definition":n=>o.preflightValidateCandidateCardDefinition({candidateCardContent:ve(n,"candidate_card_content","candidateCardContent")}),"preflight.materialize-candidate-card":n=>o.preflightMaterializeCandidateCard({candidateCardContent:ve(n,"candidate_card_content","candidateCardContent"),mockRequires:ve(n,"mock_requires","mockRequires"),mockFetchedSources:ve(n,"mock_fetched_sources","mockFetchedSources")}),"preflight.probe-single-source-in-candidate-card":n=>o.preflightProbeSingleSourceInCandidateCard({candidateCardContent:ve(n,"candidate_card_content","candidateCardContent"),mockProjections:ve(n,"mock_projections","mockProjections"),sourceIdx:Number(ke(n,"source_idx","sourceIdx"))}),"preflight.run-single-source-in-candidate-card":n=>o.preflightRunSingleSourceInCandidateCard({candidateCardContent:ve(n,"candidate_card_content","candidateCardContent"),mockProjections:ve(n,"mock_projections","mockProjections"),sourceIdx:Number(ke(n,"source_idx","sourceIdx"))}),"preflight.run-one-cycle-with-candidate-card":n=>o.preflightRunOneCycleWithCandidateCard({candidateCardContent:ve(n,"candidate_card_content","candidateCardContent"),mockRequires:ve(n,"mock_requires","mockRequires")}),"manage.read-card":n=>o.manageReadCard({cardId:me(n,"card_id","cardId")}),"stage-ai-response-and-any-attachments":n=>o.manageAddChatEntryAndAnyAttachments({cardId:me(n,"card_id","cardId"),role:"assistant",...typeof n.text=="string"?{text:n.text}:{},...typeof me(n,"turn-id","turnId","turn")=="string"&&me(n,"turn-id","turnId","turn")!==""?{turn:me(n,"turn-id","turnId","turn")}:{},...Array.isArray(n.files)?{files:n.files}:{}}),"manage.upload-card-file":n=>{let d=me(n,"card_id","cardId"),p=me(n,"file_name","fileName","name"),C=me(n,"content_type","contentType")||"application/octet-stream",S=null;if(Array.isArray(n.bytes))S=new Uint8Array(n.bytes.map(O=>Math.max(0,Math.min(255,Number(O)||0))));else if(typeof n.text=="string")S=new TextEncoder().encode(n.text);else if(typeof n.base64=="string"){let O=String(n.base64).replace(/-/g,"+").replace(/_/g,"/"),q=O+"=".repeat((4-O.length%4)%4),G=atob(q);S=Uint8Array.from(G,ue=>ue.charCodeAt(0));}if(!d)throw Object.assign(new Error("manage.upload-card-file requires card_id"),{statusCode:400});if(!p)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 rt(d,p,C,S,{inChat:false})},"manage.upsert-card":n=>o.manageUpsertCard({cardId:me(n,"card_id","cardId"),candidateCardContent:ve(n,"candidate_card_content","candidateCardContent")}),"manage.deprecate":n=>o.manageDeprecate({cardId:me(n,"card_id","cardId")})}}function I(o,n){let d=Nt(Se())[o];if(!d)throw Object.assign(new Error(`Unknown MCP tool: ${o}`),{statusCode:400});return d(n)}function g(){let o=k.map(S=>{try{let q=S.boardAdapter.kvStorageForRef(S.outputsStoreRef).read("status");if(q!=null)return q}catch{}return S.notification.status}).filter(Boolean);if(o.length===0)return null;if(o.length===1)return o[0];let n=[],d=["completed","eligible","pending","blocked","unresolved","failed","in_progress","orphan_cards"],p={};for(let S of d)p[S]=0;for(let S of o){let O=S,q=Array.isArray(O.cards)?O.cards:[];n.push(...q);for(let G of d)p[G]+=Number(O?.summary?.[G]||0);}let C=o[0];return {...C,cards:n,summary:{...C.summary||{},card_count:n.length,...p}}}function j(){let o={},n=d=>{for(let[p,C]of Object.entries(d.notification.computedValues)){let S=d.notification.cards[p];o[p]={schema_version:"v1",card_id:p,card_data:S?.card_data??{},computed_values:C??{}};}};for(let d of k)n(d);return o}function U(){let o={};for(let n of k)Object.assign(o,n.notification.dataObjects||{});return o}function Q(){let o=se(),n=j(),d=U(),p={};for(let S of o){if(!S?.id)continue;let O=S.id,q=n[O]||{},G={...q.card_data&&typeof q.card_data=="object"?q.card_data:S.card_data&&typeof S.card_data=="object"?S.card_data:{}};p[O]={schema_version:q.schema_version||"v1",card_id:q.card_id||O,card_data:G,computed_values:q.computed_values&&typeof q.computed_values=="object"?q.computed_values:{}};}let C={};for(let S of o){if(!S?.id)continue;let O=S.id;try{let q=qe(O),G=u.isProcessing(O);(q.length>0||G)&&(C[O]={messages:q.map(ue=>({role:String(ue.role||"system"),text:String(ue.text||""),files:Array.isArray(ue.files)?ue.files:[]})),receiving:!1,processing:G});}catch{}}return {boardId:s,cardDefinitions:o,statusSnapshot:g(),dataObjectsByToken:d,cardRuntimeById:p,cardChatsByCardId:C}}function ie(o,n,d){let p=d?.syncBoard!==false,C=d?.restartOnlyIfChanged===true,S=$(o);if(!S)throw Object.assign(new Error(`Card not found: ${o}`),{statusCode:404});let O=D(o);if(!O)throw Object.assign(new Error(`Card not found: ${o}`),{statusCode:404});let q=C?JSON.stringify(O):null,G=n(O)||O;if(C&&JSON.stringify(G)===q)return;let ue=S.cardStore.set({body:G});if(ue.status!=="success")throw Object.assign(new Error(ue.error||`Failed to persist card: ${o}`),{statusCode:500});if(p){let de=S.board.upsertCard({params:{cardId:o,restart:true}});if(de.status!=="success")throw Object.assign(new Error(de.error||`Failed to upsert card: ${o}`),{statusCode:500})}}function Ie(o,n){ie(o,n,{syncBoard:true});}function he(o,n){ie(o,n,{syncBoard:false});}function Te(o){let n=$(o);if(!n)throw Object.assign(new Error(`Card not found: ${o}`),{statusCode:404});if(!D(o))throw Object.assign(new Error(`Card not found: ${o}`),{statusCode:404});let p=n.board.upsertCard({params:{cardId:o,restart:true}});if(p.status!=="success")throw Object.assign(new Error(p.error||`Failed to retrigger card: ${o}`),{statusCode:500})}function Ae(o,n){ie(o,d=>{if(!n||typeof n!="object"||Object.keys(n).length===0)return d;function p(C,S,O){let q=String(S||"").split(".").filter(Boolean);if(!q.length)return;let G=C;for(let ue=0;ue<q.length-1;ue++){let de=q[ue];(!G[de]||typeof G[de]!="object")&&(G[de]={}),G=G[de];}G[q[q.length-1]]=O;}if(n.fieldValues!==void 0&&n.fieldValues!==null){let C=null,S=d.view;if(S&&Array.isArray(S.elements)){for(let O of S.elements)if(O?.data&&O.data.writeTo){C=O.data.writeTo;break}}C?p(d,C,n.fieldValues):typeof n.fieldValues=="object"&&!Array.isArray(n.fieldValues)&&(d.card_data={...d.card_data||{},...n.fieldValues});}else {if(Array.isArray(n._stagedFiles)&&n._stagedFiles.length>0)return d;for(let[C,S]of Object.entries(n))C!=="_stagedFiles"&&(S!==null&&typeof S=="object"&&!Array.isArray(S)&&d[C]!==null&&typeof d[C]=="object"&&!Array.isArray(d[C])?d[C]={...d[C],...S}:d[C]=S);}return d},{syncBoard:true,restartOnlyIfChanged:true});}function Ue(o){let n=String(o||"").trim();if(!n)return "upload.bin";let d=Math.max(n.lastIndexOf("/"),n.lastIndexOf("\\"));return (d>=0?n.slice(d+1):n)||"upload.bin"}function Ge(o){u.clear(o),u.setProcessing(o,false);}function We(o,n,d,p,C=""){let S=typeof d=="string"?d.trim():"";return u.append(o,n,S,p,C)}function qe(o){return u.readAll(o)}function Ve(o){let n=[];try{let d=D(o);if(!d)return n;let p=w().read(d.card_data&&typeof d.card_data=="object"?d.card_data:null);for(let C of p)n.push(C.stored_name);}catch{}return n}function lt(o,n,d,p){let C=_(o),S=R(o),O=Ue(n),q=T(o),G=q?q.allocateStoredName(C,O,{seedNames:Ve(o),maxLen:Gn}):`${String(Date.now())}-${O}`;return S.files&&S.files.putBytes(`${C}/${G}`,new Uint8Array(p),d||"application/octet-stream"),{name:O,stored_name:G,size:p.length,mime_type:d||"application/octet-stream",uploaded_at:new Date().toISOString()}}function rt(o,n,d,p,C){if(!p.length)throw Object.assign(new Error("Empty upload body"),{statusCode:400});let S=C?.inChat===true,O=lt(o,n,d,p),q=null;if(he(o,G=>{let ue=new Date().toISOString(),de=G.card_data&&typeof G.card_data=="object"?G.card_data:{};G.card_data=de;let le=w().normalizeIncoming([{name:O.name,stored_name:O.stored_name,size:O.size,mime_type:O.mime_type,uploaded_at:O.uploaded_at||ue,chat:S}],ue);return q=w().merge(de,le).findIndex(nt=>nt.stored_name===O.stored_name),G}),S){let G=typeof q=="number"&&q>=0?` #${q}`:"";We(o,"system",`file uploaded: ${O.name} as ${O.stored_name}${G}`,[],C?.turnId??"");}return {ok:true,file:O}}function st(o){let n=$(o);if(!n)return null;let d=n.board.getConfig({params:{key:"chat-handler-flow"}}),p=d.status==="success"?d.data?.value:null,C=n.chatHandlerRef;return p==null&&(!C||typeof C!="object")?null:{ctx:n,handlerFlow:p,handlerRef:C}}function St(o,n,d=false,p=""){let C=st(o);if(!C)return;let{ctx:S,handlerFlow:O,handlerRef:q}=C;if(!d)try{u.setProcessing(o,!0);}catch{}let G={boardId:s,cardId:String(o),lastChatEntryId:n,...p?{turnId:p}:{},...v,...b?{serverUrl:b}:{}};if(!c&&O!=null){try{u.setProcessing(o,!1);}catch{}a.warn(`[chat-handler-flow] configured for card "${o}" but no chatFlowRunner was provided`);return}if(O!=null){let de=c;if(!de)return;de.run(O,G,{boardId:s,cardId:String(o),label:S.label,logger:a,serverUrl:b,executionExtra:v}).then(le=>{if(le.dispatched)a.info(`[chat-handler-flow] invoked for card "${o}" (boardId: "${s}")`);else {try{u.setProcessing(o,!1);}catch{}a.warn(`[chat-handler-flow] dispatch failed for card "${o}": ${le.error||"unknown"}`);}},le=>{try{u.setProcessing(o,!1);}catch{}a.warn(`[chat-handler-flow] invoke failed for card "${o}": ${le?.message||String(le)}`);});return}let ue=q;ue&&i.invoke(ue,G).then(de=>{if(de.dispatched)a.info(`[chat-handler] invoked for card "${o}" (boardId: "${s}")`);else {try{u.setProcessing(o,!1);}catch{}a.warn(`[chat-handler] dispatch failed for card "${o}": ${de.error||"unknown"}`);}},de=>{try{u.setProcessing(o,!1);}catch{}a.warn(`[chat-handler] invoke failed for card "${o}": ${de?.message||String(de)}`);});}function Pt(o,n,d){let p=n==="chat-send"?he:Ie,C;p(o,S=>{let O=new Date().toISOString(),q=S.card_data&&typeof S.card_data=="object"?S.card_data:{};if(S.card_data=q,n==="chat-send"){let G=d&&typeof d.text=="string"?d.text.trim():"",ue=d&&typeof d["turn-id"]=="string"?d["turn-id"]:d&&typeof d.turnId=="string"?d.turnId:d&&typeof d.turn=="string"?d.turn:"",de=[];if(Array.isArray(d?.files)){for(let le of d.files)if(le){if(typeof le=="string"){de.push({name:le});continue}if(typeof le=="object"){let xe=le;typeof xe.name=="string"&&de.push({name:xe.name,size:xe.size,mime_type:xe.mime_type,uploaded_at:xe.uploaded_at,stored_name:xe.stored_name,chat:xe.chat===true});}}}if(G||de.length>0){let le=m.runBatch({cardId:o,commands:[{command:"append",role:"user",text:G,files:de,turn:ue},{command:"set-processing",active:true}]});if(le.status!=="success")throw new Error(le.error);let xe=le.data.results[0]?.data?.id;if(typeof xe!="string"||!xe)throw new Error(`chat-send did not return an append id for card ${o}`);C={cardId:o,lastEntryId:xe,processingAlreadySet:true,turnId:ue};try{let gt=qe(o);Jt([{kind:"card_chats",cardId:o,messages:gt.map(K=>({role:String(K.role||"system"),text:String(K.text||""),files:Array.isArray(K.files)?K.files:[]})),receiving:!0,processing:u.isProcessing(o)}]);}catch{}}return S}if(n==="file-upload"){let G=w().normalizeIncoming(d?.files,O);return G.length>0&&w().merge(q,G),S}if(n==="action"){let G=d&&typeof d.buttonId=="string"?d.buttonId:"";if(!G)return S;q.lastAction={buttonId:G,at:O},q.lastActionText=`${G} @ ${O}`;}return S}),C&&St(C.cardId,C.lastEntryId,C.processingAlreadySet,C.turnId??"");}function ee(o,n,d){let p=JSON.stringify(d),C=typeof Buffer<"u"?Buffer.byteLength(p):new TextEncoder().encode(p).length;o.writeHead(n,{...r,"Content-Type":"application/json; charset=utf-8","Content-Length":C}),o.end(p);}function $t(o,n,d){let p=D(o);if(!p)throw Object.assign(new Error("Card not found"),{statusCode:404});let C=w().resolve(p.card_data,n,d);if(!C.ok&&C.reason==="stale_reference")throw Object.assign(new Error("File reference is stale. Refresh and try again."),{statusCode:409});if(!C.ok)throw Object.assign(new Error("File not found"),{statusCode:404});let S=C.file,O=_(o),q=R(o),G=String(S.stored_name||""),ue=`${O}/${G}`,de=q.files?q.files.getBytes(ue):null;if(!de)throw Object.assign(new Error("File not found"),{statusCode:404});return {fileRecord:S,bytes:de}}function Dt(o,n,d,p){let{fileRecord:C,bytes:S}=$t(n,d,p),O=String(C.name||C.stored_name||"download.bin"),q=String(C.mime_type||"application/octet-stream");o.writeHead(200,{"Content-Type":q,"Content-Disposition":`attachment; filename="${O}"`,"Content-Length":S.length}),o.end(S);}function at(o){let n=String(o||"").toLowerCase();return n.startsWith("text/")||n.includes("json")||n.includes("xml")||n.includes("javascript")||n.includes("typescript")||n.includes("yaml")||n.includes("csv")}function ft(o,n,d){let p=o.split(/\r?\n/);return (n==="head"?p.slice(0,d):p.slice(-d)).join(`
|
|
2
|
-
`)}async function
|
|
1
|
+
import {createRequire}from'module';import'ajv-formats';var bt="b64:";function rn(e){let t=new TextEncoder().encode(e),r=globalThis.Buffer,s;if(r)s=r.from(t).toString("base64");else if(typeof btoa=="function"){let a="";for(let i of t)a+=String.fromCharCode(i);s=btoa(a);}else throw new Error("No base64 encoder available in this runtime");return s.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function nn(e){let t=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-e.length%4)%4),r=globalThis.Buffer;if(r)return r.from(t,"base64").toString("utf8");if(typeof atob=="function"){let s=atob(t),a=new Uint8Array(s.length);for(let i=0;i<s.length;i+=1)a[i]=s.charCodeAt(i);return new TextDecoder().decode(a)}throw new Error("No base64 decoder available in this runtime")}function Fe(e){return `${bt}${rn(JSON.stringify(e))}`}function ot(e){if(!e.startsWith(bt))throw new Error(`Invalid ref format (expected ${bt}<base64url(json)>): ${e}`);let t;try{t=JSON.parse(nn(e.slice(bt.length)));}catch{throw new Error(`Invalid ref format (malformed base64url/json): ${e}`)}if(!t||typeof t!="object")throw new Error(`Invalid ref format (expected object payload): ${e}`);let r=t;if(typeof r.kind!="string"||typeof r.value!="string")throw new Error(`Invalid ref format (payload must contain string kind/value): ${e}`);return {kind:r.kind,value:r.value}}async function Zt(e,t,r){let s=e.tryAcquire();if(!s)return false;try{await t();}finally{s();}return r?.(),true}var Ze={RUNNING:"running",COMPLETED:"completed",FAILED:"failed",INACTIVATED:"inactivated"};function qe(e){return e?Array.isArray(e.provides)?e.provides:[]:[]}function Qe(e){return e?Array.isArray(e.requires)?e.requires:[]:[]}function Qt(e){return e.tasks??{}}function Pt(e){return e?e.status===Ze.FAILED||e.status===Ze.INACTIVATED:false}function er(e,t){return e.refreshStrategy??t?.refreshStrategy??"data-changed"}function tr(e){return e.maxExecutions}function rr(e,t){let r=new Set;for(let[s,a]of Object.entries(t))if(a.status===Ze.COMPLETED){let i=e.tasks[s];i&&qe(i).forEach(u=>r.add(u));}return Array.from(r)}function nr(e,t){let r={};return e.forEach(s=>{let a=t[s];if(!a)return;qe(a).forEach(c=>{r[c]||(r[c]=[]),r[c].push(s);});}),r}function or(e,t,r){let s=e.tasks[t]??St(),a={};if(r){let c=r.tasks[t],u=Qe(c);for(let m of u)for(let[O,$]of Object.entries(r.tasks))if(qe($).includes(m)){let k=e.tasks[O];k?.lastDataHash&&(a[m]=k.lastDataHash);break}}let i={...s,status:"running",startedAt:new Date().toISOString(),lastUpdated:new Date().toISOString(),progress:0,error:void 0,startConsumedHashes:a};return {...e,tasks:{...e.tasks,[t]:i},lastUpdated:new Date().toISOString()}}function sr(e,t,r,s,a,i){let c=e.tasks[r]??St(),u=t.tasks[r];if(!u)throw new Error(`Task "${r}" not found in graph`);let m;s&&u.on&&u.on[s]?m=u.on[s]:m=qe(u);let O=c.startConsumedHashes?{...c.startConsumedHashes}:{...c.lastConsumedHashes};if(!c.startConsumedHashes){let v=u.requires??[];for(let T of v)for(let[w,N]of Object.entries(t.tasks))if(qe(N).includes(T)){let x=e.tasks[w];x?.lastDataHash&&(O[T]=x.lastDataHash);break}}let $={...c,status:"completed",completedAt:new Date().toISOString(),lastUpdated:new Date().toISOString(),executionCount:c.executionCount+1,lastEpoch:c.executionCount+1,lastDataHash:a,data:i,lastConsumedHashes:O,error:void 0},k=[...new Set([...e.availableOutputs,...m])];return {...e,tasks:{...e.tasks,[r]:$},availableOutputs:k,lastUpdated:new Date().toISOString()}}function ar(e,t,r,s){let a=e.tasks[r]??St(),i=t.tasks[r];if(i?.retry){let m=a.retryCount+1;if(m<=i.retry.max_attempts){let O={...a,status:"not-started",retryCount:m,lastUpdated:new Date().toISOString(),error:s};return {...e,tasks:{...e.tasks,[r]:O},lastUpdated:new Date().toISOString()}}}let c={...a,status:"failed",failedAt:new Date().toISOString(),lastUpdated:new Date().toISOString(),error:s,executionCount:a.executionCount+1},u=e.availableOutputs;if(i?.on_failure&&i.on_failure.length>0&&(u=[...new Set([...e.availableOutputs,...i.on_failure])]),i?.circuit_breaker&&c.executionCount>=i.circuit_breaker.max_executions){let m=i.circuit_breaker.on_break;u=[...new Set([...u,...m])];}return {...e,tasks:{...e.tasks,[r]:c},availableOutputs:u,lastUpdated:new Date().toISOString()}}function ir(e,t,r,s){let a=e.tasks[t]??St(),i={...a,progress:typeof s=="number"?s:a.progress,messages:[...a.messages??[],...r?[{message:r,timestamp:new Date().toISOString(),status:a.status}]:[]],lastUpdated:new Date().toISOString()};return {...e,tasks:{...e.tasks,[t]:i},lastUpdated:new Date().toISOString()}}function dr(e,t){let r=e.tasks[t];if(!r)return e;let s={...r,status:"not-started",startedAt:void 0,completedAt:void 0,failedAt:void 0,error:void 0,data:void 0,progress:null,lastUpdated:new Date().toISOString()};return {...e,tasks:{...e.tasks,[t]:s},lastUpdated:new Date().toISOString()}}function St(){return {status:"not-started",executionCount:0,retryCount:0,lastEpoch:0,messages:[],progress:null}}function wt(e,t){let r=`live-${Date.now()}`,s={};for(let i of Object.keys(e.tasks))s[i]=ur();let a={status:"running",tasks:s,availableOutputs:[],stuckDetection:{is_stuck:false,stuck_description:null,outputs_unresolvable:[],tasks_blocked:[]},lastUpdated:new Date().toISOString(),executionId:r,executionConfig:{executionMode:e.settings.execution_mode??"eligibility-mode",conflictStrategy:e.settings.conflict_strategy??"alphabetical",completionStrategy:e.settings.completion}};return {config:e,state:a}}function on(e,t){let{config:r,state:s}=e;if("executionId"in t&&t.executionId&&t.executionId!==s.executionId)return e;switch(t.type){case "task-started":return {config:r,state:or(s,t.taskName,r)};case "task-completed":return {config:r,state:sr(s,r,t.taskName,t.result,t.dataHash,t.data)};case "task-failed":return {config:r,state:ar(s,r,t.taskName,t.error)};case "task-progress":return {config:r,state:ir(s,t.taskName,t.message,t.progress)};case "task-restart":return {config:r,state:dr(s,t.taskName)};case "inject-tokens":return {config:r,state:{...s,availableOutputs:[...new Set([...s.availableOutputs,...t.tokens])],lastUpdated:new Date().toISOString()}};case "agent-action":return {config:r,state:fn(s,t.action)};case "task-upsert":return sn(e,t.taskName,t.taskConfig);case "task-removal":return an(e,t.taskName);case "node-requires-add":return dn(e,t.nodeName,t.tokens);case "node-requires-remove":return cn(e,t.nodeName,t.tokens);case "node-provides-add":return un(e,t.nodeName,t.tokens);case "node-provides-remove":return ln(e,t.nodeName,t.tokens);default:return e}}function cr(e,t){return t.reduce((r,s)=>on(r,s),e)}function sn(e,t,r){let s=!!e.config.tasks[t];return {config:{...e.config,tasks:{...e.config.tasks,[t]:r}},state:{...e.state,tasks:{...e.state.tasks,[t]:s?e.state.tasks[t]:ur()},lastUpdated:new Date().toISOString()}}}function an(e,t){if(!e.config.tasks[t])return e;let{[t]:r,...s}=e.config.tasks,{[t]:a,...i}=e.state.tasks;return {config:{...e.config,tasks:s},state:{...e.state,tasks:i,lastUpdated:new Date().toISOString()}}}function dn(e,t,r){let s=e.config.tasks[t];if(!s)return e;let a=Qe(s),i=r.filter(c=>!a.includes(c));return i.length===0?e:{config:{...e.config,tasks:{...e.config.tasks,[t]:{...s,requires:[...a,...i]}}},state:e.state}}function cn(e,t,r){let s=e.config.tasks[t];if(!s)return e;let a=Qe(s),i=a.filter(c=>!r.includes(c));return i.length===a.length?e:{config:{...e.config,tasks:{...e.config.tasks,[t]:{...s,requires:i}}},state:e.state}}function un(e,t,r){let s=e.config.tasks[t];if(!s)return e;let a=qe(s),i=r.filter(c=>!a.includes(c));return i.length===0?e:{config:{...e.config,tasks:{...e.config.tasks,[t]:{...s,provides:[...a,...i]}}},state:e.state}}function ln(e,t,r){let s=e.config.tasks[t];if(!s)return e;let a=qe(s),i=a.filter(c=>!r.includes(c));return i.length===a.length?e:{config:{...e.config,tasks:{...e.config.tasks,[t]:{...s,provides:i}}},state:e.state}}function ft(e){return {version:1,config:e.config,state:e.state,snapshotAt:new Date().toISOString()}}function vt(e){if(!e||typeof e!="object")throw new Error("Invalid snapshot: expected an object");let t=e;if(!t.config||typeof t.config!="object")throw new Error('Invalid snapshot: missing or invalid "config"');if(!t.state||typeof t.state!="object")throw new Error('Invalid snapshot: missing or invalid "state"');let r=t.config,s=t.state;if(!r.settings||typeof r.settings!="object")throw new Error("Invalid snapshot: config.settings missing");if(!r.tasks||typeof r.tasks!="object")throw new Error("Invalid snapshot: config.tasks missing");if(!s.tasks||typeof s.tasks!="object")throw new Error("Invalid snapshot: state.tasks missing");if(!Array.isArray(s.availableOutputs))throw new Error("Invalid snapshot: state.availableOutputs must be an array");return {config:r,state:s}}function ur(){return {status:"not-started",executionCount:0,retryCount:0,lastEpoch:0,messages:[],progress:null}}function fn(e,t){let r=new Date().toISOString();switch(t){case "stop":return {...e,status:"stopped",lastUpdated:r};case "pause":return {...e,status:"paused",lastUpdated:r};case "resume":return {...e,status:"running",lastUpdated:r};default:return e}}function pt(e){let{config:t,state:r}=e,s=Qt(t);if(Object.keys(s).length===0)return {eligible:[],pending:[],unresolved:[],blocked:[],conflicts:{}};let i=pn(s),c=rr(t,r.tasks),u=new Set([...c,...r.availableOutputs]),m=[],O=[],$=[],k=[];for(let[T,w]of Object.entries(s)){let N=r.tasks[T],x=er(w,t.settings),L=x!=="once";if(N?.status===Ze.RUNNING||Pt(N))continue;let H=tr(w);if(H!==void 0&&N&&N.executionCount>=H||w.circuit_breaker&&N&&N.executionCount>=w.circuit_breaker.max_executions||!L&&N?.status===Ze.COMPLETED)continue;if(L&&N?.status===Ze.COMPLETED){let y=Qe(w),l=false;switch(x){case "data-changed":{y.length>0&&y.some(S=>{for(let[A,_]of Object.entries(s))if(qe(_).includes(S)){let j=r.tasks[A];if(!j)continue;let Y=N.lastConsumedHashes?.[S];return j.lastDataHash==null?j.executionCount>N.lastEpoch:j.lastDataHash!==Y}return false})||(l=true);break}case "epoch-changed":{y.length>0&&y.some(S=>{for(let[A,_]of Object.entries(s))if(qe(_).includes(S)){let j=r.tasks[A];if(j&&j.executionCount>N.lastEpoch)return true}return false})||(l=true);break}case "time-based":{let p=w.refreshInterval??0;if(p<=0){l=true;break}let S=N.completedAt;if(!S){l=true;break}(Date.now()-Date.parse(S))/1e3<p&&(l=true);break}case "manual":l=true;break}if(l)continue}let I=Qe(w);if(I.length===0){m.push(T);continue}let M=[],R=[],C=[];for(let y of I){if(u.has(y))continue;let l=i[y]||[];l.length===0?M.push(y):l.every(S=>Pt(r.tasks[S]))?C.push({token:y,failedProducer:l[0]}):R.push(y);}M.length>0?$.push({taskName:T,missingTokens:M}):C.length>0?k.push({taskName:T,failedTokens:C.map(y=>y.token),failedProducers:[...new Set(C.map(y=>y.failedProducer))]}):R.length>0?O.push({taskName:T,waitingOn:R}):m.push(T);}let v={};if(m.length>1){let T=nr(m,s);for(let[w,N]of Object.entries(T))N.length>1&&(v[w]=N);}return {eligible:m,pending:O,unresolved:$,blocked:k,conflicts:v}}function pn(e){let t={};for(let[r,s]of Object.entries(e)){for(let a of qe(s))t[a]||(t[a]=[]),t[a].push(r);if(s.on)for(let a of Object.values(s.on))for(let i of a)t[i]||(t[i]=[]),t[i].includes(r)||t[i].push(r);if(s.on_failure)for(let a of s.on_failure)t[a]||(t[a]=[]),t[a].includes(r)||t[a].push(r);}return t}var gt=class{buffer=[];append(t){this.buffer.push(t);}drain(){let t=this.buffer;return this.buffer=[],t}get size(){return this.buffer.length}};function $t(e){let t=Dt(e);return gn(t)}function Dt(e){if(e==null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return "["+e.map(Dt).join(",")+"]";let t=e;return "{"+Object.keys(t).sort().map(s=>JSON.stringify(s)+":"+Dt(t[s])).join(",")+"}"}function gn(e){let t=0xcbf29ce484222325n,r=0x100000001b3n,s=0xffffffffffffffffn;for(let a=0;a<e.length;a++)t^=BigInt(e.charCodeAt(a)),t=t*r&s;return t.toString(16).padStart(16,"0")}function mn(e){if(typeof Buffer<"u")return Buffer.from(e,"utf8").toString("base64url");if(typeof btoa=="function"){let t=new TextEncoder().encode(e),r="";for(let s of t)r+=String.fromCharCode(s);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}throw new Error("No base64 encoder available in this runtime")}function hn(e){if(typeof Buffer<"u")return Buffer.from(e,"base64url").toString("utf8");if(typeof atob=="function"){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r=t+"=".repeat((4-t.length%4)%4),s=atob(r),a=new Uint8Array(s.length);for(let i=0;i<s.length;i++)a[i]=s.charCodeAt(i);return new TextDecoder().decode(a)}throw new Error("No base64 decoder available in this runtime")}function lr(e){let t=JSON.stringify({t:e,n:Date.now().toString(36)+Math.random().toString(36).slice(2,6)});return mn(t)}function yn(e){try{let t=JSON.parse(hn(e));return typeof t?.t=="string"?{taskName:t.t}:null}catch{return null}}function fr(e,t,r){let{handlers:s,onNodeRemoved:a,onDrain:i}=t,c=new gt,u="state"in e&&"config"in e?e:wt(e),m=false,O=new Set,$=new Map(Object.entries(s)),k=new gt,v=false,T=false;function w(){if(!m){if(v){T=true;return}v=true;try{do T=!1,N();while(T)}finally{v=false;}}}function N(){let I=k.drain(),M=c.drain(),R=[...I,...M];if(R.length>0&&(u=cr(u,R),a)){for(let y of R)if(y.type==="task-removal")try{a(y.taskName);}catch(l){console.warn("[reactive] onNodeRemoved failed:",l instanceof Error?l.message:String(l));}}let C=pt(u);R.length>0&&i?.(R,u,C);for(let y of C.eligible)H(y);for(let y of R)if(y.type==="task-progress"){let{taskName:l,update:p}=y;if(!u.config.tasks[l])continue;let A=u.state.tasks[l];if(!A||A.status!=="running")continue;let _=lr(l),j=L(l,_,p).catch(Y=>{m||(k.append({type:"task-failed",taskName:l,error:Y.message??String(Y),timestamp:new Date().toISOString()}),w());}).finally(()=>{O.delete(j);});O.add(j);}}function x(I){let R=u.config.tasks[I].requires??[],C=new Map;for(let[l,p]of Object.entries(u.config.tasks))for(let S of p.provides??[])C.set(S,l);let y={};for(let l of R){let p=C.get(l);p?y[l]=u.state.tasks[p]?.data:y[l]=void 0;}return y}async function L(I,M,R){let C=u.config.tasks[I],y=C.taskHandlers??[],l=x(I);for(let p of y){let S=$.get(p);if(!S)throw new Error(`Handler '${p}' not found in registry (task '${I}')`);let A={nodeId:I,state:l,taskState:u.state.tasks[I],config:C,callbackToken:M,update:R};if(await S(A)==="task-initiate-failure")throw new Error(`Handler '${p}' returned task-initiate-failure (task '${I}')`)}}function H(I){let R=u.config.tasks[I]?.taskHandlers;if(!R||R.length===0)return;k.append({type:"task-started",taskName:I,timestamp:new Date().toISOString()}),w();let C=lr(I),y=L(I,C).catch(l=>{m||(k.append({type:"task-failed",taskName:I,error:l.message??String(l),timestamp:new Date().toISOString()}),w());}).finally(()=>{O.delete(y);});O.add(y);}return {push(I){m||(I.type==="task-completed"&&I.data&&!I.dataHash&&(I={...I,dataHash:$t(I.data)}),c.append(I),w());},pushAll(I){if(!m){for(let M of I)M.type==="task-completed"&&M.data&&!M.dataHash?c.append({...M,dataHash:$t(M.data)}):c.append(M);w();}},resolveCallback(I,M,R){if(m)return;let C=yn(I);if(!C)return;let{taskName:y}=C;if(u.config.tasks[y]){if(R&&R.length>0)c.append({type:"task-failed",taskName:y,error:R.join("; "),timestamp:new Date().toISOString()});else {let l=M&&Object.keys(M).length>0?$t(M):void 0;c.append({type:"task-completed",taskName:y,data:M,dataHash:l,timestamp:new Date().toISOString()});}w();}},addNode(I,M){m||(c.append({type:"task-upsert",taskName:I,taskConfig:M,timestamp:new Date().toISOString()}),w());},removeNode(I){m||(c.append({type:"task-removal",taskName:I,timestamp:new Date().toISOString()}),w());},addRequires(I,M){m||(c.append({type:"node-requires-add",nodeName:I,tokens:M,timestamp:new Date().toISOString()}),w());},removeRequires(I,M){m||(c.append({type:"node-requires-remove",nodeName:I,tokens:M,timestamp:new Date().toISOString()}),w());},addProvides(I,M){m||(c.append({type:"node-provides-add",nodeName:I,tokens:M,timestamp:new Date().toISOString()}),w());},removeProvides(I,M){m||(c.append({type:"node-provides-remove",nodeName:I,tokens:M,timestamp:new Date().toISOString()}),w());},registerHandler(I,M){$.set(I,M);},unregisterHandler(I){$.delete(I);},retrigger(I){m||u.config.tasks[I]&&(c.append({type:"task-restart",taskName:I,timestamp:new Date().toISOString()}),w());},retriggerAll(I){if(!m){for(let M of I)u.config.tasks[M]&&c.append({type:"task-restart",taskName:M,timestamp:new Date().toISOString()});w();}},snapshot(){return ft(u)},getState(){return u},getSchedule(){return pt(u)},async waitForHandlers(){O.size>0&&await Promise.allSettled([...O]);},async dispose(I){I?.wait&&O.size>0&&await Promise.allSettled([...O]),m=true;}}}var kn=createRequire(import.meta.url);kn("./jsonata-sync.cjs");var bn=createRequire(import.meta.url),xt=bn("./jsonata-sync.cjs"),mr=xt;function pr(e,t){if(!t||!e)return;let r=t.split("."),s=e;for(let a=0;a<r.length;a++){if(s==null)return;s=s[r[a]];}return s}function hr(e,t,r){let s=t.split("."),a=e;for(let i=0;i<s.length-1;i++)(a[s[i]]==null||typeof a[s[i]]!="object")&&(a[s[i]]={}),a=a[s[i]];a[s[s.length-1]]=r;}async function Sn(e,t){if(!e?.compute?.length)return e;e.card_data||(e.card_data={}),e.computed_values={},e._sourcesData=t?.sourcesData??{};let r=e.requires??{},s={card_data:e.card_data,requires:r,expects_data:r,fetched_sources:e._sourcesData,data:e.computed_values,computed_values:e.computed_values};for(let a of e.compute)try{let i=await xt(a.expr).evaluate(s);hr(e.computed_values,a.bindTo,i),s.computed_values=e.computed_values;}catch{}return e}function wn(e,t){if(!e?.compute?.length)return {ok:true,node:e};e.card_data||(e.card_data={}),e.computed_values={},e._sourcesData=t?.sourcesData??{};let r=e.requires??{},s={card_data:e.card_data,requires:r,expects_data:r,fetched_sources:e._sourcesData,data:e.computed_values,computed_values:e.computed_values},a=[];for(let i of e.compute)try{let c=mr(i.expr).evaluate(s);hr(e.computed_values,i.bindTo,c),s.computed_values=e.computed_values;}catch(c){let u=c instanceof Error?c.message:String(c);a.push({bindTo:i.bindTo,error:u});}return a.length>0?{ok:true,node:e,errors:a}:{ok:true,node:e}}async function vn(e,t,r){let s={...r??{},card_data:t.card_data??{},requires:t.requires??{},fetched_sources:t._sourcesData??{},computed_values:t.computed_values??{}};return xt(e).evaluate(s)}function xn(e,t){return t.startsWith("fetched_sources.")?pr(e._sourcesData??{},t.slice(16)):pr(e,t)}var gr=new Set(["metric","table","editable-table","chart","form","filter","list","notes","todo","alert","narrative","badge","text","markdown","ref","custom","actions"]),An=new Set(["id","meta","requires","provides","view","card_data","compute","source_defs"]);function In(e){let t=[];if(!e||typeof e!="object"||Array.isArray(e))return {ok:false,errors:["Node must be a non-null object"]};let r=e;(typeof r.id!="string"||!r.id)&&t.push("id: required, must be a non-empty string");for(let s of Object.keys(r))An.has(s)||t.push(`Unknown top-level key: "${s}"`);if((r.card_data==null||typeof r.card_data!="object"||Array.isArray(r.card_data))&&t.push("card_data: required, must be an object"),r.meta!=null)if(typeof r.meta!="object"||Array.isArray(r.meta))t.push("meta: must be an object");else {let s=r.meta;s.title!=null&&typeof s.title!="string"&&t.push("meta.title: must be a string"),s.tags!=null&&!Array.isArray(s.tags)&&t.push("meta.tags: must be an array");}if(r.requires!=null&&!Array.isArray(r.requires)&&t.push("requires: must be an array of strings"),r.provides!=null&&(Array.isArray(r.provides)?r.provides.forEach((s,a)=>{if(!s||typeof s!="object"||Array.isArray(s))t.push(`provides[${a}]: must be an object with bindTo and ref`);else {let i=s;(typeof i.bindTo!="string"||!i.bindTo)&&t.push(`provides[${a}]: missing required "bindTo" string`),(typeof i.ref!="string"||!i.ref)&&t.push(`provides[${a}]: missing required "ref" string`);}}):t.push("provides: must be an array of { bindTo, ref } bindings")),r.compute!=null&&(Array.isArray(r.compute)?r.compute.forEach((s,a)=>{if(!s||typeof s!="object"||Array.isArray(s))t.push(`compute[${a}]: must be a compute step object`);else {let i=s;(typeof i.bindTo!="string"||!i.bindTo)&&t.push(`compute[${a}]: missing required "bindTo" property`),(typeof i.expr!="string"||!i.expr)&&t.push(`compute[${a}]: missing required "expr" string (JSONata expression)`);}}):t.push("compute: must be an array of compute steps")),r.source_defs!=null)if(!Array.isArray(r.source_defs))t.push("source_defs: must be an array");else {let s=new Set,a=new Set;r.source_defs.forEach((i,c)=>{if(!i||typeof i!="object"||Array.isArray(i))t.push(`source_defs[${c}]: must be an object`);else {let u=i;typeof u.bindTo!="string"||!u.bindTo?t.push(`source_defs[${c}]: missing required "bindTo" property`):(s.has(u.bindTo)&&t.push(`source_defs[${c}]: bindTo "${u.bindTo}" is not unique across source_defs`),s.add(u.bindTo)),typeof u.outputFile!="string"||!u.outputFile?t.push(`source_defs[${c}]: missing required "outputFile" property`):(a.has(u.outputFile)&&t.push(`source_defs[${c}]: outputFile "${u.outputFile}" is not unique across source_defs`),a.add(u.outputFile)),u.optionalForCompletionGating!=null&&typeof u.optionalForCompletionGating!="boolean"&&t.push(`source_defs[${c}]: optionalForCompletionGating must be a boolean`);}});}if(r.view!=null)if(typeof r.view!="object"||Array.isArray(r.view))t.push("view: must be an object");else {let s=r.view;!Array.isArray(s.elements)||s.elements.length===0?t.push("view.elements: required, must be a non-empty array"):s.elements.forEach((a,i)=>{if(!a||typeof a!="object"){t.push(`view.elements[${i}]: must be an object`);return}!a.kind||typeof a.kind!="string"?t.push(`view.elements[${i}].kind: required, must be a string`):gr.has(a.kind)||t.push(`view.elements[${i}].kind: unknown kind "${a.kind}". Valid: ${[...gr].join(", ")}`),a.data!=null&&(typeof a.data!="object"||Array.isArray(a.data))&&t.push(`view.elements[${i}].data: must be an object`);}),s.layout!=null&&(typeof s.layout!="object"||Array.isArray(s.layout))&&t.push("view.layout: must be an object"),s.features!=null&&(typeof s.features!="object"||Array.isArray(s.features))&&t.push("view.features: must be an object");}return {ok:t.length===0,errors:t}}async function _n(e,t){if(!e||e.length===0)return [];let r={card_data:t.card_data??{},requires:t.requires??{}};return Promise.all(e.map(async s=>{let a={};if(s.projections&&typeof s.projections=="object"&&!Array.isArray(s.projections)){for(let[i,c]of Object.entries(s.projections))if(typeof c=="string"&&c.trim().length>0)try{a[i]=await xt(c).evaluate(r);}catch{a[i]=void 0;}}return {...s,_projections:a}}))}function Tn(e,t){if(!e||e.length===0)return [];let r={card_data:t.card_data??{},requires:t.requires??{}};return e.map(s=>{let a={};if(s.projections&&typeof s.projections=="object"&&!Array.isArray(s.projections)){for(let[i,c]of Object.entries(s.projections))if(typeof c=="string"&&c.trim().length>0)try{a[i]=mr(c).evaluate(r);}catch{a[i]=void 0;}}return {...s,_projections:a}})}var Ge={run:Sn,runSync:wn,eval:vn,resolve:xn,validate:In,enrichSources:_n,enrichSourcesSync:Tn};function yr(e){return JSON.stringify(e)}function Cr(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}function mt(e,t){function r(){return e.readIndex()??{}}function s(a,i,c){let u=String(i||"").split(".").filter(Boolean);if(u.length===0)return c&&typeof c=="object"&&!Array.isArray(c)?c:{value:c};let m={...a},O=m;for(let $=0;$<u.length-1;$++){let k=u[$],v=O[k],T=v&&typeof v=="object"&&!Array.isArray(v)?{...v}:{};O[k]=T,O=T;}return O[u[u.length-1]]=c,m}return {readCard(a){let i=r()[a];return !i||!e.cardExists(i.key)?null:e.readCard(i.key)},readCardKey(a){return r()[a]?.key??null},readAllCards(){let a=[];for(let[i,c]of Object.entries(r())){if(!e.cardExists(c.key))continue;let u=e.readCard(c.key);u?a.push(u):t?.(`[card-store] could not read card "${i}" at key "${c.key}"`);}return a},readChecksumIndex(){let a={};for(let[i,c]of Object.entries(r()))a[i]=c.checksum;return a},changedSince(a){let i=r(),c=[];for(let[u,m]of Object.entries(i))a[u]!==m.checksum&&c.push(u);for(let u of Object.keys(a))i[u]||c.push(u);return c},validateUpsert(a,i){let c=r(),u=c[a],m=Object.entries(c).find(([,O])=>O.key===i);return u&&u.key!==i?{ok:false,error:`Card id "${a}" is already mapped to key "${u.key}", cannot remap to "${i}"`}:m&&m[0]!==a?{ok:false,error:`Key "${i}" is already mapped to card id "${m[0]}", cannot remap to "${a}"`}:{ok:true}},writeCard(a,i,c){let u=r(),m=c??u[a]?.key??e.defaultCardKey(a),O=e.writeCard(m,i);u[a]={key:m,checksum:O,updatedAt:new Date().toISOString()},e.writeIndex(u);},patchCard(a,i,c){let u=r(),m=u[a];if(!m||!e.cardExists(m.key))throw new Error(`card "${a}" not found`);let O=e.readCard(m.key);if(!O||typeof O!="object"||Array.isArray(O))throw new Error(`card "${a}" is not patchable`);let $=s(O,i,c),k=e.writeCard(m.key,$);u[a]={key:m.key,checksum:k,updatedAt:new Date().toISOString()},e.writeIndex(u);},removeCard(a){let i=r(),c=i[a];c&&(e.removeCard(c.key),delete i[a],e.writeIndex(i));},readIndex(){return r()}}}function At(e,t){return {readSourceData(r,s){let a=e.read(`${r}/${s}`);if(a==null)return null;let i=a.trim();if(!i)return null;try{return JSON.parse(i)}catch{return i}},ingestSourceDataStaged(r,s,a,i){let c=t(a);e.write(`${r}/.staged/${i}/${s}`,c);},commitSourceData(r,s,a){let i=`${r}/.staged/${a}/${s}`,c=e.read(i);return c==null?false:(e.write(`${r}/${s}`,c),e.remove(i),true)},hasSource(r,s){return e.exists(`${r}/${s}`)},listSources(r){return e.listKeys(`${r}/`).filter(s=>!s.includes("/.staged/")).map(s=>s.slice(`${r}/`.length))}}}function wr(e){function t(r){let s=e.readAllEntries();if(!r)return s;let a=s.findIndex(i=>i.id===r);return a===-1?s:s.slice(a+1)}return {readEntriesAfterCursor(r){let s=t(r);return s.length===0?{events:[],newCursor:r}:{events:s.map(a=>a.event),newCursor:s[s.length-1].id}},pendingCount(r){return t(r).length},appendEvent(r){e.appendEntry({id:e.generateId(),event:r});}}}function vr(e,t){return {appendEntries(r,s){if(!r||s.length===0)return;let a=e.read(r)??[];e.write(r,[...a,...s]);},dispatchEntriesForJournalId(r,s){if(!r)return;let a=e.read(r);if(!(!a||a.length===0)){for(let i of a)try{s(i);}catch(c){let u=c instanceof Error?c.message:String(c);try{t(i,u);}catch{}}e.delete(r);}}}}var It="v1",rt="board/graph",xr="board/lastJournalProcessedId";function kr(e){return `cards/${e}/runtime`}function Ar(e){return {readRuntime(t){return e.read(kr(t))??{_sources:{}}},writeRuntime(t,r){e.write(kr(t),r);}}}function En(e,t){let r={...e};for(let s of t.deleteKeys)delete r[s];return {...r,...t.shallowMerge}}function Ir(e){return {readSnapshot(t){return e.readValues(t)},commitSnapshot(t,r){if(r.schemaVersion!==It)throw new Error(`Unsupported snapshot schema version: ${r.schemaVersion}`);let s=e.readValues(t);if(s.version!==r.expectedVersion)return {ok:false,reason:"version-mismatch",currentVersion:s.version};let a=En(s.values,r);return {ok:true,newVersion:e.writeValues(t,a,r.deleteKeys)}}}}function Lt(e){function t(r){let s=e.read(r);return s==null?null:typeof s=="string"?s:JSON.stringify(s)}return {readTaskExecutorRef(){let r=t("task-executor");if(r?.trim())return Cr(r.trim())},writeTaskExecutorRef(r){e.write("task-executor",yr(r));},readChatHandlerFlow(){return e.read("chat-handler-flow")},writeChatHandlerFlow(r){e.write("chat-handler-flow",r);},readCardStoreRef(){return t("card-store-ref")},writeCardStoreRef(r){e.write("card-store-ref",r);},readOutputsStoreRef(){return t("outputs-store-ref")},writeOutputsStoreRef(r){e.write("outputs-store-ref",r);},readScratchStoreRef(){return t("scratch-store-ref")},writeScratchStoreRef(r){e.write("scratch-store-ref",r);},readArchiveStoreRef(){return t("archive-store-ref")},writeArchiveStoreRef(r){e.write("archive-store-ref",r);},readChatStoreRef(){return t("chat-store-ref")},writeChatStoreRef(r){e.write("chat-store-ref",r);},readArtifactsStoreRef(){return t("artifacts-store-ref")},writeArtifactsStoreRef(r){e.write("artifacts-store-ref",r);}}}function _r(e){return {writeComputedValues(t,r){e.write(`cards/${t}/computed_values`,r);},readComputedValues(t){return e.read(`cards/${t}/computed_values`)},readAllComputedValues(){let t={};for(let r of e.listKeys("cards/")){let s=r.match(/^cards\/([^/]+)\/computed_values$/);s&&(t[s[1]]=e.read(r));}return t},writeDataObjects(t){for(let[r,s]of Object.entries(t))r&&e.write(`data-objects/${r}`,s);},readDataObject(t){return e.read(`data-objects/${t}`)},readAllDataObjects(){let t={};for(let r of e.listKeys("data-objects/"))t[r.slice(13)]=e.read(r);return t},writeStatusSnapshot(t){e.write("status",t);},readStatusSnapshot(){return e.read("status")}}}function Rr(e){return e?{lastRequestedToken:e.lastRequestedToken,lastCompletedToken:e.lastCompletedToken,lastCompletionStatus:e.lastCompletionStatus??(e.lastCompletedToken?"success":"not-started"),queueRequestedToken:e.queueRequestedToken}:{lastCompletionStatus:"not-started"}}function On(e){return e?.lastRequestedToken?e.lastCompletedToken!==e.lastRequestedToken:false}function br(e,t){return e?.lastRequestedToken?On(e)?"in-flight":!e.lastCompletedToken||e.lastCompletedToken<t?"dispatch":"idle":"dispatch"}function jn(e,t){return {...e,lastCompletedToken:t,lastCompletionStatus:"success"}}function Sr(e,t){return {...e,lastCompletedToken:t,lastCompletionStatus:"failure"}}function _t(e,t){let r=t.state.tasks,s=t.config.tasks,a=Object.keys(r),i=pt(t),c={completed:0,failed:0,in_progress:0,pending:0,blocked:0,unresolved:0},u=new Map;for(let w of i.pending)u.set(w.taskName,w.waitingOn);for(let w of i.unresolved)u.set(w.taskName,w.missingTokens);for(let w of i.blocked)u.set(w.taskName,w.failedTokens);let m=new Map;for(let[w,N]of Object.entries(s))for(let x of N.requires??[]){let L=m.get(x)??[];L.push(w),m.set(x,L);}let O=a.sort().map(w=>{let N=r[w],x=s[w]??{requires:[],provides:[]};N.status==="completed"?c.completed+=1:N.status==="failed"?c.failed+=1:N.status==="in-progress"&&(c.in_progress+=1);let L=x.requires??[],H=x.provides??[],I=Object.keys(N.data??{}).sort(),M=L.filter(S=>t.state.availableOutputs.includes(S)),R=L.filter(S=>!t.state.availableOutputs.includes(S)),C=u.get(w)??R,y=new Set;for(let S of H)for(let A of m.get(S)??[])A!==w&&y.add(A);let l=N.failedAt,p=N.error?{message:N.error,code:"TASK_FAILED",at:l,source:"task-runtime"}:void 0;return {name:w,status:N.status,error:p,requires:L,requires_satisfied:M,requires_missing:R,provides_declared:H,provides_runtime:I,blocked_by:C,unblocks:Array.from(y).sort(),runtime:{attempt_count:N.executionCount??0,restart_count:N.retryCount??0,in_progress_since:N.status==="in-progress"?N.startedAt??null:null,last_transition_at:N.lastUpdated??null,last_completed_at:N.completedAt??null,last_restarted_at:N.startedAt??null,status_age_ms:N.lastUpdated?0:null}}});c.pending=i.pending.length,c.blocked=i.blocked.length,c.unresolved=i.unresolved.length;let $=O.map(w=>({name:w.name,fanOut:w.unblocks.length})).sort((w,N)=>N.fanOut-w.fanOut||w.name.localeCompare(N.name)),k=$.length>0?$[0]:{name:null,fanOut:0},v=new Set;for(let w of Object.values(s))for(let N of w.requires??[])v.add(N);let T=0;for(let[w,N]of Object.entries(s)){let x=(N.requires??[]).length===0,H=(N.provides??[]).some(I=>(m.get(I)??[]).some(M=>M!==w));x&&!H&&(T+=1);}return {schema_version:"v1",meta:{board:{path:e}},summary:{card_count:a.length,completed:c.completed,eligible:i.eligible.length,pending:c.pending,blocked:c.blocked,unresolved:c.unresolved,failed:c.failed,in_progress:c.in_progress,orphan_cards:T,topology:{edge_count:Array.from(v).length,max_fan_out_card:k.name,max_fan_out:k.fanOut}},cards:O}}function Bn(){return new Date().toISOString()}function Tr(e,t,r,s,a,i,c){return async u=>{let m=[],O=r.cardStore.readCard(u.nodeId);if(!O)return "task-initiate-failure";let $=O.id,k=O.card_data??{},v=O.source_defs??[],T=v.filter(B=>B.optionalForCompletionGating!==true),w=r.cardRuntimeStore.readRuntime($),N=false,x=()=>{N&&(r.cardRuntimeStore.writeRuntime($,w),N=false);},L=B=>Rr(w._sources[B]),H=(B,q)=>{w._sources[B]=Rr(q),N=true;},I=u.taskState?.executionCount??0;if(w._lastExecutionCount!==I&&(w._sources={},w._lastExecutionCount=I,N=true),u.update){let B=u.update,q=B.outputFile;if(q){let Q=L(q);if(B.failure){let ie=B.rqt??Q.lastRequestedToken??Q.queueRequestedToken;ie&&H(q,Sr(Q,ie));}else {let ie=B.rqt;if(!Q.lastCompletedToken||ie>Q.lastCompletedToken){let ee=typeof B.deliveryToken=="string"?B.deliveryToken:void 0,_e=false;ee&&(_e=r.fetchedSourcesStore.commitSourceData($,q,ee)),_e?H(q,jn(Q,ie)):H(q,Sr(Q,ie));}}x();}}let R={};for(let B of v)if(B.outputFile){let q=r.fetchedSourcesStore.readSourceData($,B.outputFile);q!==null&&(R[B.bindTo]=q);}let C={};for(let[B,q]of Object.entries(u.state??{}))if(q!==null&&typeof q=="object"&&!Array.isArray(q)){let Q=q[B];C[B]=Q!==void 0?Q:q;}else C[B]=q;let y={id:$,card_data:{...k},requires:C,source_defs:v,compute:O.compute};y._sourcesData=R,O.compute&&Ge.runSync(y,{sourcesData:R}),(i??r.outputStore.writeComputedValues.bind(r.outputStore))($,y.computed_values??{});let l={...O},p=Ge.enrichSourcesSync(Array.isArray(O.source_defs)?O.source_defs:void 0,{card_data:O.card_data,requires:C}),S=e.value;l.source_defs=Array.isArray(p)?p.map(B=>({...B,boardDir:typeof B.boardDir=="string"&&B.boardDir?B.boardDir:S})):p;let A=Bn(),_=u.update?void 0:A,j=T.filter(B=>{let q=B.outputFile;if(typeof q!="string"||!q)return true;let Q=L(q);_&&(Q={...Q,queueRequestedToken:_},H(q,Q));let ie=Q.queueRequestedToken??Q.lastRequestedToken??A,ee=br(Q,ie);return ee==="in-flight"?false:ee==="dispatch"});if(x(),j.length>0){let B=false,q=A;for(let Q of j){let ie=Q.outputFile;if(typeof ie!="string"||!ie)continue;let ee=L(ie),_e=ee.queueRequestedToken??A;H(ie,{...ee,lastRequestedToken:_e}),q=_e,B=true;}return B&&x(),B&&(m.push({taskKind:"source-fetch",payload:{boardRef:Fe(e),enrichedCard:l,callbackToken:u.callbackToken,rqt:q}}),r.executionRequestStore.appendEntries(t,m)),"task-initiated"}if(T.some(B=>{let q=B.outputFile;if(typeof q!="string"||!q)return false;let Q=L(q),ie=Q.queueRequestedToken??Q.lastRequestedToken??A;return br(Q,ie)==="in-flight"}))return "task-initiated";let re=O.provides??[],ne={};for(let{bindTo:B,ref:q}of re)ne[B]=Ge.resolve(y,q);return (c??r.outputStore.writeDataObjects.bind(r.outputStore))(ne),v.filter(B=>{if(B.optionalForCompletionGating!==true)return false;let q=L(B.outputFile);return !q.lastRequestedToken||!q.lastCompletedToken?true:q.lastCompletedToken<=q.lastRequestedToken}).length>0&&m.push({taskKind:"source-fetch",payload:{boardRef:Fe(e),enrichedCard:l,callbackToken:u.callbackToken,rqt:A}}),s(u.nodeId,ne),m.length>0&&r.executionRequestStore.appendEntries(t,m),"task-initiated"}}var Mt={settings:{completion:"manual",refreshStrategy:"data-changed"},tasks:{}};function Er(e){return {[rt]:e.graph,[xr]:e.lastDrainedJournalId}}function Or(e){let t=e[rt],r=e[xr];if(!t||typeof t!="object")throw new Error(`State snapshot is missing required key: ${rt}`);return {graph:t,lastDrainedJournalId:typeof r=="string"?r:""}}function jr(e){let t=e.requires,r=e.provides?.map(s=>s.bindTo)??[];return {requires:t&&t.length>0?t:void 0,provides:r,taskHandlers:["card-handler"],description:e.meta?.title??e.id}}function Tt(e){function t(i){return {status:"success",data:i}}function r(i){return {status:"fail",error:i}}function s(i){return {status:"error",error:i instanceof Error?i.message:String(i)}}function a(i){if(Array.isArray(i))return i;if(i&&typeof i=="object"){let c=i;return Array.isArray(c.files)?c.files:[i]}return null}return {get(i){try{let c=i.params?.id;if(c){let u=e.readCard(c);return u?t({cards:[u]}):r(`card "${c}" not found`)}return t({cards:e.readAllCards()})}catch(c){return s(c)}},set(i){try{let c=i.body;if(c==null)return r("set requires a body (card object or array of cards)");let u=Array.isArray(c)?c:[c];for(let m of u){if(typeof m.id!="string")return r("each card must have a string `id` field");e.writeCard(m.id,m);}return t({count:u.length})}catch(c){return s(c)}},del(i){try{let c=i.body?.ids??[],u=i.params?.id,m=u?[...c,u]:c;if(m.length===0)return r("del requires body.ids (string[]) or params.id");for(let O of m)e.removeCard(O);return t({count:m.length})}catch(c){return s(c)}},patch(i){try{let c=i.params?.id,u=i.params?.path;if(!c)return r("patch requires params.id");if(!u)return r("patch requires params.path");let m=i.body,O=m&&Object.prototype.hasOwnProperty.call(m,"value")?m.value:i.body;return e.patchCard(c,u,O),t({count:1})}catch(c){return s(c)}},appendFiles(i){try{let c=i.params?.id;if(!c)return r("appendFiles requires params.id");let u=e.readCard(c);if(!u)return r(`card "${c}" not found`);let m=a(i.body);if(!m||m.length===0)return r("appendFiles requires a file metadata object, array, or body.files array");let O=u.card_data&&typeof u.card_data=="object"&&!Array.isArray(u.card_data)?u.card_data:{},$=Array.isArray(O.files)?O.files:[],k=[...$,...m],v=m.map((w,N)=>({idx:$.length+N,entry:w})),T=this.patch({params:{id:c,path:"card_data.files"},body:{value:k}});return T.status!=="success"?T:t({files_added:v})}catch(c){return s(c)}}}}function ae(e){return e!==void 0?{status:"success",data:e}:{status:"success"}}function z(e){return {status:"fail",error:e}}function de(e){return {status:"error",error:e instanceof Error?e.message:String(e)}}function Fn(e){let t=new TextEncoder().encode(e),r=Array.from(t,s=>String.fromCharCode(s)).join("");return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Fr(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r=t+"=".repeat((4-t.length%4)%4),s=atob(r),a=Uint8Array.from(s,i=>i.charCodeAt(0));return new TextDecoder().decode(a)}function Et(e){try{let t=JSON.parse(Fr(e));return typeof t?.t=="string"?{taskName:t.t}:null}catch{return null}}function qn(e){return Fn(JSON.stringify(e))}function Br(e){try{let t=JSON.parse(Fr(e));return typeof t?.cbk=="string"&&typeof t?.cid=="string"&&typeof t?.b=="string"&&typeof t?.d=="string"?t:null}catch{return null}}function Oe(){return new Date().toISOString()}function qr(e,t){let r=t.onWarn??(()=>{}),s=Fe(e);function a(E){if(E.length!==0)try{let g=t.publishBoardChangeNotifications?.(E);g&&typeof g.catch=="function"&&g.catch(P=>r(`[board-live-cards-public] publishBoardChangeNotifications failed: ${P instanceof Error?P.message:String(P)}`));}catch(g){r(`[board-live-cards-public] publishBoardChangeNotifications failed: ${g instanceof Error?g.message:String(g)}`);}}function i(){let E=u().readCardStoreRef();if(!E)throw new Error(`Board at ${e.value} has no card store configured. Run: init --base-ref <ref> --store-ref <b64-ref>`);let g=t.kvStorageForRef(E);return {readIndex(){return g.read("_index")},writeIndex(P){g.write("_index",P);},readCard(P){return g.read(P)},writeCard(P,G){return g.write(P,G),t.hashFn(G)},removeCard(P){g.delete(P);},cardExists(P){return g.read(P)!==null},defaultCardKey(P){return P}}}let c={readValues(E){let g=t.kvStorage("state-snapshot"),P=g.listKeys().sort();if(P.length===0)return {version:null,values:{}};let G={};for(let oe of P)G[oe]=g.read(oe);return {version:t.hashFn(G),values:G}},writeValues(E,g,P){let G=t.kvStorage("state-snapshot");for(let oe of P)G.delete(oe);for(let[oe,le]of Object.entries(g))G.write(oe,le);return t.hashFn(g)}},u=()=>Lt(t.kvStorage("config")),m=()=>Ir(c),O=()=>wr(t.journalAdapter()),$=()=>mt(i(),r),k=()=>{let E=u().readOutputsStoreRef();if(!E)throw new Error(`Board at ${e.value} has no outputs store configured. Run: init --outputs-store-ref <b64-ref>`);return _r(t.kvStorageForRef(E))},v=()=>{let E=u().readArchiveStoreRef();return E?t.archiveFactoryForRef(E):t.archiveFactory()};function T(){return !!m().readSnapshot(e.value).values[rt]}function w(){let E=m().readSnapshot(e.value);if(!E.values[rt])throw new Error(`Board not initialized at ${e.value}`);return Or(E.values)}function N(E,g){let P=m().commitSnapshot(e.value,{schemaVersion:It,expectedVersion:g,commitId:t.genId(),committedAt:Oe(),deleteKeys:[],shallowMerge:Er(E)});if(!P.ok)throw new Error(`Snapshot commit failed (version mismatch): expected=${g??"null"} current=${P.currentVersion??"null"}`)}function x(E){O().appendEvent(E);}async function L(){let E=(D,W)=>{let ye=D.payload,Be=(ye?.enrichedCard??{}).id??ye?.cardId??"unknown";x({type:"task-failed",taskName:Be,error:W,timestamp:Oe()});},g=vr(t.kvStorage("execution-requests"),E),P=Ar(t.kvStorage("card-runtime")),G=At(t.blobStorage("sources"),D=>t.resolveBlob(D)),oe=new Map,le={readRuntime(D){return oe.get(D)??P.readRuntime(D)},writeRuntime(D,W){oe.set(D,W);}},ve=[],he=new Map,xe={readSourceData(D,W){let ye=`${D}/${W}`;return he.has(ye)?he.get(ye):G.readSourceData(D,W)},ingestSourceDataStaged(D,W,ye,$e){G.ingestSourceDataStaged(D,W,ye,$e);},commitSourceData(D,W,ye){let $e=`${D}/.staged/${ye}/${W}`,Xe=t.blobStorage("sources").read($e);if(Xe==null)return false;let De=`${D}/${W}`,ut=Xe.trim();try{he.set(De,JSON.parse(ut));}catch{he.set(De,ut);}return ve.push({cardId:D,outputFile:W,deliveryToken:ye}),true},hasSource(D,W){let ye=`${D}/${W}`;return he.has(ye)?true:G.hasSource(D,W)},listSources(D){let W=G.listSources(D),ye=new Set;for(let Be of he.keys())Be.startsWith(`${D}/`)&&ye.add(Be.slice(`${D}/`.length));let $e=new Set([...W,...ye]);return Array.from($e)}},Ae={cardStore:$(),cardRuntimeStore:le,fetchedSourcesStore:xe,outputStore:k(),executionRequestStore:g},Ue=w(),Ve=vt(Ue.graph),{events:We,newCursor:Ye}=O().readEntriesAfterCursor(Ue.lastDrainedJournalId),Ke=[],st=[],et=[],at=new Map,yt=new Set,it=(D,W)=>{Ke.push({type:"task-completed",taskName:D,data:W,timestamp:Oe()});try{v().stream("exec-history").append({taskName:D,status:"completed",completedAt:Oe()});}catch{}},dt=(D,W)=>{x({type:"task-failed",taskName:D,error:W,timestamp:Oe()});try{v().stream("exec-history").append({taskName:D,status:"failed",error:W,completedAt:Oe()});}catch{}},te=fr(Ve,{handlers:{"card-handler":Tr(e,Ye,Ae,it,dt,(D,W)=>{st.push({cardId:D,values:W});},D=>{et.push(D);})},onNodeRemoved:D=>{at.delete(D),oe.delete(D),yt.add(D);}});for(Ke=We;Ke.length>0;){let D=Ke;Ke=[];for(let W of D)if(W.type==="task-restart"){let ye=Ae.cardStore.readCard(W.taskName);ye&&at.set(W.taskName,ye);}te.pushAll(D),await te.waitForHandlers();}let ct=te.getState();await te.dispose({wait:true});let Ct=m().readSnapshot(e.value).version;N({lastDrainedJournalId:Ye,graph:ft(ct)},Ct);for(let{cardId:D,values:W}of st)Ae.outputStore.writeComputedValues(D,W);for(let D of et)Ae.outputStore.writeDataObjects(D);for(let[D,W]of oe)P.writeRuntime(D,W);for(let{cardId:D,outputFile:W,deliveryToken:ye}of ve)G.commitSourceData(D,W,ye);let nt;try{nt=_t(s,ct),Ae.outputStore.writeStatusSnapshot(nt);}catch(D){r(`[board-live-cards-public] status publish failed: ${D instanceof Error?D.message:String(D)}`);}let He=[];for(let{cardId:D,values:W}of st)He.push({kind:"computed_values",cardId:D,values:W});for(let D of et)for(let[W,ye]of Object.entries(D))W&&He.push({kind:"data_object",key:W,payload:ye});for(let[D,W]of at)He.push({kind:"card_refreshed",cardId:D,card:W});for(let D of yt)He.push({kind:"card_removed",cardId:D});nt!==void 0&&He.push({kind:"status",status:nt}),a(He);let Pe=u().readTaskExecutorRef()??{howToRun:"built-in",whatToRun:Fe({kind:"built-in",value:"source-cli-task-executor"})};g.dispatchEntriesForJournalId(Ye,D=>{if(D.taskKind!=="source-fetch"){r(`[process-accumulated-events] unknown taskKind "${D.taskKind}" \u2014 skipping`);return}let W=D.payload,ye=W.enrichedCard?.id??"unknown",$e=W.enrichedCard?.source_defs??[];for(let Be of $e){if(!Be.outputFile){r(`[dispatch] source "${Be.bindTo}" has no outputFile \u2014 skipping`);continue}let Xe=qn({cbk:W.callbackToken,rg:e.value,br:Fe(e),cid:ye,b:Be.bindTo,d:Be.outputFile,cs:void 0,rqt:W.rqt});t.dispatchExecution(Pe,{source_def:Be,base_ref:Fe(e),callback:{token:Xe,via:t.selfRef}}).catch(De=>dt(ye,De instanceof Error?De.message:String(De)));}});}async function H(){try{let E=()=>{let P=w(),{events:G}=O().readEntriesAfterCursor(P.lastDrainedJournalId);G.length<=0||(H(),t.requestProcessAccumulated?.());},g=await Zt(t.lock,L,E);return ae({ran:g!==!1})}catch(E){return de(E)}}function I(){H(),t.requestProcessAccumulated?.();}function M(E){try{let g=E.params?.cardStoreRef;if(!g)return z("init requires params.cardStoreRef \u2014 create a card store with card-store-cli and pass its ref here");if(!T()){let Ae=wt(Mt);N({lastDrainedJournalId:"",graph:ft(Ae)},null);}let P=E.params?.outputsStoreRef;if(!P)return z("init requires params.outputsStoreRef \u2014 pass the outputs store ref here");let G=E.params?.scratchStoreRef,oe=E.params?.archiveStoreRef,le=E.params?.chatStoreRef,ve=E.params?.artifactsStoreRef,he=u();he.writeCardStoreRef(g),he.writeOutputsStoreRef(P),G&&he.writeScratchStoreRef(G),oe&&he.writeArchiveStoreRef(oe),le&&he.writeChatStoreRef(le),ve&&he.writeArtifactsStoreRef(ve);let xe=E.body??{};xe["task-executor-ref"]&&he.writeTaskExecutorRef(xe["task-executor-ref"]),Object.prototype.hasOwnProperty.call(xe,"chat-handler-flow")&&he.writeChatHandlerFlow(xe["chat-handler-flow"]);try{k().writeStatusSnapshot(_t(s,vt(w().graph)));}catch{}return ae()}catch(g){return de(g)}}function R(E){try{let g=k().readStatusSnapshot();if(!g){g=_t(s,vt(w().graph));try{k().writeStatusSnapshot(g);}catch{}}return ae(g)}catch(g){return de(g)}}function C(E){try{let g=E.params?.id;return g?(x({type:"task-removal",taskName:g,timestamp:Oe()}),I(),ae()):z("removeCard requires params.id")}catch(g){return de(g)}}function y(E){try{let g=E.params?.cardId;if(!g)return z("addCardFiles requires params.cardId");let P=Tt($()).appendFiles({params:{id:g},body:E.body});if(P.status!=="success")return P;let G=l({params:{cardId:g}});return G.status!=="success"?G:ae({cardId:g,files_added:P.data.files_added,notified:!0})}catch(g){return de(g)}}function l(E){try{let g=E.params?.cardId;if(!g)return z("cardRefreshedNotify requires params.cardId");let P=$().readCard(g);return P?(a([{kind:"card_refreshed",cardId:g,card:P}]),ae({cardId:g,notified:!0})):z(`Card "${g}" not found in board at ${e.value}`)}catch(g){return de(g)}}function p(E){try{let g=E.params?.id;return g?(x({type:"task-restart",taskName:g,timestamp:Oe()}),I(),ae()):z("retrigger requires params.id")}catch(g){return de(g)}}async function S(E){return H()}function A(E){try{let g=E.params?.cardId,P=E.params?.all,G=!!E.params?.restart;if(!g&&!P)return z("upsertCard requires --card-id <id> or --all");let oe=P?$().readAllCards().map(le=>le.id):[g];for(let le of oe)if(!$().readCard(le))return z(`Card "${le}" not found in board at ${e.value}`);for(let le of oe){let ve=$().readCard(le),he=jr(ve),xe=t.hashFn(he),Ae=t.kvStorage("card-upsert"),Ue=Ae.read(le),Ve=Ue?.taskConfigHash!==xe;if(!(!Ve&&!G)){if(Ve){let We=Ue?.blobRef??$().readCardKey(le)??le;x({type:"task-upsert",taskName:le,taskConfig:he,timestamp:Oe()}),Ae.write(le,{blobRef:We,taskConfigHash:xe,updatedAt:Oe()});}G&&x({type:"task-restart",taskName:le,timestamp:Oe()});}}return I(),ae()}catch(g){return de(g)}}function _(E){try{let g=E.params?.token;if(!g)return z("taskFailed requires params.token");let P=E.params?.error??"unknown error",G=Et(g);if(!G)return z("Invalid callback token");x({type:"task-failed",taskName:G.taskName,error:P,timestamp:Oe()});try{v().stream("exec-history").append({taskName:G.taskName,status:"failed",error:P,completedAt:Oe()});}catch{}return I(),ae()}catch(g){return de(g)}}function j(E){try{let g=E.params?.token;if(!g)return z("taskProgress requires params.token");let G=(E.body??{}).update??{},oe=Et(g);return oe?(x({type:"task-progress",taskName:oe.taskName,update:G,timestamp:Oe()}),I(),ae()):z("Invalid callback token")}catch(g){return de(g)}}function Y(E){try{let g=E.params?.token,P=E.params?.ref;if(!g)return z("sourceDataFetched requires params.token");if(!P)return z("sourceDataFetched requires params.ref");let G=Br(g);if(!G)return z("Invalid source token");let{cbk:oe,cid:le,b:ve,d:he,cs:xe,rqt:Ae}=G,Ue=At(t.blobStorage("sources"),Ke=>t.resolveBlob(Ke)),Ve=t.genId();Ue.ingestSourceDataStaged(le,he,ot(P),Ve);let We=Et(oe);if(!We)return z("Invalid callback token embedded in source token");let Ye=Oe();return x({type:"task-progress",taskName:We.taskName,update:{bindTo:ve,outputFile:he,fetchedAt:Ye,deliveryToken:Ve,sourceChecksum:xe,rqt:Ae},timestamp:Ye}),I(),ae()}catch(g){return de(g)}}function re(E){try{let g=E.params?.token,P=E.params?.reason??"unknown";if(!g)return z("sourceDataFetchFailure requires params.token");let G=Br(g);if(!G)return z("Invalid source token");let{cbk:oe,b:le,d:ve,cs:he,rqt:xe}=G,Ae=Et(oe);return Ae?(x({type:"task-progress",taskName:Ae.taskName,update:{bindTo:le,outputFile:ve,failure:!0,reason:P,sourceChecksum:he,rqt:xe},timestamp:Oe()}),I(),ae()):z("Invalid callback token embedded in source token")}catch(g){return de(g)}}function ne(E){try{let g=u().readCardStoreRef();return g?ae({storeRef:g}):z(`Board at ${e.value} has no card store configured`)}catch(g){return de(g)}}function se(E){try{let g=u().readOutputsStoreRef();return g?ae({storeRef:g}):z(`Board at ${e.value} has no outputs store configured`)}catch(g){return de(g)}}function B(E){try{let g=u().readScratchStoreRef();return ae({storeRef:g})}catch(g){return de(g)}}function q(E){try{let g=u().readArchiveStoreRef();return ae({storeRef:g})}catch(g){return de(g)}}function Q(E){try{let g=u().readChatStoreRef();return ae({storeRef:g})}catch(g){return de(g)}}function ie(E){try{let g=u().readArtifactsStoreRef();return ae({storeRef:g})}catch(g){return de(g)}}function ee(E){try{let g=E.params?.key;if(!g)return z("getConfig requires params.key");let P=u(),G;switch(g){case "task-executor":G=P.readTaskExecutorRef()??null;break;case "chat-handler-flow":G=P.readChatHandlerFlow()??null;break;case "card-store-ref":G=P.readCardStoreRef();break;case "outputs-store-ref":G=P.readOutputsStoreRef();break;case "scratch-store-ref":G=P.readScratchStoreRef();break;case "archive-store-ref":G=P.readArchiveStoreRef();break;case "chat-store-ref":G=P.readChatStoreRef();break;case "artifacts-store-ref":G=P.readArtifactsStoreRef();break;default:return z(`getConfig: unknown key "${g}"`)}return ae({value:G})}catch(g){return de(g)}}function _e(E){try{let g=E.params?.key;if(!g)return z("getOutputsDataObject requires params.key");let P=k().readDataObject(g);return ae(P)}catch(g){return de(g)}}function X(E){try{return ae(k().readAllDataObjects())}catch(g){return de(g)}}function ke(E){try{let g=E.params?.key;if(!g)return z("getOutputsComputedValues requires params.key");let P=k().readComputedValues(g);return ae(P)}catch(g){return de(g)}}function we(E){try{return ae(k().readAllComputedValues())}catch(g){return de(g)}}function me(){return At(t.blobStorage("sources"),E=>t.resolveBlob(E))}function be(E){let g=t.blobStorage("sources").keyRef?.(E);return g?Fe(g):E}function Ne(E){try{let g=E.params?.key;if(!g)return z("getOutputsFetchedSources requires params.key");let P=me().listSources(g),G={};for(let oe of P)G[oe]=be(`${g}/${oe}`);return ae(G)}catch(g){return de(g)}}function je(E){try{let g=me(),P=new Set;for(let oe of t.blobStorage("sources").listKeys()){let le=oe.indexOf("/");le>0&&!oe.includes("/.staged/")&&P.add(oe.slice(0,le));}let G={};for(let oe of P){let le=g.listSources(oe);if(le.length>0){G[oe]={};for(let ve of le)G[oe][ve]=be(`${oe}/${ve}`);}}return ae(G)}catch(g){return de(g)}}return {init:M,status:R,getCardStoreRef:ne,getOutputsStoreRef:se,getScratchStoreRef:B,getArchiveStoreRef:q,getChatStoreRef:Q,getArtifactsStoreRef:ie,getConfig:ee,getOutputsDataObject:_e,getAllOutputsDataObjects:X,getOutputsComputedValues:ke,getAllOutputsComputedValues:we,getOutputsFetchedSources:Ne,getAllOutputsFetchedSources:je,removeCard:C,addCardFiles:y,cardRefreshedNotify:l,retrigger:p,processAccumulatedEvents:S,upsertCard:A,taskFailed:_,taskProgress:j,sourceDataFetched:Y,sourceDataFetchFailure:re}}function Nr(e,t){let r=()=>Lt(t.kvStorage("config"));function s(){let R=r().readCardStoreRef();if(!R)throw new Error(`Board at ${e.value} has no card store configured. Run: init --base-ref <ref> --store-ref <b64-ref>`);let C=t.kvStorageForRef(R);return {readIndex(){return C.read("_index")},writeIndex(y){C.write("_index",y);},readCard(y){return C.read(y)},writeCard(y,l){return C.write(y,l),t.hashFn(l)},removeCard(y){C.delete(y);},cardExists(y){return C.read(y)!==null},defaultCardKey(y){return y}}}let a=()=>mt(s(),t.onWarn??(()=>{})),i=()=>{let R=r().readScratchStoreRef();return R?t.scratchStorageForRef(R):t.scratchStorage()};function c(R,C){let y=t.validateSchema(C),l=[],p=r().readTaskExecutorRef();if(p&&Array.isArray(C.source_defs))for(let A of C.source_defs){let _=typeof A.bindTo=="string"?A.bindTo:"(unknown)";try{let j;try{j=t.invokeExecutorSync(p,"validate-source-def",[],{timeout:t.executorTimeouts?.validationMs??1e4,input:JSON.stringify(A)});}catch(re){let ne=re;if(j=typeof ne?.stdout=="string"?ne.stdout:"",!j.trim()){l.push(`source "${_}": executor validate-source-def failed \u2014 ${re instanceof Error?re.message:String(re)}`);continue}}let Y=JSON.parse(j.trim());if(!Y.ok&&Array.isArray(Y.errors))for(let re of Y.errors)l.push(`source "${_}": ${re}`);}catch(j){l.push(`source "${_}": executor validate-source-def failed \u2014 ${j instanceof Error?j.message:String(j)}`);}}let S=[...y.errors,...l];return ae({cardId:R,isValid:S.length===0,issues:S})}function u(R,C){let y=r().readTaskExecutorRef();if(!y)throw new Error("No task-executor registered for this board");let l=typeof R.bindTo=="string"?R.bindTo:"source",p=i(),S={...R,boardDir:e.value,_projections:C},A=p.create(JSON.stringify(S,null,2),`probe-in-${l}`,".json"),_=p.getUniqueKey(`probe-out-${l}`,".json"),j=p.getUniqueKey(`probe-err-${l}`,".txt"),Y=Fe(p.keyRef(A)),re=Fe(p.keyRef(_)),ne=Fe(p.keyRef(j)),se=null;try{if(t.invokeExecutorSync(y,"run-source-fetch",["--in-ref",Y,"--out-ref",re,"--err-ref",ne],{timeout:R.timeout??t.executorTimeouts?.probeMs??6e4}),se=p.read(_),se===null)throw new Error("Executor produced no output file")}catch(B){let q=p.read(j)?.trim()??(B instanceof Error?B.message:String(B));throw new Error(`Probe failed: ${q}`)}finally{try{p.remove(A);}catch{}try{p.remove(j);}catch{}}return {bindTo:l,result:se}}function m(R,C,y){let l;try{l=u(R,C);}catch(p){return z(p instanceof Error?p.message:String(p))}if(y){let p=ot(y);t.absoluteBlob.write(p.value,l.result);}return ae({bindTo:l.bindTo,resultSizeBytes:l.result.length})}function O(R,C){let y=R.params?.sourceIdx,l=R.params?.outRef;if(y===void 0)return z(`${C} requires params.sourceIdx`);if(!R.body||typeof R.body!="object"||Array.isArray(R.body))return z(`${C} requires card JSON object in body`);let p=R.body,S=p["card-content"]??p,A=p["mock-projections"]??{},_=S.source_defs??[];if(y<0||y>=_.length)return z(`sourceIdx ${y} out of range (card has ${_.length} source(s))`);let j=_[y],Y=typeof j.bindTo=="string"?j.bindTo:"source";return {src:j,bindTo:Y,outRef:l,mockProjections:A}}function $(R){try{let C=R.params?.cardId,y=R.params?.all;if(!C&&!y)return z("validateCard requires --card-id <id> or --all");let l=y?a().readAllCards().map(S=>S.id):[C],p=[];for(let S of l){let A=a().readCard(S);if(!A){p.push({cardId:S,isValid:!1,issues:[`Card "${S}" not found`]});continue}let _=c(S,A);if(_.status!=="success")return _;p.push(_.data);}return ae(p)}catch(C){return de(C)}}function k(R){try{if(!R.body||typeof R.body!="object"||Array.isArray(R.body))return z("validateCardPreflight requires card JSON object in body");let C=R.body,y=C["card-content"]??C,l=typeof y.id=="string"?y.id:"(unknown)";return c(l,y)}catch(C){return de(C)}}function v(R){try{let C=R.params?.cardId,y=R.params?.sourceIdx,l=R.params?.outRef;if(!C)return z("probeSource requires params.cardId");if(y===void 0)return z("probeSource requires params.sourceIdx");let S=(R.body??{})["mock-projections"]??{},A=a().readCard(C);if(!A)return z(`Card "${C}" not found`);let _=A.source_defs??[];return y<0||y>=_.length?z(`sourceIdx ${y} out of range (card has ${_.length} source(s))`):m(_[y],S,l)}catch(C){return de(C)}}function T(R){try{let C=R.params?.outRef,y=R.body;if(!y)return z('probeTmpSource requires body with "source-def" and "mock-projections"');let l=y["source-def"],p=y["mock-projections"]??{};return l?m(l,p,C):z('probeTmpSource body requires "source-def"')}catch(C){return de(C)}}function w(R){try{let C=O(R,"probeSourcePreflight");if("status"in C)return C;let y=r().readTaskExecutorRef();if(!y)return z("No task-executor registered for this board");try{let l={...C.src,_projections:C.mockProjections},p=t.invokeExecutorSync(y,"probe-source-preflight",[],{timeout:C.src.timeout??t.executorTimeouts?.preflightMs??6e4,input:JSON.stringify(l)}),S=JSON.parse(p.trim());return S.ok?ae({bindTo:C.bindTo,reachable:S.reachable,latencyMs:S.latencyMs,note:S.note}):z(S.error??"Preflight probe failed")}catch{return z("Executor does not support probe-source-preflight")}}catch(C){return de(C)}}function N(R){try{let C=O(R,"runSourcePreflight");if("status"in C)return C;try{let y=u(C.src,C.mockProjections);if(C.outRef){let p=ot(C.outRef);t.absoluteBlob.write(p.value,y.result);}let l=y.result;try{l=JSON.parse(y.result);}catch{}return ae({bindTo:y.bindTo,ok:!0,result:l,issues:[]})}catch(y){let l=y instanceof Error?y.message:String(y);return l==="No task-executor registered for this board"?z(l):ae({bindTo:C.bindTo,ok:!1,result:null,issues:[l]})}}catch(C){return de(C)}}function x(R){try{let C=r().readTaskExecutorRef();if(!C)return z("No task-executor registered for this board");let y=t.invokeExecutorSync(C,"describe-capabilities",[],{timeout:t.executorTimeouts?.describeMs??1e4});return ae(JSON.parse(y.trim()))}catch(C){return de(C)}}function L(R){try{let C=R.body;if(!C||!Array.isArray(C.ops))return z("updatesInCardStore requires body.ops array");let y=C.ops,l=a();for(let p of y){let S=p.op,A=p.id;if(!A)return z('op is missing "id"');if(S==="update"){let _=p["card-content"];if(!_)return z(`update op for "${A}" is missing "card-content"`);l.writeCard(A,_);}else return z(`Unknown op type: "${S??"(none)"}"`)}return ae()}catch(C){return de(C)}}function H(R){try{let C=R.body;if(!C||!Array.isArray(C.ids))return z("readFromCardStore requires body.ids array");let y=C.ids,l=a(),p=y.map(S=>({id:S,"card-content":l.readCard(S)}));return ae({cards:p})}catch(C){return de(C)}}function I(R){try{if(!R.body||typeof R.body!="object"||Array.isArray(R.body))return z("evalCardCompute requires a JSON object in body");let C=R.body,y=C["card-content"]??C,l=typeof y.id=="string"?y.id:"(unknown)",p=C["mock-fetched-sources"]??{},S=C["mock-requires"]??{},A=y.compute;if(!A||!Array.isArray(A)||A.length===0)return ae({cardId:l,ok:!0,computed_values:{},errors:[]});let _={id:l,card_data:y.card_data??{},requires:S,source_defs:y.source_defs,compute:A},j=Ge.runSync(_,{sourcesData:p}),Y=j.node.computed_values??{},re=j.errors??[];return ae({cardId:l,ok:re.length===0,computed_values:Y,errors:re})}catch(C){return de(C)}}function M(R){try{if(!R.body||typeof R.body!="object"||Array.isArray(R.body))return z("simulateCardCycle requires a JSON object in body");let C=R.body,y=C["card-content"]??C,l=typeof y.id=="string"?y.id:"(unknown)",p=C["mock-fetched-sources"]??{},S=C["mock-requires"]??{},A=c(l,y),_=A.status==="success"?{isValid:A.data.isValid,issues:A.data.issues}:{isValid:!1,issues:[A.status==="fail"?A.error:"internal error"]},j=y.source_defs??[],Y=y.card_data??{},re=[],ne=[];if(j.length>0){re=Ge.enrichSourcesSync(j,{card_data:Y,requires:S});for(let X of re){let ke=X.projections,we=X._projections;if(ke&&we){for(let me of Object.keys(ke))if(we[me]===void 0){let be=typeof X.bindTo=="string"?X.bindTo:"(unknown)";ne.push({bindTo:be,key:me,error:`Projection "${me}" resolved to undefined`});}}}}let se=[],B=C["task-executor-ref"],q=(B?.howToRun&&B?.whatToRun?B:void 0)??r().readTaskExecutorRef();for(let X=0;X<re.length;X++){let ke=re[X],we=typeof ke.bindTo=="string"?ke.bindTo:`source_${X}`;if(!q){se.push({bindTo:we,skipped:!0,error:"No task executor configured"});continue}try{let me={...ke},be=t.invokeExecutorSync(q,"run-source-preflight",[],{timeout:ke.timeout??t.executorTimeouts?.preflightMs??6e4,input:JSON.stringify(me)}),Ne=JSON.parse(be.trim());se.push({bindTo:we,reachable:Ne.reachable,latencyMs:Ne.latencyMs,error:Ne.ok?void 0:Ne.error});}catch{se.push({bindTo:we,skipped:!0,error:"Executor does not support run-source-preflight"});}}let Q=y.compute,ie={},ee=[];if(Q&&Array.isArray(Q)&&Q.length>0){let X={id:l,card_data:Y,requires:S,source_defs:y.source_defs,compute:Q},ke=Ge.runSync(X,{sourcesData:p});ie=ke.node.computed_values??{},ee=ke.errors??[];}let _e=_.isValid&&ne.length===0&&ee.length===0&&se.every(X=>X.reachable!==!1);return ae({cardId:l,ok:_e,validation:_,source_probes:se,projection_errors:ne,computed_values:ie,compute_errors:ee})}catch(C){return de(C)}}return {validateCard:$,validateCardPreflight:k,probeSource:v,probeTmpSource:T,probeSourcePreflight:w,runSourcePreflight:N,evalCardCompute:I,simulateCardCycle:M,describeTaskExecutorCapabilities:x,updatesInCardStore:L,readFromCardStore:H}}function Ie(e,t){if(e?.status==="success")return Object.prototype.hasOwnProperty.call(e,"data")?e.data:void 0;throw e?.status==="fail"||e?.status==="error"?new Error(e.error||`${t} failed`):new Error(`${t} returned an unexpected response`)}function Nn(e,t){if(e?.status==="success"&&Object.prototype.hasOwnProperty.call(e,"data"))return e.data;throw e?.status==="success"?new Error(`${t} returned success without data`):e?.status==="fail"||e?.status==="error"?new Error(e.error||`${t} failed`):new Error(`${t} returned an unexpected response`)}function Z(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Re(e){return Array.isArray(e)?e:[]}function Gt(e,t){if(typeof t!="string"||t.length===0)return;let r=e,s=t;s.startsWith("fetched_sources.")&&(r=Z(e).fetched_sources,s=s.slice(16));for(let a of s.split(".")){if(r==null||typeof r!="object")return;r=r[a];}return r}function Ut(e,t){let r=Z(e.view),s=Re(r.elements);return {layout:r.layout,features:r.features,elements:s.map((a,i)=>{let c=Z(a),u=Z(c.data),m=typeof c.visible=="string"?!!Gt(t,c.visible):true,O=typeof u.bind=="string"?u.bind:void 0,$=O?Gt(t,O):void 0,k={id:typeof c.id=="string"&&c.id?c.id:`element-${i}`,kind:c.kind,label:c.label,visible:m};return O&&(k.bind=O),Array.isArray(u.columns)&&(k.columns=u.columns),typeof u.maxRows=="number"&&(k.maxRows=u.maxRows),$!==void 0&&(k.resolved=Array.isArray($)&&typeof k.maxRows=="number"?$.slice(0,k.maxRows):$),k})}}function Pr(e,t){let r=typeof e.id=="string"&&e.id?e.id:"card",s=Re(e.provides),a=s.length>0?s:[{bindTo:r,ref:"card_data"}],i={};for(let c of a){let u=Z(c),m=typeof u.bindTo=="string"?u.bindTo:"",O=typeof u.ref=="string"?u.ref:"";if(!m||!O)continue;let $=Gt(t,O);$!==void 0&&(i[m]=$);}return i}function Pn(e){if(typeof e!="string"||!e.trim())return null;let t=/^(file uploaded|AI generated|AI geneterated):\s*.*?#(\d+)\s*$/i.exec(e.trim());if(!t)return null;let r=Number.parseInt(t[2],10);return !Number.isInteger(r)||r<0?null:r}function $n(e){return {"card-content":e}}function ht(e,t){let r=Ie(e.get({params:{id:t}}),"cardStore.get"),s=Array.isArray(r?.cards)?r.cards:[];if(s.length===0)throw new Error(`Card "${t}" not found`);return s[0]}function $r(e){let{board:t,nonCore:r,cardStore:s,chatStore:a,uploadCardFile:i,buildFileDownloadUrl:c,readFetchedSourceJsonByRef:u}=e;function m(l){if(Array.isArray(l.bytes))return new Uint8Array(l.bytes.map(p=>Math.max(0,Math.min(255,Number(p)||0))));if(typeof l.text=="string")return new TextEncoder().encode(l.text);if(typeof l.base64=="string"){let p=String(l.base64).replace(/-/g,"+").replace(/_/g,"/"),S=p+"=".repeat((4-p.length%4)%4),A=atob(S);return Uint8Array.from(A,_=>_.charCodeAt(0))}throw new Error("file entry requires bytes, text, or base64")}function O(){let l=Z(Ie(r.describeTaskExecutorCapabilities({}),"describeTaskExecutorCapabilities"));return {version:l.version,commonSourceFields:Z(l.commonSourceDefFields),sourceKinds:Z(l.sourceKinds)}}function $(){let l=Z(Ie(t.status({}),"status")),p=Z(l.summary),S=Re(l.cards);return {meta:Z(l.meta),summary:{card_count:typeof p.card_count=="number"?p.card_count:0,completed:typeof p.completed=="number"?p.completed:0,eligible:typeof p.eligible=="number"?p.eligible:0,pending:typeof p.pending=="number"?p.pending:0,blocked:typeof p.blocked=="number"?p.blocked:0,in_progress:typeof p.in_progress=="number"?p.in_progress:0,failed:typeof p.failed=="number"?p.failed:0,unresolved:typeof p.unresolved=="number"?p.unresolved:0},cards:S.map(A=>{let _=Z(A);return {"card-id":typeof _.name=="string"?_.name:null,status:_.status??null,error:_.error??null,requires:Re(_.requires),requires_satisfied:Re(_.requires_satisfied),requires_missing:Re(_.requires_missing),provides_declared:Re(_.provides_declared),provides_runtime:Re(_.provides_runtime)}})}}function k(l){let p=String(l.cardId||"").trim();if(!p)throw new Error("inspectCardDefinitionAndRuntime requires cardId");let S=Z(Ie(t.status({}),"status")),_=Re(S.cards).map(Z).find(X=>X.name===p);if(!_)throw new Error(`card "${p}" not found in board status`);let j=Z(ht(s,p)),Y=Re(_.requires_satisfied).filter(X=>typeof X=="string"&&!!X),re=Re(_.provides_runtime).filter(X=>typeof X=="string"&&!!X),ne=Object.fromEntries(Y.map(X=>[X,Ie(t.getOutputsDataObject({params:{key:X}}),`getOutputsDataObject(${X})`)])),se=Object.fromEntries(re.map(X=>[X,Ie(t.getOutputsDataObject({params:{key:X}}),`getOutputsDataObject(${X})`)])),B=Z(Ie(t.getOutputsComputedValues({params:{key:p}}),"getOutputsComputedValues")),q=Ie(t.getOutputsFetchedSources({params:{key:p}}),"getOutputsFetchedSources"),Q=Re(j.source_defs).map(Z),ie={};for(let X of Q)typeof X.bindTo=="string"&&typeof X.outputFile=="string"&&(ie[X.outputFile]=X.bindTo);let ee={};for(let[X,ke]of Object.entries(q)){let we=ie[X]??X;if(!u||typeof ke!="string"){ee[we]=null;continue}try{ee[we]=u({cardId:p,ref:ke});}catch{ee[we]=null;}}let _e={card_data:Z(j.card_data),requires:ne,fetched_sources:ee,computed_values:B};return {cardId:p,card_status_in_board:_,card_definition_and_static_data:j,refs_for_fetched_source_files:q,runtime_data:{requires:ne,provides:se,computed_values:B,rendered_view:Ut(j,_e)}}}function v(l){let p=String(l.cardId||"").trim();if(!p)throw new Error("inspectChatMessagesOnCards requires cardId");let S=typeof l.turnId=="string"?l.turnId:"",A=l.allTurns===true,_=typeof l.tailTurnsBeforeId=="string"?l.tailTurnsBeforeId:"",j=A?void 0:l.lastUserTurns??(S?void 0:1),Y=l.tail,re={...j===void 0?{}:{tailTurns:j},...S?{turnId:S}:{},...A?{allTurns:true}:{},..._?{tailTurnsBeforeId:_}:{}},ne=Object.keys(re).length>0?{params:{cardId:p},body:re}:{params:{cardId:p}},se=Ie(a.readAll(ne),"chatStore.readAll"),B=Z(ht(s,p)),q=Re(Z(B.card_data).files).map((ee,_e)=>({idx:_e,stored_name:Z(ee).stored_name})).filter(ee=>typeof ee.stored_name=="string"&&ee.stored_name.length>0),ie=(Array.isArray(se.records)?se.records:[]).map(ee=>{let X=Z(ee.payload),ke={...ee},we=typeof ee?.role=="string"?ee.role:typeof X.role=="string"?String(X.role):"",me=typeof ee?.text=="string"?ee.text:typeof X.text=="string"?String(X.text):"";if(we==="system"){let be=Pn(me);if(be!==null&&q.some(je=>je.idx===be)){let je=`Retrieve using inspect-file-contents --card-id ${p} --file-idx ${be}`;ke.retrieval_hint=je,Object.keys(X).length>0&&typeof ee.role!="string"&&(ke.payload={...X,retrieval_hint:je});}}return ke});return {cardId:p,messages:typeof Y=="number"&&Y>=0?ie.slice(-Y):ie}}function T(l){let p=String(l.cardId||"").trim(),S=Number(l.fileIdx);if(!p)throw new Error("inspectFileContents requires cardId");if(!Number.isInteger(S)||S<0)throw new Error("inspectFileContents requires fileIdx to be a non-negative integer");let A=Z(ht(s,p)),_=Re(Z(A.card_data).files).map(Z);if(S>=_.length)throw new Error(`attachment index ${S} is out of range for card "${p}"`);let j=_[S],Y=typeof j.stored_name=="string"?j.stored_name:null;return {cardId:p,fileIdx:S,downloadUrl:c({cardId:p,fileIdx:S,storedName:Y}),...typeof j.name=="string"?{name:j.name}:{},...typeof j.stored_name=="string"?{stored_name:j.stored_name}:{},...typeof j.mime_type=="string"?{mime_type:j.mime_type}:{},...typeof j.size=="number"?{size:j.size}:{},...typeof j.uploaded_at=="string"?{uploaded_at:j.uploaded_at}:{}}}function w(l){return r.validateCardPreflight({body:$n(l.candidateCardContent)})}function N(l){if(!l.mockRequires||typeof l.mockRequires!="object"||Array.isArray(l.mockRequires))throw new Error("preflightMaterializeCandidateCard requires mockRequires");if(!l.mockFetchedSources||typeof l.mockFetchedSources!="object"||Array.isArray(l.mockFetchedSources))throw new Error("preflightMaterializeCandidateCard requires mockFetchedSources");let p=r.evalCardCompute({body:{"card-content":l.candidateCardContent,"mock-requires":l.mockRequires,"mock-fetched-sources":l.mockFetchedSources}});if(p.status!=="success")return p;let S=Z(Nn(p,"evalCardCompute")),A=Z(l.candidateCardContent),_={card_data:Z(A.card_data),requires:Z(l.mockRequires),fetched_sources:Z(l.mockFetchedSources),computed_values:Z(S.computed_values)};return {status:"success",data:{cardId:typeof S.cardId=="string"?S.cardId:typeof A.id=="string"?A.id:"(unknown)",ok:S.ok===true,computed_values:Z(S.computed_values),errors:Re(S.errors).map(j=>{let Y=Z(j);return {bindTo:typeof Y.bindTo=="string"?Y.bindTo:"",error:typeof Y.error=="string"?Y.error:""}}),provides_outputs:Pr(A,_),rendered_view:Ut(A,_)}}}function x(l){return r.probeSourcePreflight({params:{sourceIdx:l.sourceIdx},body:{"card-content":l.candidateCardContent,"mock-projections":l.mockProjections}})}function L(l){return r.runSourcePreflight({params:{sourceIdx:l.sourceIdx},body:{"card-content":l.candidateCardContent,"mock-projections":l.mockProjections}})}function H(l){let p=String(l.cardId||"").trim();if(!p)throw new Error("preflightRunSingleSourceInLiveCard requires cardId");if(!l.mockRequires||typeof l.mockRequires!="object"||Array.isArray(l.mockRequires))throw new Error("preflightRunSingleSourceInLiveCard requires mockRequires");let S=Z(ht(s,p)),A=Re(S.source_defs).filter(j=>!!j&&typeof j=="object"&&!Array.isArray(j)),_={};if(l.sourceIdx>=0&&l.sourceIdx<A.length){let j=A[l.sourceIdx],Y=Ge.enrichSourcesSync([j],{card_data:Z(S.card_data),requires:l.mockRequires});Array.isArray(Y)&&Y.length>0&&(_=Z(Y[0]._projections));}return r.runSourcePreflight({params:{sourceIdx:l.sourceIdx},body:{"card-content":S,"mock-requires":l.mockRequires,"mock-projections":_}})}function I(l){let p=Z(Ie(r.simulateCardCycle({body:{"card-content":l.candidateCardContent,"mock-requires":l.mockRequires}}),"simulateCardCycle")),S=Z(l.candidateCardContent),A=Z(p.validation),_=Re(p.source_probes),j=Re(p.projection_errors),Y=Re(p.compute_errors),re=Z(p.computed_values),ne={card_data:Z(S.card_data),requires:l.mockRequires,fetched_sources:{},computed_values:re},se=[];for(let B of Re(A.issues))typeof B=="string"&&B&&se.push(B);for(let B of _){let q=Z(B),Q=typeof q.bindTo=="string"?q.bindTo:"source",ie=typeof q.error=="string"?q.error:"";ie&&se.push(`${Q}: ${ie}`);}for(let B of j){let q=Z(B),Q=typeof q.bindTo=="string"?q.bindTo:"source",ie=typeof q.key=="string"?q.key:"projection",ee=typeof q.error=="string"?q.error:"projection failed";se.push(`${Q}.${ie}: ${ee}`);}for(let B of Y){let q=Z(B),Q=typeof q.bindTo=="string"?q.bindTo:"compute",ie=typeof q.error=="string"?q.error:"compute failed";se.push(`${Q}: ${ie}`);}return {status:"success",data:{cardId:typeof p.cardId=="string"?p.cardId:"(unknown)",ok:p.ok===true,issues:se,provides_outputs:Pr(S,ne),rendered_view:Ut(S,ne)}}}function M(l){let p=String(l.cardId||"").trim();if(!p)throw new Error("manageReadCard requires cardId");let S=Ie(s.get({params:{id:p}}),"cardStore.get");return Array.isArray(S.cards)?S.cards:[]}function R(l){let p=String(l.cardId||"").trim(),S=String(l.role||"").trim(),A=typeof l.text=="string"?l.text:"",_=typeof l.turn=="string"?l.turn:"";if(!p)throw new Error("manageAddChatEntryAndAnyAttachments requires cardId");if(!S)throw new Error("manageAddChatEntryAndAnyAttachments requires role");let j=Re(l.files).map(re=>{let ne=Z(re),se=String(ne.file_name??ne.fileName??ne.name??"").trim(),B=String(ne.content_type??ne.contentType??"application/octet-stream");if(!se)throw new Error("file entry requires file_name");return i({cardId:p,fileName:se,contentType:B,bytes:m(ne)}).file});j.forEach((re,ne)=>{let se=S==="assistant"?`AI generated: ${String(re.name||"")} as ${String(re.stored_name||"")} #${ne}`:`file uploaded: ${String(re.name||"")} as ${String(re.stored_name||"")} #${ne}`;Ie(a.append({params:{cardId:p},body:{role:"system",text:se,files:[],turn:_}}),"chatStore.append(system attachment message)");});let Y=Ie(a.append({params:{cardId:p},body:{role:S,text:A,files:j,turn:_}}),"chatStore.append");return {status:"success",data:{cardId:p,id:String(Y.id),role:S,turn:_,files:j}}}function C(l){let p=String(l.cardId||"").trim(),S=Z(l.candidateCardContent);if(!p)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!==p)throw new Error(`candidateCardContent.id must match cardId (${p})`);let A=w({candidateCardContent:S}),_=Z(A),j=Z(_.data);if(_.status!=="success"||j.isValid!==true)return {status:"fail",step:"validate",validation:A};let Y=null;try{Y=ht(s,p);}catch{Y=null;}let re=s.set({body:S});Ie(re,"cardStore.set");let ne;try{ne=t.upsertCard({params:{cardId:p,restart:!0}}),Ie(ne,"upsertCard");}catch(B){try{Y&&s.set({body:Y});}catch{}throw B}let se=null;try{se=t.cardRefreshedNotify({params:{cardId:p}}),Ie(se,"cardRefreshedNotify");}catch{se=null;}return {status:"success",data:{validation:A,card_saved:null,board_result:ne,refresh_notify:se}}}function y(l){let p=String(l.cardId||"").trim();if(!p)throw new Error("manageDeprecate requires cardId");let S=t.removeCard({params:{id:p}});return Ie(S,"removeCard"),S}return {discoverSourceKinds:O,inspectBoardRuntimeStatus:$,inspectCardDefinitionAndRuntime:k,inspectChatMessagesOnCards:v,inspectFileContents:T,preflightValidateCandidateCardDefinition:w,preflightMaterializeCandidateCard:N,preflightProbeSingleSourceInCandidateCard:x,preflightRunSingleSourceInCandidateCard:L,preflightRunSingleSourceInLiveCard:H,preflightRunOneCycleWithCandidateCard:I,manageReadCard:M,manageAddChatEntryAndAnyAttachments:R,manageUpsertCard:C,manageDeprecate:y}}function Dr(){return new Date().toISOString()}function Lr(e){return new TextEncoder().encode(e).byteLength}function Dn(e){return e?{key:e.key,size:e.size,updatedAt:e.updatedAt,contentType:e.contentType}:null}function Ln(e){let t=String(e||"").match(/^(\d+)[-_]/);return t?parseInt(t[1],10):0}function Mn(e){let t=String(e||"").trim();if(!t)return "upload.bin";let r=Math.max(t.lastIndexOf("/"),t.lastIndexOf("\\"));return (r>=0?t.slice(r+1):t)||"upload.bin"}function Un(e){return String(e||"").toLowerCase().replace(/\s+/g,"_").replace(/[^a-z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_+|_+$/g,"")||"file"}function Gn(e){if(!e||e===".")return "";let t=String(e).replace(/^\./,"").toLowerCase().replace(/[^a-z0-9]/g,"");return t?`.${t}`:""}function Vn(e){let t=Mn(e),r=t.lastIndexOf(".");return r<=0||r===t.length-1?{stem:t,ext:""}:{stem:t.slice(0,r),ext:t.slice(r)}}function Kn(e){let t=e.lastIndexOf("/");return t>=0?e.slice(t+1):e}function Mr(e){function t(r){let s=e.stat?Dn(e.stat(r)):null;if(s)return s;if(!e.exists(r))return null;let a=e.read(r);return a===null?{key:r}:{key:r,size:Lr(a)}}return {exists(r){return e.exists(r)},putText(r,s,a="text/plain; charset=utf-8"){e.write(r,s);let i=t(r)??{key:r};return i.contentType=a,i.updatedAt=i.updatedAt??Dr(),i.size=i.size??Lr(s),i},putBytes(r,s,a="application/octet-stream"){if(e.writeBytes)e.writeBytes(r,s);else {let c=JSON.stringify({__kind:"bytes-array",data:[...s]});e.write(r,c);}let i=t(r)??{key:r};return i.contentType=a,i.updatedAt=i.updatedAt??Dr(),i.size=i.size??s.byteLength,i},getText(r){let s=e.read(r);if(s===null){if(!e.readBytes)return null;let a=e.readBytes(r);return a===null?null:Buffer.from(a).toString("utf-8")}try{let a=JSON.parse(s);if(a&&a.__kind==="bytes-array"&&Array.isArray(a.data))return new TextDecoder("utf-8").decode(new Uint8Array(a.data))}catch{}return s},getBytes(r){if(e.readBytes){let a=e.readBytes(r);if(a!==null)return a}let s=e.read(r);if(s===null)return null;try{let a=JSON.parse(s);if(a&&a.__kind==="bytes-array"&&Array.isArray(a.data))return new Uint8Array(a.data)}catch{}return new TextEncoder().encode(s)},head:t,list(r=""){return e.listKeys(r).map(s=>t(s)??{key:s}).sort((s,a)=>s.key.localeCompare(a.key))},remove(r){e.remove(r);}}}function Ur(e){function t(a,i){let c=0,u=[];Array.isArray(i)&&u.push(...i);for(let m of e.list(`${a}/`))u.push(Kn(m.key));for(let m of u){let O=Ln(m);Number.isFinite(O)&&O>c&&(c=O);}return c+1}function r(a,i,c){let u=Number(c?.maxLen||32),{stem:m,ext:O}=Vn(a),$=Gn(O),k=Un(m),v=`${String(i).padStart(3,"0")}-`,T=$,w=u-v.length-T.length;w<1&&(T="",w=u-v.length);let N=k.slice(0,Math.max(1,w)),x=`${v}${N}${T}`;return x.length>u&&(x=x.slice(0,u).replace(/\.$/,"")),x}function s(a,i,c){let u=t(a,c?.seedNames),m=r(i,u,{maxLen:c?.maxLen});for(;e.exists(`${a}/${m}`);)u+=1,m=r(i,u,{maxLen:c?.maxLen});return m}return {nextSerial:t,buildStoredName:r,allocateStoredName:s}}function Gr(){function e(a,i){if(!Array.isArray(a))return [];let c=[];for(let u of a){if(!u||typeof u!="object")continue;let m=u;typeof m.stored_name=="string"&&c.push({name:typeof m.name=="string"?m.name:m.stored_name,stored_name:m.stored_name,size:typeof m.size=="number"&&Number.isFinite(m.size)?m.size:null,mime_type:typeof m.mime_type=="string"?m.mime_type:null,uploaded_at:typeof m.uploaded_at=="string"?m.uploaded_at:i||null,chat:m.chat===true});}return c}function t(a){return !a||typeof a!="object"?[]:e(a.files,void 0)}function r(a,i){let c=t(a);if(i.length===0)return a.files=c,c;let u=new Set(c.map(m=>m.stored_name));for(let m of i)u.has(m.stored_name)||(c.push(m),u.add(m.stored_name));return a.files=c,c}function s(a,i,c){let u=t(a);if(!Number.isInteger(i)||i<0||i>=u.length)return {ok:false,reason:"index_out_of_range"};let m=u[i];return !m||!m.stored_name?{ok:false,reason:"missing_stored_name"}:c&&c!==m.stored_name?{ok:false,reason:"stale_reference"}:{ok:true,file:m}}return {read:t,normalizeIncoming:e,merge:r,resolve:s}}function Hn(){let e=globalThis.crypto;return typeof e?.randomUUID=="function"?String(e.randomUUID()):`id-${Date.now()}-${Math.random().toString(36).slice(2)}`}function Vr(){let e=new Map,t=new Map;function r(s){return e.has(s)||e.set(s,[]),e.get(s)}return {append(s,a,i,c=[],u=""){let m={id:Hn(),role:a,text:i,files:c,turn:u,updated_at:new Date().toISOString()};return r(s).push(m),m.id},readAll(s){return r(s).slice()},readAfter(s,a){let i=r(s);if(!a)return {records:i.slice(),cursor:i.length>0?i[i.length-1].id:null};let c=i.findIndex(m=>m.id===a),u=c===-1?i.slice():i.slice(c+1);return {records:u,cursor:u.length>0?u[u.length-1].id:a}},clear(s){e.set(s,[]);},setProcessing(s,a){a?t.set(`p:${s}`,true):t.delete(`p:${s}`);},isProcessing(s){return t.get(`p:${s}`)===true},getConfig(s){return t.get(`c:${s}`)??{}},setConfig(s,a){let i=t.get(`c:${s}`)??{};t.set(`c:${s}`,{...i,...a});}}}function Kr(e){function t(k){let v=typeof k=="number"?k:Number(k);return Number.isInteger(v)&&v>0?v:null}function r(k,v){let T=v;for(let w=k.length-1;w>=0;w-=1)if(k[w]?.role==="user"&&(T-=1,T===0))return k.slice(w);return k}function s(k){return k.some(v=>typeof v?.turn=="string"&&v.turn!=="")}function a(k,v){if(v<=0)return [];if(!s(k))return r(k,v);let T=new Map,w=[];for(let x of k){let L=typeof x?.turn=="string"?x.turn:"";T.has(L)||(T.set(L,[]),w.push(L)),T.get(L).push(x);}return w.slice(Math.max(0,w.length-v)).flatMap(x=>T.get(x)??[])}function i(k){return {status:"success",data:k}}function c(k){return {status:"fail",error:k}}function u(k){return {status:"error",error:k instanceof Error?k.message:String(k)}}function m(k,v="command envelope"){let T=typeof k.cardId=="string"?k.cardId:void 0;if(!k.command)return c(`chat-store: ${v} missing "command"`);if(!T)return c(`chat-store: ${v} missing "cardId"`);if(k.command==="append")return $.append({params:{cardId:T},body:{role:k.role,text:k.text,files:k.files,turn:k.turn}});if(k.command==="read-all")return $.readAll({params:{cardId:T},body:{lastUserTurns:k.lastUserTurns,tailTurns:k.tailTurns,turnId:k.turnId,allTurns:k.allTurns,tailTurnsBeforeId:k.tailTurnsBeforeId}});if(k.command==="read-after")return $.readAfter({params:{cardId:T},body:{cursor:k.cursor??null}});if(k.command==="clear")return $.clear({params:{cardId:T}});if(k.command==="set-processing")return $.setProcessing({params:{cardId:T},body:{active:k.active}});if(k.command==="is-processing")return $.isProcessing({params:{cardId:T}});if(k.command==="get-config")return $.getConfig({params:{cardId:T}});if(k.command==="set-config"){let{command:w,cardId:N,...x}=k;return $.setConfig({params:{cardId:T},body:x})}return c(`chat-store: unknown command "${String(k.command)}"`)}function O(k){if(!Array.isArray(k.commands)||k.commands.length===0)return c('chat-store: command envelope must include a non-empty "commands" array');let v=[];for(let T=0;T<k.commands.length;T+=1){let w=k.commands[T];if(!w||typeof w!="object"||Array.isArray(w))return c(`chat-store: command envelope entry ${T} must be an object`);let N={cardId:k.cardId,...w},x=m(N,`command envelope entry ${T}`);if(x.status!=="success")return x;v.push({index:T,command:String(N.command),data:x.data});}return i({results:v})}let $={append(k){try{let v=k.params?.cardId;if(!v)return c("append requires params.cardId");let T=k.body??{},w=typeof T.role=="string"?T.role:"",N=typeof T.text=="string"?T.text:"",x=Array.isArray(T.files)?T.files:[],L=typeof T.turn=="string"?T.turn:"";if(!w)return c("append requires body.role");let H=e.append(v,w,N,x,L);return i({id:H})}catch(v){return u(v)}},readAll(k){try{let v=k.params?.cardId;if(!v)return c("readAll requires params.cardId");let T=k.body??{},w=typeof T.turnId=="string"?T.turnId:"",N=T.allTurns===!0,x=typeof T.tailTurnsBeforeId=="string"?T.tailTurnsBeforeId:"",L=T.tailTurns===void 0?T.lastUserTurns:T.tailTurns,H=L===void 0?N||w?void 0:1:t(L);if(L!==void 0&&H===null)return c("readAll requires body.tailTurns (positive integer)");let I=e.readAll(v),M=I.filter(R=>!w||String(R.turn||"")===w);if(x){let R=H;if(typeof R!="number"||!Number.isInteger(R)||R<=0)return c("readAll requires body.tailTurns (positive integer) when body.tailTurnsBeforeId is provided");let C=new Map,y=[];for(let A of I){let _=String(A.turn||"");C.has(_)||(C.set(_,[]),y.push(_)),C.get(_).push(A);}let l=y.findIndex(A=>A===x),p=Math.max(0,l-R);return M=(l===-1?[]:y.slice(p,l)).flatMap(A=>C.get(A)??[]),i({records:M})}return i(typeof H=="number"?{records:a(M,H)}:{records:M})}catch(v){return u(v)}},readAfter(k){try{let v=k.params?.cardId;if(!v)return c("readAfter requires params.cardId");let w=(k.body??{}).cursor??null;return i(e.readAfter(v,w))}catch(v){return u(v)}},clear(k){try{let v=k.params?.cardId;return v?(e.clear(v),i({ok:!0})):c("clear requires params.cardId")}catch(v){return u(v)}},setProcessing(k){try{let v=k.params?.cardId;if(!v)return c("setProcessing requires params.cardId");let T=k.body??{};return typeof T.active!="boolean"?c("setProcessing requires body.active (boolean)"):(e.setProcessing(v,T.active),i({ok:!0}))}catch(v){return u(v)}},isProcessing(k){try{let v=k.params?.cardId;return v?i({active:e.isProcessing(v)}):c("isProcessing requires params.cardId")}catch(v){return u(v)}},getConfig(k){try{let v=k.params?.cardId;return v?i({config:e.getConfig(v)}):c("getConfig requires params.cardId")}catch(v){return u(v)}},setConfig(k){try{let v=k.params?.cardId;if(!v)return c("setConfig requires params.cardId");let T=k.body??{};return e.setConfig(v,T),i({ok:!0})}catch(v){return u(v)}},run:m,runBatch:O};return $}var Hr={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"content-type,x-file-name","Access-Control-Allow-Methods":"GET,POST,PATCH,OPTIONS"},Jn=32;function zn(){return {status:null,computedValues:{},dataObjects:{},cards:{}}}function Jr(e){if(!e||typeof e!="object")return false;let t=e.summary;return !t||typeof t!="object"?false:Number(t.card_count||0)>0}function zr(e,t){if(!t||typeof t!="object")return;let r=t;if(r.kind==="notification-batch"&&Array.isArray(r.notifications)){for(let s of r.notifications)zr(e,s);return}r.kind==="status"&&Jr(r.status)&&(e.status=r.status),r.kind==="computed_values"&&r.cardId&&(e.computedValues[r.cardId]=r.values),r.kind==="data_object"&&r.key&&(e.dataObjects[r.key]=r.payload),r.kind==="card_refreshed"&&r.cardId&&(e.cards[r.cardId]=r.card),r.kind==="card_removed"&&r.cardId&&(delete e.cards[r.cardId],delete e.computedValues[r.cardId]);}function rs(e){let t=String(e.apiBasePath||"/api/board").replace(/\/$/,""),r={...Hr,...e.corsHeaders||{}},s=e.boardId||"",a=e.logger||{info:console.log,warn:console.warn,error:console.error},i=e.invocationAdapter,c=e.chatFlowRunner||null,u=e.chatStorage??Vr(),m=Kr(u),O=e.notificationTransport||null,$=e.serverUrl||null,k=e.executionExtra||{},v=e.onSseClientConnected,T=e.onSseClientDisconnected,w=e.onChannelSubscribed,N=e.onChannelUnsubscribed,x=new Map,L=new Map,H=new Map,I=null;function M(o){let n=qr(o.baseRef,o.boardAdapter),d=o.nonCoreAdapter??(l(o.boardAdapter)?o.boardAdapter:null),f=d?Nr(o.baseRef,d):null,h=o.boardAdapter.kvStorageForRef(o.cardStoreRef),F=Tt(mt({readIndex:()=>h.read("_index"),writeIndex:pe=>h.write("_index",pe),readCard:pe=>h.read(pe),writeCard:(pe,Se)=>(h.write(pe,Se),pe),cardExists:pe=>h.read(pe)!==null,defaultCardKey:pe=>pe},a.warn)),U=o.artifactsAdapter||o.boardAdapter,V=o.filesArtifactsStore??null,ue=o.artifactsAdapter?U.blobStorage(""):U.blobStorage("files"),fe=null;return {label:o.label,board:n,nonCore:f,cardStore:F,get filesArtifacts(){return fe??=V??Mr(ue)},boardAdapter:o.boardAdapter,cardStoreRef:o.cardStoreRef,outputsStoreRef:o.outputsStoreRef,artifactsStoreRef:o.artifactsStoreRef,scratchStoreRef:o.scratchStoreRef,archiveStoreRef:o.archiveStoreRef,notifyRef:o.notifyRef,taskExecutorRef:o.taskExecutorRef,chatHandlerRef:o.chatHandlerRef,chatHandlerFlow:o.chatHandlerFlow,inferenceAdapterRef:o.inferenceAdapterRef,notification:zn(),notificationTeardown:null,initialized:false,cardsBootstrapped:false}}let R=e.boards.map(M),C=new Map;function y(o){return C.get(o)??0}function l(o){let n=o;return typeof n.invokeExecutorSync=="function"&&typeof n.validateSchema=="function"}function p(o){let n=R[y(o)];return {files:n?n.filesArtifacts:null}}function S(o){let n=p(o);return n.files?Ur(n.files):null}function A(){return Gr()}function _(o){return String(o||"").replace(/[^a-zA-Z0-9_-]/g,"_")||"unknown-card"}async function j(o){if(!o||o.notificationTeardown||!O||!o.notifyRef)return;let n=await O.subscribe(o.notifyRef,d=>{zr(o.notification,d);let f=d.kind==="notification-batch"?d.notifications:[d];Jt(f);});o.notificationTeardown=n;}async function Y(o){if(!o||o.initialized)return;let n={cardStoreRef:o.cardStoreRef,outputsStoreRef:o.outputsStoreRef};o.artifactsStoreRef&&(n.artifactsStoreRef=o.artifactsStoreRef),o.scratchStoreRef&&(n.scratchStoreRef=o.scratchStoreRef),o.archiveStoreRef&&(n.archiveStoreRef=o.archiveStoreRef);let d={};o.taskExecutorRef&&(d["task-executor-ref"]=o.taskExecutorRef),o.chatHandlerFlow!==void 0&&(d["chat-handler-flow"]=o.chatHandlerFlow),o.inferenceAdapterRef&&(d["inference-adapter-ref"]=o.inferenceAdapterRef);let f=o.board.init({params:n,body:d});if(f.status!=="success")throw Object.assign(new Error(f.error||`init failed for ${o.label}`),{statusCode:500});if(await j(o),!o.chatHandlerFlow&&o.chatHandlerRef&&i.describe)try{let h=await i.describe(o.chatHandlerRef);h&&h.kind!=="chat-handler"?a.warn(`[init] chat-handler describe returned kind="${h.kind}", expected "chat-handler" for ${o.label}`):h&&a.info(`[init] chat-handler validated: ${h.name} (protocol ${h.protocolVersion}) for ${o.label}`);}catch(h){a.warn(`[init] chat-handler describe failed for ${o.label}: ${h?.message||String(h)}`);}o.initialized=true;}function re(o){if(!o.boardAdapter.publishBoardChangeNotifications)return;let n=[],d=o.board.status({});d.status==="success"&&d.data!=null&&Jr(d.data)&&n.push({kind:"status",status:d.data});let f=o.board.getAllOutputsDataObjects({});if(f.status==="success"&&f.data!=null)for(let[b,F]of Object.entries(f.data))b&&n.push({kind:"data_object",key:b,payload:F});let h=o.board.getAllOutputsComputedValues({});if(h.status==="success"&&h.data!=null)for(let[b,F]of Object.entries(h.data))b&&n.push({kind:"computed_values",cardId:b,values:F});n.length>0&&o.boardAdapter.publishBoardChangeNotifications(n);}function ne(o,n){if(!o||o.cardsBootstrapped)return;let d=o.cardStore.get({}),f=d.status==="success"&&Array.isArray(d.data?.cards)?d.data.cards:[];for(let h of f)typeof h.id=="string"&&(C.set(h.id,n),o.board.upsertCard({params:{cardId:h.id}}));o.cardsBootstrapped=true;}async function se(){for(let o of R)await Y(o);}async function B(){await se();for(let o=0;o<R.length;o++)re(R[o]),ne(R[o],o);}function q(o){return R[y(o)]??null}function Q(o){let n=q(o);if(!n)return null;let d=n.cardStore.get({params:{id:o}});if(d.status!=="success")return null;let f=Array.isArray(d.data?.cards)?d.data.cards:[];return f.length>0?f[0]:null}function ie(){let o=d=>{if(!d||!d.cardStore)return [];let f=d.cardStore.get({});return f.status!=="success"||!Array.isArray(f.data?.cards)?[]:f.data.cards},n=[];for(let d of R)n.push(...o(d));return n}function ee(){return R[0]??null}function _e(){return {status(){let o=oe();return o==null?{status:"fail",error:"Board status is unavailable"}:{status:"success",data:o}},getOutputsDataObject(o){let n=o?.params?.key;return n?{status:"success",data:ve()[n]}:{status:"fail",error:"getOutputsDataObject requires params.key"}},getOutputsComputedValues(o){let n=o?.params?.key;return n?{status:"success",data:le()[n]?.computed_values}:{status:"fail",error:"getOutputsComputedValues requires params.key"}},getOutputsFetchedSources(o){let n=o?.params?.key;if(!n)return {status:"fail",error:"getOutputsFetchedSources requires params.key"};let d=q(n)??ee();return d?d.board.getOutputsFetchedSources({params:{key:n}}):{status:"fail",error:"Board context is unavailable"}},removeCard(o){let n=o?.params?.id;if(!n)return {status:"fail",error:"removeCard requires params.id"};let d=q(n)??ee();return d?d.board.removeCard({params:{id:n}}):{status:"fail",error:"Board context is unavailable"}},cardRefreshedNotify(o){let n=o?.params?.cardId;if(!n)return {status:"fail",error:"cardRefreshedNotify requires params.cardId"};let d=q(n)??ee();return d?d.board.cardRefreshedNotify({params:{cardId:n}}):{status:"fail",error:"Board context is unavailable"}},upsertCard(o){let n=o?.params?.cardId;if(!n)return {status:"fail",error:"upsertCard requires params.cardId"};let d=q(n)??ee();return d?d.board.upsertCard({params:{cardId:n,restart:o.params.restart===true}}):{status:"fail",error:"Board context is unavailable"}}}}function X(){let o=()=>{let n=ee();if(!n?.nonCore)throw new Error("Board non-core adapter is not configured for MCP preflight/discovery tools");return n.nonCore};return {describeTaskExecutorCapabilities(n){return o().describeTaskExecutorCapabilities(n)},validateCardPreflight(n){return o().validateCardPreflight(n)},evalCardCompute(n){return o().evalCardCompute(n)},probeSourcePreflight(n){return o().probeSourcePreflight(n)},runSourcePreflight(n){return o().runSourcePreflight(n)},simulateCardCycle(n){return o().simulateCardCycle(n)}}}function ke(){return {get(o){let n=typeof o.params?.id=="string"?o.params.id:void 0;if(n){let d=Q(n);return d?{status:"success",data:{cards:[d]}}:{status:"fail",error:`card "${n}" not found`}}return {status:"success",data:{cards:ie()}}},set(o){let n=o.body;if(n==null)return {status:"fail",error:"set requires a body (card object or array of cards)"};let d=Array.isArray(n)?n:[n];for(let f of d){let h=f,b=typeof h.id=="string"?h.id:"";if(!b)return {status:"fail",error:"each card must have a string `id` field"};let F=C.get(b)??0,U=R[F]??ee();if(!U)return {status:"fail",error:"Board context is unavailable"};let V=U.cardStore.set({body:h});if(V.status!=="success")return V;C.set(b,F);}return {status:"success",data:{count:d.length}}},del(o){let n=[o.params?.id,...o.body?.ids??[]].filter(d=>typeof d=="string"&&!!d);if(n.length===0)return {status:"fail",error:"del requires body.ids (string[]) or params.id"};for(let d of n){let f=q(d)??ee();if(!f)return {status:"fail",error:"Board context is unavailable"};let h=f.cardStore.del({params:{id:d}});if(h.status!=="success")return h;C.delete(d);}return {status:"success",data:{count:n.length}}},patch(o){let n=typeof o.params?.id=="string"?o.params.id:void 0,d=typeof o.params?.path=="string"?o.params.path:void 0;if(!n||!d)return {status:"fail",error:"patch requires params.id and params.path"};let f=q(n)??ee();return f?f.cardStore.patch(o):{status:"fail",error:"Board context is unavailable"}},appendFiles(o){let n=typeof o.params?.id=="string"?o.params.id:void 0;if(!n)return {status:"fail",error:"appendFiles requires params.id"};let d=q(n)??ee();return d?d.cardStore.appendFiles(o):{status:"fail",error:"Board context is unavailable"}}}}function we(){return $r({board:_e(),nonCore:X(),cardStore:ke(),chatStore:m,uploadCardFile({cardId:o,fileName:n,contentType:d,bytes:f}){return it(o,n,d,f,{inChat:false})},buildFileDownloadUrl({cardId:o,fileIdx:n,storedName:d}){let f=`${$||""}${t}/cards/${encodeURIComponent(o)}/files/${n}`;return d?`${f}?sn=${encodeURIComponent(d)}`:f},readFetchedSourceJsonByRef({cardId:o,ref:n}){let d=q(o)??ee();if(!d)return null;let h=d.boardAdapter.resolveBlob(ot(n)).trim();return h?JSON.parse(h):null}})}function me(o,...n){for(let d of n)if(typeof o[d]=="string")return String(o[d]);return ""}function be(o,...n){for(let d of n)if(o[d]!==void 0)return Number(o[d])}function Ne(o,...n){for(let d of n){let f=o[d];if(f&&typeof f=="object"&&!Array.isArray(f))return f}return {}}function je(o,n,...d){for(let f of d){let h=o[f];if(h&&typeof h=="object"&&!Array.isArray(h))return h}throw Object.assign(new Error(`MCP tool requires ${n}`),{statusCode:400})}function E(o,n,...d){for(let f of d){let h=o[f];if(h!==void 0){let b=Number(h);if(Number.isFinite(b))return b}}throw Object.assign(new Error(`MCP tool requires ${n}`),{statusCode:400})}function g(o){return {"discover.source-kinds":()=>o.discoverSourceKinds(),"inspect.board-runtime-status":()=>o.inspectBoardRuntimeStatus(),"inspect.card-definition-and-runtime":n=>o.inspectCardDefinitionAndRuntime({cardId:me(n,"card_id","cardId")}),"inspect.chat-messages-on-cards":n=>{let d=be(n,"tail-turns"),f=be(n,"tail"),h=me(n,"turn-id"),b=n["all-turns"]===true,F=me(n,"tail-turns-before-id");return o.inspectChatMessagesOnCards({cardId:me(n,"card_id","cardId"),...d!==void 0?{lastUserTurns:d}:{},...f!==void 0?{tail:f}:{},...h?{turnId:h}:{},...b?{allTurns:true}:{},...F?{tailTurnsBeforeId:F}:{}})},"inspect.file-contents":n=>o.inspectFileContents({cardId:me(n,"card_id","cardId"),fileIdx:Number(be(n,"file_idx","fileIdx"))}),"preflight.validate-candidate-card-definition":n=>o.preflightValidateCandidateCardDefinition({candidateCardContent:je(n,"candidate_card_content","candidate_card_content","candidateCardContent")}),"preflight.materialize-candidate-card":n=>o.preflightMaterializeCandidateCard({candidateCardContent:je(n,"candidate_card_content","candidate_card_content","candidateCardContent"),mockRequires:je(n,"mock_requires","mock_requires","mockRequires"),mockFetchedSources:je(n,"mock_fetched_sources","mock_fetched_sources","mockFetchedSources")}),"preflight.probe-single-source-in-candidate-card":n=>o.preflightProbeSingleSourceInCandidateCard({candidateCardContent:je(n,"candidate_card_content","candidate_card_content","candidateCardContent"),mockProjections:Ne(n,"mock_projections","mockProjections"),sourceIdx:E(n,"source_idx","source_idx","sourceIdx")}),"preflight.run-single-source-in-candidate-card":n=>o.preflightRunSingleSourceInCandidateCard({candidateCardContent:je(n,"candidate_card_content","candidate_card_content","candidateCardContent"),mockProjections:Ne(n,"mock_projections","mockProjections"),sourceIdx:E(n,"source_idx","source_idx","sourceIdx")}),"preflight.run-single-source-in-live-card":n=>o.preflightRunSingleSourceInLiveCard({cardId:me(n,"card_id","cardId"),sourceIdx:E(n,"source_idx","source_idx","sourceIdx"),mockRequires:je(n,"mock_requires","mock_requires","mockRequires")}),"preflight.run-one-cycle-with-candidate-card":n=>o.preflightRunOneCycleWithCandidateCard({candidateCardContent:je(n,"candidate_card_content","candidate_card_content","candidateCardContent"),mockRequires:Ne(n,"mock_requires","mockRequires")}),"manage.read-card":n=>o.manageReadCard({cardId:me(n,"card_id","cardId")}),"stage-ai-response-and-any-attachments":n=>o.manageAddChatEntryAndAnyAttachments({cardId:me(n,"card_id","cardId"),role:"assistant",...typeof n.text=="string"?{text:n.text}:{},...typeof me(n,"turn-id","turnId","turn")=="string"&&me(n,"turn-id","turnId","turn")!==""?{turn:me(n,"turn-id","turnId","turn")}:{},...Array.isArray(n.files)?{files:n.files}:{}}),"manage.upload-card-file":n=>{let d=me(n,"card_id","cardId"),f=me(n,"file_name","fileName","name"),h=me(n,"content_type","contentType")||"application/octet-stream",b=null;if(Array.isArray(n.bytes))b=new Uint8Array(n.bytes.map(F=>Math.max(0,Math.min(255,Number(F)||0))));else if(typeof n.text=="string")b=new TextEncoder().encode(n.text);else if(typeof n.base64=="string"){let F=String(n.base64).replace(/-/g,"+").replace(/_/g,"/"),U=F+"=".repeat((4-F.length%4)%4),V=atob(U);b=Uint8Array.from(V,ue=>ue.charCodeAt(0));}if(!d)throw Object.assign(new Error("manage.upload-card-file requires card_id"),{statusCode:400});if(!f)throw Object.assign(new Error("manage.upload-card-file requires file_name"),{statusCode:400});if(!b)throw Object.assign(new Error("manage.upload-card-file requires args.bytes, args.text, or args.base64"),{statusCode:400});return it(d,f,h,b,{inChat:false})},"manage.upsert-card":n=>o.manageUpsertCard({cardId:me(n,"card_id","cardId"),candidateCardContent:Ne(n,"candidate_card_content","candidateCardContent")}),"manage.deprecate":n=>o.manageDeprecate({cardId:me(n,"card_id","cardId")})}}function P(o,n){let d=g(we())[o];if(!d)throw Object.assign(new Error(`Unknown MCP tool: ${o}`),{statusCode:400});let f=d(n);if(f&&typeof f=="object"&&!Array.isArray(f)){let h=f,b=h.status;if(b==="success")return Object.prototype.hasOwnProperty.call(h,"data")?f:{status:"success",data:{}};if(b==="fail"||b==="error")return f}return {status:"success",data:f}}function G(o,n){if(!o||typeof o!="object"||Array.isArray(o))return n;let d=o;if(typeof d.error=="string"&&d.error.trim())return d.error;if(d.step==="validate"){let f=d.validation;if(f&&typeof f=="object"&&!Array.isArray(f)){let b=f.data;if(b&&typeof b=="object"&&!Array.isArray(b)){let F=b.issues;if(Array.isArray(F)){let V=F.find(ue=>typeof ue=="string"&&ue.trim());if(typeof V=="string")return `Validation failed: ${V}`}let U=b.errors;if(Array.isArray(U)&&U.length>0)return "Validation failed"}}return "Validation failed"}return n}function oe(){let o=R.map(b=>{try{let U=b.boardAdapter.kvStorageForRef(b.outputsStoreRef).read("status");if(U!=null)return U}catch{}return b.notification.status}).filter(Boolean);if(o.length===0)return null;if(o.length===1)return o[0];let n=[],d=["completed","eligible","pending","blocked","unresolved","failed","in_progress","orphan_cards"],f={};for(let b of d)f[b]=0;for(let b of o){let F=b,U=Array.isArray(F.cards)?F.cards:[];n.push(...U);for(let V of d)f[V]+=Number(F?.summary?.[V]||0);}let h=o[0];return {...h,cards:n,summary:{...h.summary||{},card_count:n.length,...f}}}function le(){let o={},n=d=>{for(let[f,h]of Object.entries(d.notification.computedValues)){let b=d.notification.cards[f];o[f]={schema_version:"v1",card_id:f,card_data:b?.card_data??{},computed_values:h??{}};}};for(let d of R)n(d);return o}function ve(){let o={};for(let n of R)Object.assign(o,n.notification.dataObjects||{});return o}function he(){let o=ie(),n=le(),d=ve(),f={};for(let b of o){if(!b?.id)continue;let F=b.id,U=n[F]||{},V={...U.card_data&&typeof U.card_data=="object"?U.card_data:b.card_data&&typeof b.card_data=="object"?b.card_data:{}};f[F]={schema_version:U.schema_version||"v1",card_id:U.card_id||F,card_data:V,computed_values:U.computed_values&&typeof U.computed_values=="object"?U.computed_values:{}};}let h={};for(let b of o){if(!b?.id)continue;let F=b.id;try{let U=et(F),V=u.isProcessing(F);(U.length>0||V)&&(h[F]={messages:U.map(ue=>({role:String(ue.role||"system"),text:String(ue.text||""),files:Array.isArray(ue.files)?ue.files:[]})),receiving:!1,processing:V});}catch{}}return {boardId:s,cardDefinitions:o,statusSnapshot:oe(),dataObjectsByToken:d,cardRuntimeById:f,cardChatsByCardId:h}}function xe(o,n,d){let f=d?.syncBoard!==false,h=d?.restartOnlyIfChanged===true,b=q(o);if(!b)throw Object.assign(new Error(`Card not found: ${o}`),{statusCode:404});let F=Q(o);if(!F)throw Object.assign(new Error(`Card not found: ${o}`),{statusCode:404});let U=h?JSON.stringify(F):null,V=n(F)||F;if(h&&JSON.stringify(V)===U)return;let ue=b.cardStore.set({body:V});if(ue.status!=="success")throw Object.assign(new Error(ue.error||`Failed to persist card: ${o}`),{statusCode:500});if(f){let fe=b.board.upsertCard({params:{cardId:o,restart:true}});if(fe.status!=="success")throw Object.assign(new Error(fe.error||`Failed to upsert card: ${o}`),{statusCode:500})}}function Ae(o,n){xe(o,n,{syncBoard:true});}function Ue(o,n){xe(o,n,{syncBoard:false});}function Ve(o){let n=q(o);if(!n)throw Object.assign(new Error(`Card not found: ${o}`),{statusCode:404});if(!Q(o))throw Object.assign(new Error(`Card not found: ${o}`),{statusCode:404});let f=n.board.upsertCard({params:{cardId:o,restart:true}});if(f.status!=="success")throw Object.assign(new Error(f.error||`Failed to retrigger card: ${o}`),{statusCode:500})}function We(o,n){xe(o,d=>{if(!n||typeof n!="object"||Object.keys(n).length===0)return d;function f(h,b,F){let U=String(b||"").split(".").filter(Boolean);if(!U.length)return;let V=h;for(let ue=0;ue<U.length-1;ue++){let fe=U[ue];(!V[fe]||typeof V[fe]!="object")&&(V[fe]={}),V=V[fe];}V[U[U.length-1]]=F;}if(n.fieldValues!==void 0&&n.fieldValues!==null){let h=null,b=d.view;if(b&&Array.isArray(b.elements)){for(let F of b.elements)if(F?.data&&F.data.writeTo){h=F.data.writeTo;break}}h?f(d,h,n.fieldValues):typeof n.fieldValues=="object"&&!Array.isArray(n.fieldValues)&&(d.card_data={...d.card_data||{},...n.fieldValues});}else {if(Array.isArray(n._stagedFiles)&&n._stagedFiles.length>0)return d;for(let[h,b]of Object.entries(n))h!=="_stagedFiles"&&(b!==null&&typeof b=="object"&&!Array.isArray(b)&&d[h]!==null&&typeof d[h]=="object"&&!Array.isArray(d[h])?d[h]={...d[h],...b}:d[h]=b);}return d},{syncBoard:true,restartOnlyIfChanged:true});}function Ye(o){let n=String(o||"").trim();if(!n)return "upload.bin";let d=Math.max(n.lastIndexOf("/"),n.lastIndexOf("\\"));return (d>=0?n.slice(d+1):n)||"upload.bin"}function Ke(o){u.clear(o),u.setProcessing(o,false);}function st(o,n,d,f,h=""){let b=typeof d=="string"?d.trim():"";return u.append(o,n,b,f,h)}function et(o){return u.readAll(o)}function at(o){let n=[];try{let d=Q(o);if(!d)return n;let f=A().read(d.card_data&&typeof d.card_data=="object"?d.card_data:null);for(let h of f)n.push(h.stored_name);}catch{}return n}function yt(o,n,d,f){let h=_(o),b=p(o),F=Ye(n),U=S(o),V=U?U.allocateStoredName(h,F,{seedNames:at(o),maxLen:Jn}):`${String(Date.now())}-${F}`;return b.files&&b.files.putBytes(`${h}/${V}`,new Uint8Array(f),d||"application/octet-stream"),{name:F,stored_name:V,size:f.length,mime_type:d||"application/octet-stream",uploaded_at:new Date().toISOString()}}function it(o,n,d,f,h){if(!f.length)throw Object.assign(new Error("Empty upload body"),{statusCode:400});let b=h?.inChat===true,F=yt(o,n,d,f),U=null;if(Ue(o,V=>{let ue=new Date().toISOString(),fe=V.card_data&&typeof V.card_data=="object"?V.card_data:{};V.card_data=fe;let pe=A().normalizeIncoming([{name:F.name,stored_name:F.stored_name,size:F.size,mime_type:F.mime_type,uploaded_at:F.uploaded_at||ue,chat:b}],ue);return U=A().merge(fe,pe).findIndex(tt=>tt.stored_name===F.stored_name),V}),b){let V=typeof U=="number"&&U>=0?` #${U}`:"";st(o,"system",`file uploaded: ${F.name} as ${F.stored_name}${V}`,[],h?.turnId??"");}return {ok:true,file:F}}function dt(o){let n=q(o);if(!n)return null;let d=n.board.getConfig({params:{key:"chat-handler-flow"}}),f=d.status==="success"?d.data?.value:null,h=n.chatHandlerRef;return f==null&&(!h||typeof h!="object")?null:{ctx:n,handlerFlow:f,handlerRef:h}}function Vt(o,n,d=false,f=""){let h=dt(o);if(!h)return;let{ctx:b,handlerFlow:F,handlerRef:U}=h;if(!d)try{u.setProcessing(o,!0);}catch{}let V={boardId:s,cardId:String(o),lastChatEntryId:n,...f?{turnId:f}:{},...k,...$?{serverUrl:$}:{}};if(!c&&F!=null){try{u.setProcessing(o,!1);}catch{}a.warn(`[chat-handler-flow] configured for card "${o}" but no chatFlowRunner was provided`);return}if(F!=null){let fe=c;if(!fe)return;fe.run(F,V,{boardId:s,cardId:String(o),label:b.label,logger:a,serverUrl:$,executionExtra:k}).then(pe=>{if(pe.dispatched)a.info(`[chat-handler-flow] invoked for card "${o}" (boardId: "${s}")`);else {try{u.setProcessing(o,!1);}catch{}a.warn(`[chat-handler-flow] dispatch failed for card "${o}": ${pe.error||"unknown"}`);}},pe=>{try{u.setProcessing(o,!1);}catch{}a.warn(`[chat-handler-flow] invoke failed for card "${o}": ${pe?.message||String(pe)}`);});return}let ue=U;ue&&i.invoke(ue,V).then(fe=>{if(fe.dispatched)a.info(`[chat-handler] invoked for card "${o}" (boardId: "${s}")`);else {try{u.setProcessing(o,!1);}catch{}a.warn(`[chat-handler] dispatch failed for card "${o}": ${fe.error||"unknown"}`);}},fe=>{try{u.setProcessing(o,!1);}catch{}a.warn(`[chat-handler] invoke failed for card "${o}": ${fe?.message||String(fe)}`);});}function Kt(o,n,d){let f=n==="chat-send"?Ue:Ae,h;f(o,b=>{let F=new Date().toISOString(),U=b.card_data&&typeof b.card_data=="object"?b.card_data:{};if(b.card_data=U,n==="chat-send"){let V=d&&typeof d.text=="string"?d.text.trim():"",ue=d&&typeof d["turn-id"]=="string"?d["turn-id"]:d&&typeof d.turnId=="string"?d.turnId:d&&typeof d.turn=="string"?d.turn:"",fe=[];if(Array.isArray(d?.files)){for(let pe of d.files)if(pe){if(typeof pe=="string"){fe.push({name:pe});continue}if(typeof pe=="object"){let Se=pe;typeof Se.name=="string"&&fe.push({name:Se.name,size:Se.size,mime_type:Se.mime_type,uploaded_at:Se.uploaded_at,stored_name:Se.stored_name,chat:Se.chat===true});}}}if(V||fe.length>0){let pe=m.runBatch({cardId:o,commands:[{command:"append",role:"user",text:V,files:fe,turn:ue},{command:"set-processing",active:true}]});if(pe.status!=="success")throw new Error(pe.error);let Se=pe.data.results[0]?.data?.id;if(typeof Se!="string"||!Se)throw new Error(`chat-send did not return an append id for card ${o}`);h={cardId:o,lastEntryId:Se,processingAlreadySet:true,turnId:ue};try{let lt=et(o);Jt([{kind:"card_chats",cardId:o,messages:lt.map(J=>({role:String(J.role||"system"),text:String(J.text||""),files:Array.isArray(J.files)?J.files:[]})),receiving:!0,processing:u.isProcessing(o)}]);}catch{}}return b}if(n==="file-upload"){let V=A().normalizeIncoming(d?.files,F);return V.length>0&&A().merge(U,V),b}if(n==="action"){let V=d&&typeof d.buttonId=="string"?d.buttonId:"";if(!V)return b;U.lastAction={buttonId:V,at:F},U.lastActionText=`${V} @ ${F}`;}return b}),h&&Vt(h.cardId,h.lastEntryId,h.processingAlreadySet,h.turnId??"");}function te(o,n,d){let f=JSON.stringify(d),h=typeof Buffer<"u"?Buffer.byteLength(f):new TextEncoder().encode(f).length;o.writeHead(n,{...r,"Content-Type":"application/json; charset=utf-8","Content-Length":h}),o.end(f);}function ct(o,n,d){let f=Q(o);if(!f)throw Object.assign(new Error("Card not found"),{statusCode:404});let h=A().resolve(f.card_data,n,d);if(!h.ok&&h.reason==="stale_reference")throw Object.assign(new Error("File reference is stale. Refresh and try again."),{statusCode:409});if(!h.ok)throw Object.assign(new Error("File not found"),{statusCode:404});let b=h.file,F=_(o),U=p(o),V=String(b.stored_name||""),ue=`${F}/${V}`,fe=U.files?U.files.getBytes(ue):null;if(!fe)throw Object.assign(new Error("File not found"),{statusCode:404});return {fileRecord:b,bytes:fe}}function Ct(o,n,d,f){let{fileRecord:h,bytes:b}=ct(n,d,f),F=String(h.name||h.stored_name||"download.bin"),U=String(h.mime_type||"application/octet-stream");o.writeHead(200,{"Content-Type":U,"Content-Disposition":`attachment; filename="${F}"`,"Content-Length":b.length}),o.end(b);}function nt(o){let n=String(o||"").toLowerCase();return n.startsWith("text/")||n.includes("json")||n.includes("xml")||n.includes("javascript")||n.includes("typescript")||n.includes("yaml")||n.includes("csv")}function He(o,n,d){let f=o.split(/\r?\n/);return (n==="head"?f.slice(0,d):f.slice(-d)).join(`
|
|
2
|
+
`)}async function Pe(o){let n=[];for await(let f of o)n.push(f);let d=typeof Buffer<"u"?Buffer.concat(n).toString("utf-8").trim():new TextDecoder().decode(W(n)).trim();return d?JSON.parse(d):{}}async function D(o){let n=[];for await(let d of o)n.push(d);return typeof Buffer<"u"?Buffer.concat(n):W(n)}function W(o){let n=o.reduce((h,b)=>h+b.length,0),d=new Uint8Array(n),f=0;for(let h of o)d.set(h,f),f+=h.length;return d}let ye=0;function $e(o){let n=JSON.stringify(o);return ye++,`id: ${ye}
|
|
3
3
|
data: ${n}
|
|
4
4
|
|
|
5
|
-
`}function
|
|
5
|
+
`}function Be(o){let n=o;try{n.flushHeaders?.();}catch{}try{n.flush?.();}catch{}try{n.socket?.setNoDelay?.(!0);}catch{}try{n.socket?.uncork?.();}catch{}}function Xe(o,n){let d=x.get(o);if(d&&!(n&&d.res!==n)){x.delete(o),Bt();try{T?.(o);}catch{}try{d.res.end();}catch{}}}function De(o,n){let d=x.get(o);if(!d)return;let f=$e(n);try{d.res.write(f),Be(d.res);}catch{Xe(o,d.res);}}function ut(o,n,d,f,h){if(!x.has(n)){te(o,404,{error:`SSE client not connected: ${n}`});return}h?w?.(n,d,f):N?.(n,d,f),te(o,200,{ok:true,clientId:n,channelName:d,...f.cardId?{cardId:f.cardId}:{},subscribed:h});}function Ot(){let o=new Set;for(let n of x.values())for(let d of n.subscribedChatCardIds)o.add(d);return Array.from(o)}function Wr(o){let n=L.has(o)?L.get(o):null,{cursor:d}=u.readAfter(o,n),f=u.isProcessing(o),h=f!==(H.get(o)??false),b=d!==n;return b&&L.set(o,d),H.set(o,f),b||h}function Ht(o,n=true){let d=et(o),f=Date.now();return {kind:"card_chats",cardId:o,sentAt:new Date(f).toISOString(),sentAtMs:f,messages:d.map(h=>({role:String(h.role||"system"),text:String(h.text||""),files:Array.isArray(h.files)?h.files:[]})),receiving:n,processing:u.isProcessing(o)}}function jt(o,n=true){let d={kind:"notification-batch",notifications:[Ht(o,n)]};for(let[f,h]of x.entries())h.subscribedChatCardIds.has(o)&&De(f,d);}function Bt(){Ot().length>0||(I&&(clearInterval(I),I=null),L.clear(),H.clear());}function Yr(){if(I)return;let o=()=>{let n=Ot();if(n.length===0){Bt();return}let d=new Set(n);for(let f of Array.from(L.keys()))d.has(f)||L.delete(f);for(let f of Array.from(H.keys()))d.has(f)||H.delete(f);for(let f of n)Wr(f)&&jt(f,true);};o(),I=setInterval(o,1e3);}function Xr(o,n){let d=x.get(o);if(!d)return false;d.subscribedChatCardIds.add(n);let{cursor:f}=u.readAfter(n,null);return L.set(n,f),H.set(n,u.isProcessing(n)),Yr(),De(o,{kind:"notification-batch",notifications:[Ht(n,true)]}),true}function Zr(o,n){let d=x.get(o);return d?(d.subscribedChatCardIds.delete(n),Ot().includes(n)||(L.delete(n),H.delete(n)),Bt(),true):false}function Qr(o){if(!o||typeof o!="object")return false;let n=o.kind;return n==="card_chats"||n==="chat_messages"}function Jt(o){if(!o||o.length===0)return;let n=[],d=new Set;for(let f of o)Qr(f)&&typeof f.cardId=="string"?d.add(String(f.cardId)):n.push(f);if(n.length>0){let f={kind:"notification-batch",notifications:n};for(let h of x.keys())De(h,f);}for(let f of d)jt(f,true);}function en(o,n,d){let f=x.get(d),h=f?new Set(f.subscribedChatCardIds):new Set;f&&Xe(d,f.res),n.writeHead(200,{...r,"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),Be(n),x.set(d,{res:n,subscribedChatCardIds:h});let b=he(),F=$e(b);n.write(F);try{v?.(d,V=>{De(d,V);});}catch{}let U=setInterval(()=>{try{n.write(`: keepalive
|
|
6
6
|
|
|
7
|
-
`);}catch{}},15e3);o.on("close",()=>{clearInterval(q),fe(d,n);});}async function Xr(o,n,d){let p=o.method||"GET",C=d,S=C.pathname;try{if(p==="GET"&&S===`${t}/init-board`)return await ye(),ee(n,200,Q()),!0;if(p==="GET"&&S===`${t}/sse`){await ye();let K=String(C.searchParams.get("clientId")||"").trim();if(!K)return ee(n,400,{error:"clientId query param is required for SSE"}),!0;Yr(o,n,K);for(let W=0;W<k.length;W++)X(k[W]),ce(k[W],W);return !0}if(p==="GET"&&S===`${t}/board-status`)return ee(n,200,Q()),!0;if(p==="POST"&&S===`${t}/mcp`){await N();let K=await $e(o),W=typeof K.tool=="string"?K.tool.trim():"",ae=K.args&&typeof K.args=="object"&&!Array.isArray(K.args)?K.args:{};return W?W==="inspect.file-contents"?(ee(n,400,{error:"inspect.file-contents is only available on /mcp-raw"}),!0):(ee(n,200,I(W,ae)),!0):(ee(n,400,{error:"tool is required"}),!0)}if(p==="POST"&&S===`${t}/mcp-raw`){await N();let K=await $e(o),W=typeof K.tool=="string"?K.tool.trim():"",ae=K.args&&typeof K.args=="object"&&!Array.isArray(K.args)?K.args:{};if(!W)return ee(n,400,{error:"tool is required"}),!0;if(W!=="inspect.file-contents")return ee(n,400,{error:`Tool does not support raw response: ${W}`}),!0;let Re=me(ae,"card_id","cardId"),we=ke(ae,"file_idx","fileIdx"),be=ke(ae,"head-lines","headLines"),Oe=ke(ae,"tail-lines","tailLines"),Le=ke(ae,"head-bytes","headBytes"),Me=ke(ae,"tail-bytes","tailBytes");if(!Re)return ee(n,400,{error:"inspect.file-contents requires card_id"}),!0;if(we===void 0||!Number.isInteger(we)||we<0)return ee(n,400,{error:"inspect.file-contents requires file_idx to be a non-negative integer"}),!0;if([be,Oe,Le,Me].filter(Je=>Je!==void 0).length>1)return ee(n,400,{error:"inspect.file-contents accepts at most one of head-lines, tail-lines, head-bytes, tail-bytes"}),!0;for(let[Je,ze]of [["head-lines",be],["tail-lines",Oe],["head-bytes",Le],["tail-bytes",Me]])if(ze!==void 0&&(!Number.isInteger(ze)||ze<0))return ee(n,400,{error:`inspect.file-contents requires ${Je} to be a non-negative integer`}),!0;let dt=Se().inspectFileContents({cardId:Re,fileIdx:we}),ct=typeof dt?.stored_name=="string"?dt.stored_name:null,{fileRecord:ht,bytes:yt}=$t(Re,we,ct),He=String(ht.name||ht.stored_name||"download.bin"),Ze=String(ht.mime_type||"application/octet-stream");if(be!==void 0||Oe!==void 0){if(!at(Ze))return ee(n,400,{error:"head-lines/tail-lines are only supported for text-like files; use head-bytes/tail-bytes for binary content"}),!0;let Je=new TextDecoder().decode(yt),ze=be!==void 0?ft(Je,"head",be):ft(Je,"tail",Oe),zt=typeof Buffer<"u"?Buffer.from(ze,"utf8"):new TextEncoder().encode(ze);return n.writeHead(200,{"Content-Type":Ze,"Content-Disposition":`attachment; filename="${He}"`,"Content-Length":zt.length}),n.end(zt),!0}if(Le!==void 0||Me!==void 0){let Je=Le??Me,ze=Le!==void 0?yt.slice(0,Je):yt.slice(Math.max(0,yt.length-Je));return n.writeHead(200,{"Content-Type":Ze,"Content-Disposition":`attachment; filename="${He}"`,"Content-Length":ze.length}),n.end(ze),!0}return Dt(n,Re,we,ct),!0}let O=S.match(new RegExp(`^${De(t)}/cards/([^/]+)$`));if(p==="GET"&&O){await N();let K=decodeURIComponent(O[1]),W=D(K);return W?(ee(n,200,W),!0):(ee(n,404,{error:`card not found: ${K}`}),!0)}if(p==="PATCH"&&O){await N();let K=decodeURIComponent(O[1]),W=await $e(o);return Ae(K,W),ee(n,200,{ok:!0}),!0}let q=S.match(new RegExp(`^${De(t)}/cards/([^/]+)/retrigger$`));if(p==="POST"&&q){await N();let K=decodeURIComponent(q[1]);return Te(K),ee(n,200,{ok:!0}),!0}let G=S.match(new RegExp(`^${De(t)}/cards/([^/]+)/actions$`));if(p==="POST"&&G){await N();let K=decodeURIComponent(G[1]),W=Date.now(),ae=new Date(W).toISOString(),Re=await $e(o),we=Re?.actionType;if(we==="chat-send"&&!st(K)){let Oe=Date.now();return ee(n,409,{error:`chat handler is not configured for card: ${K}`,requestReceivedAt:ae,requestReceivedAtMs:W,responseSentAt:new Date(Oe).toISOString(),responseSentAtMs:Oe,responseStatus:409}),!0}Pt(K,we,Re?.payload);let be=Date.now();return ee(n,200,{ok:!0,requestReceivedAt:ae,requestReceivedAtMs:W,responseSentAt:new Date(be).toISOString(),responseSentAtMs:be,responseStatus:200}),!0}let ue=S.match(new RegExp(`^${De(t)}/cards/([^/]+)/chats$`));if(p==="GET"&&ue){await N();let K=decodeURIComponent(ue[1]),W=String(C.searchParams.get("turn-id")||""),ae=String(C.searchParams.get("all-turns")||"").toLowerCase()==="true",Re=String(C.searchParams.get("tail-turns-before-id")||""),we=C.searchParams.get("tail-turns"),be=we==null||we===""?ae||W?void 0:1:Number.parseInt(we,10),Oe=be===void 0?m.readAll({params:{cardId:K}}):m.readAll({params:{cardId:K},body:{lastUserTurns:be}});if(Oe.status!=="success")return ee(n,400,{error:Oe.error||"Failed to read chats"}),!0;let Le=Oe.data.records.filter(Me=>!W||String(Me.turn||"")===W);if(Re){if(be===void 0||!Number.isInteger(be)||be<=0)return ee(n,400,{error:"tail-turns is required when tail-turns-before-id is provided"}),!0;let Me=m.readAll({params:{cardId:K}});if(Me.status!=="success")return ee(n,400,{error:Me.error||"Failed to read chats"}),!0;let mt=new Map,dt=[];for(let He of Me.data.records){let Ze=String(He.turn||"");mt.has(Ze)||(mt.set(Ze,[]),dt.push(Ze)),mt.get(Ze).push(He);}let ct=dt.findIndex(He=>He===Re),ht=Math.max(0,ct-be);Le=(ct===-1?[]:dt.slice(ht,ct)).flatMap(He=>mt.get(He)??[]);}return ee(n,200,{ok:!0,messages:Le}),!0}if(p==="POST"&&ue){await N();let K=decodeURIComponent(ue[1]),W=await $e(o),ae=typeof W?.role=="string"?W.role:"assistant",Re=typeof W?.text=="string"?W.text:"",we=Array.isArray(W?.files)?W.files:[],be=W?.done===!0,Oe=u.append(K,ae,Re,we);return be&&u.setProcessing(K,!1),qt(K,!be),ee(n,200,{ok:!0,id:Oe}),!0}let de=S.match(new RegExp(`^${De(t)}/cards/([^/]+)/chats/subscribe-sse$`));if(p==="POST"&&de){await N();let K=decodeURIComponent(de[1]),W=await $e(o),ae=typeof W?.clientId=="string"?W.clientId.trim():"";return ae?Jr(ae,K)?(ee(n,200,{ok:!0,clientId:ae,cardId:K,subscribed:!0}),!0):(ee(n,404,{error:`SSE client not connected: ${ae}`}),!0):(ee(n,400,{error:"clientId is required"}),!0)}let le=S.match(new RegExp(`^${De(t)}/cards/([^/]+)/chats/unsubscribe-sse$`));if(p==="POST"&&le){await N();let K=decodeURIComponent(le[1]),W=await $e(o),ae=typeof W?.clientId=="string"?W.clientId.trim():"";return ae?zr(ae,K)?(ee(n,200,{ok:!0,clientId:ae,cardId:K,subscribed:!1}),!0):(ee(n,404,{error:`SSE client not connected: ${ae}`}),!0):(ee(n,400,{error:"clientId is required"}),!0)}let xe=S.match(new RegExp(`^${De(t)}/watch-channel/([^/]+)/(subscribe|unsubscribe)-sse$`));if(p==="POST"&&xe){await N();let K=decodeURIComponent(xe[1]),W=xe[2]==="subscribe",ae=await $e(o),Re=typeof ae?.clientId=="string"?ae.clientId.trim():"";return Re?(je(n,Re,K,{},W),!0):(ee(n,400,{error:"clientId is required"}),!0)}let nt=S.match(new RegExp(`^${De(t)}/cards/([^/]+)/watch-channel/([^/]+)/(subscribe|unsubscribe)-sse$`));if(p==="POST"&&nt){await N();let K=decodeURIComponent(nt[1]),W=decodeURIComponent(nt[2]),ae=nt[3]==="subscribe",Re=await $e(o),we=typeof Re?.clientId=="string"?Re.clientId.trim():"";return we?(je(n,we,W,{cardId:K},ae),!0):(ee(n,400,{error:"clientId is required"}),!0)}let Mt=S.match(new RegExp(`^${De(t)}/cards/([^/]+)/files$`));if(p==="POST"&&Mt){await N();let K=decodeURIComponent(Mt[1]),W=String(C.searchParams.get("inChat")||"").toLowerCase()==="true",ae=String(C.searchParams.get("turn-id")||""),Re=o.headers["x-file-name"],we=String(o.headers["content-type"]||"application/octet-stream"),be=Array.isArray(Re)?Re[0]:Re,Oe=be?decodeURIComponent(String(be)):"upload.bin",Le=await it(o);return ee(n,200,rt(K,Oe,we,Le,{inChat:W,turnId:ae})),!0}let gt=S.match(new RegExp(`^${De(t)}/cards/([^/]+)/files/(\\d+)$`));if(p==="GET"&>){let K=decodeURIComponent(gt[1]),W=parseInt(gt[2],10),ae=C.searchParams.get("sn");return Dt(n,K,W,ae),!0}return !1}catch(O){let q=O?.statusCode||500;return ee(n,q,{error:String(O?.message||O)}),true}}return {get apiBasePath(){return t},get corsHeaders(){return r},handleRuntimeApi:Xr,buildPublishedRuntimePayload:Q,clearChatRecords:Ge,reportSourceFetched(o,n){let d=k[0];return d?d.board.sourceDataFetched({params:{token:o,ref:n}}):{status:"fail",error:"no board context"}},reportSourceFetchFailure(o,n){let d=k[0];return d?d.board.sourceDataFetchFailure({params:{token:o,reason:n}}):{status:"fail",error:"no board context"}},get cardStore(){return k[0]?.cardStore??{set(){return {status:"fail",error:"no board context"}}}}}}function Xo(e){let t=String(e.apiBasePath||"/api/boards").replace(/\/$/,""),r={...Gr,...e.corsHeaders||{}},s=e.serverMetaStore,a=e.boardRuntimeFactory,i=new Map,c="boards-config.json";function u(){let E=s.getText(c);if(!E)return {boards:[{id:"default",label:"Default Board"}]};try{return JSON.parse(E)}catch{return {boards:[{id:"default",label:"Default Board"}]}}}function m(E){s.putText(c,JSON.stringify(E,null,2));}function h(E){let V=String(E||"").replace(/[^a-zA-Z0-9_-]/g,"_").replace(/^_+|_+$/g,"");return V.length>0&&V.length<=64?V:null}function b(E){if(i.has(E))return i.get(E);let Y=u().boards.find(L=>L.id===E)||{},x=a(E,Y);return i.set(E,x),x}function v(E,V,Y){let x=JSON.stringify(Y),L=typeof Buffer<"u"?Buffer.byteLength(x):new TextEncoder().encode(x).length;E.writeHead(V,{...r,"Content-Type":"application/json; charset=utf-8","Content-Length":L}),E.end(x);}async function M(E,V,Y){let x=E.method||"GET",L=Y.pathname;if(x==="GET"&&L===t)return v(V,200,{ok:true,boards:u().boards}),true;if(x==="POST"&&L===t){let k=[];for await(let _ of E)k.push(_);let y=typeof Buffer<"u"?Buffer.concat(k).toString("utf-8").trim():new TextDecoder().decode(Kn(k)).trim(),l={};try{l=y?JSON.parse(y):{};}catch{l={};}let f=h(l.id);if(!f)return v(V,400,{error:"board id must be 1-64 alphanumeric/dash/underscore characters"}),true;let R=u();if(R.boards.some(_=>_.id===f))return v(V,409,{error:`Board "${f}" is already registered`}),true;let T=typeof l.label=="string"&&l.label.trim()?l.label.trim():f,w={id:f,label:T};for(let[_,F]of Object.entries(l))_==="id"||_==="label"||F!=null&&(w[_]=F);return R.boards.push(w),m(R),v(V,200,{ok:true,board:w}),true}return false}async function J(E,V,Y){let L=Y.pathname.match(new RegExp(`^${De(t)}/([^/]+)(/|$)`));if(!L)return false;let k=h(decodeURIComponent(L[1]));return k?u().boards.some(f=>f.id===k)?!!await b(k).handleRuntimeApi(E,V,Y):(v(V,404,{error:`Board "${k}" not registered. POST ${t} with {id} to register it first.`}),true):(v(V,400,{error:"Invalid board id"}),true)}async function A(E,V,Y){return !!(await M(E,V,Y)||await J(E,V,Y))}function B(E){if(!u().boards.some(Y=>Y.id===E))throw Object.assign(new Error(`Board "${E}" not registered`),{statusCode:404});return {service:b(E)}}return {get apiBasePath(){return t},get corsHeaders(){return r},handleApi:A,requireBoardService:B}}function De(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Kn(e){let t=e.reduce((a,i)=>a+i.length,0),r=new Uint8Array(t),s=0;for(let a of e)r.set(a,s),s+=a.length;return r}export{Xo as createMultiBoardServerRuntime,Yo as createSingleBoardServerRuntime};//# sourceMappingURL=index.js.map
|
|
7
|
+
`);}catch{}},15e3);o.on("close",()=>{clearInterval(U),Xe(d,n);});}async function tn(o,n,d){let f=o.method||"GET",h=d,b=h.pathname;try{if(f==="GET"&&b===`${t}/init-board`)return await se(),te(n,200,he()),!0;if(f==="GET"&&b===`${t}/sse`){await se();let J=String(h.searchParams.get("clientId")||"").trim();if(!J)return te(n,400,{error:"clientId query param is required for SSE"}),!0;en(o,n,J);for(let K=0;K<R.length;K++)re(R[K]),ne(R[K],K);return !0}if(f==="GET"&&b===`${t}/board-status`)return te(n,200,he()),!0;if(f==="POST"&&b===`${t}/mcp`){await B();let J=await Pe(o),K=typeof J.tool=="string"?J.tool.trim():"",ce=J.args&&typeof J.args=="object"&&!Array.isArray(J.args)?J.args:{};if(!K)return te(n,400,{error:"tool is required"}),!0;if(K==="inspect.file-contents")return te(n,400,{error:"inspect.file-contents is only available on /mcp-raw"}),!0;let ge=P(K,ce);if(ge&&typeof ge=="object"&&!Array.isArray(ge)){let Ce=ge;if(Ce.status==="fail")return te(n,400,{error:G(ge,"Request failed")}),!0;if(Ce.status==="error")return te(n,500,{error:G(ge,"Internal error")}),!0}return te(n,200,ge),!0}if(f==="POST"&&b===`${t}/mcp-raw`){await B();let J=await Pe(o),K=typeof J.tool=="string"?J.tool.trim():"",ce=J.args&&typeof J.args=="object"&&!Array.isArray(J.args)?J.args:{};if(!K)return te(n,400,{error:"tool is required"}),!0;if(K!=="inspect.file-contents")return te(n,400,{error:`Tool does not support raw response: ${K}`}),!0;let ge=me(ce,"card_id","cardId"),Ce=be(ce,"file_idx","fileIdx"),Te=be(ce,"head-lines","headLines"),Ee=be(ce,"tail-lines","tailLines"),Le=be(ce,"head-bytes","headBytes"),kt=be(ce,"tail-bytes","tailBytes");if(!ge)return te(n,400,{error:"inspect.file-contents requires card_id"}),!0;if(Ce===void 0||!Number.isInteger(Ce)||Ce<0)return te(n,400,{error:"inspect.file-contents requires file_idx to be a non-negative integer"}),!0;if([Te,Ee,Le,kt].filter(Je=>Je!==void 0).length>1)return te(n,400,{error:"inspect.file-contents accepts at most one of head-lines, tail-lines, head-bytes, tail-bytes"}),!0;for(let[Je,ze]of [["head-lines",Te],["tail-lines",Ee],["head-bytes",Le],["tail-bytes",kt]])if(ze!==void 0&&(!Number.isInteger(ze)||ze<0))return te(n,400,{error:`inspect.file-contents requires ${Je} to be a non-negative integer`}),!0;let zt=we().inspectFileContents({cardId:ge,fileIdx:Ce}),Wt=typeof zt?.stored_name=="string"?zt.stored_name:null,{fileRecord:qt,bytes:Rt}=ct(ge,Ce,Wt),Yt=String(qt.name||qt.stored_name||"download.bin"),Nt=String(qt.mime_type||"application/octet-stream");if(Te!==void 0||Ee!==void 0){if(!nt(Nt))return te(n,400,{error:"head-lines/tail-lines are only supported for text-like files; use head-bytes/tail-bytes for binary content"}),!0;let Je=new TextDecoder().decode(Rt),ze=Te!==void 0?He(Je,"head",Te):He(Je,"tail",Ee),Xt=typeof Buffer<"u"?Buffer.from(ze,"utf8"):new TextEncoder().encode(ze);return n.writeHead(200,{"Content-Type":Nt,"Content-Disposition":`attachment; filename="${Yt}"`,"Content-Length":Xt.length}),n.end(Xt),!0}if(Le!==void 0||kt!==void 0){let Je=Le??kt,ze=Le!==void 0?Rt.slice(0,Je):Rt.slice(Math.max(0,Rt.length-Je));return n.writeHead(200,{"Content-Type":Nt,"Content-Disposition":`attachment; filename="${Yt}"`,"Content-Length":ze.length}),n.end(ze),!0}return Ct(n,ge,Ce,Wt),!0}let F=b.match(new RegExp(`^${Me(t)}/cards/([^/]+)$`));if(f==="GET"&&F){await B();let J=decodeURIComponent(F[1]),K=Q(J);return K?(te(n,200,K),!0):(te(n,404,{error:`card not found: ${J}`}),!0)}if(f==="PATCH"&&F){await B();let J=decodeURIComponent(F[1]),K=await Pe(o);return We(J,K),te(n,200,{ok:!0}),!0}let U=b.match(new RegExp(`^${Me(t)}/cards/([^/]+)/retrigger$`));if(f==="POST"&&U){await B();let J=decodeURIComponent(U[1]);return Ve(J),te(n,200,{ok:!0}),!0}let V=b.match(new RegExp(`^${Me(t)}/cards/([^/]+)/actions$`));if(f==="POST"&&V){await B();let J=decodeURIComponent(V[1]),K=Date.now(),ce=new Date(K).toISOString(),ge=await Pe(o),Ce=ge?.actionType;if(Ce==="chat-send"&&!dt(J)){let Ee=Date.now();return te(n,409,{error:`chat handler is not configured for card: ${J}`,requestReceivedAt:ce,requestReceivedAtMs:K,responseSentAt:new Date(Ee).toISOString(),responseSentAtMs:Ee,responseStatus:409}),!0}Kt(J,Ce,ge?.payload);let Te=Date.now();return te(n,200,{ok:!0,requestReceivedAt:ce,requestReceivedAtMs:K,responseSentAt:new Date(Te).toISOString(),responseSentAtMs:Te,responseStatus:200}),!0}let ue=b.match(new RegExp(`^${Me(t)}/cards/([^/]+)/chats$`));if(f==="GET"&&ue){await B();let J=decodeURIComponent(ue[1]),K=String(h.searchParams.get("turn-id")||""),ce=String(h.searchParams.get("all-turns")||"").toLowerCase()==="true",ge=String(h.searchParams.get("tail-turns-before-id")||""),Ce=h.searchParams.get("tail-turns"),Te=Ce==null||Ce===""?ce||K?void 0:1:Number.parseInt(Ce,10),Ee=m.readAll({params:{cardId:J},body:{...Te===void 0?{}:{tailTurns:Te},...K?{turnId:K}:{},...ce?{allTurns:!0}:{},...ge?{tailTurnsBeforeId:ge}:{}}});if(Ee.status!=="success")return te(n,400,{error:Ee.error||"Failed to read chats"}),!0;let Le=Ee.data.records;return te(n,200,{ok:!0,messages:Le}),!0}if(f==="POST"&&ue){await B();let J=decodeURIComponent(ue[1]),K=await Pe(o),ce=typeof K?.role=="string"?K.role:"assistant",ge=typeof K?.text=="string"?K.text:"",Ce=Array.isArray(K?.files)?K.files:[],Te=typeof K?.turn=="string"?K.turn:typeof K?.["turn-id"]=="string"?K["turn-id"]:typeof K?.turnId=="string"?K.turnId:"",Ee=K?.done===!0,Le=u.append(J,ce,ge,Ce,Te);return Ee&&u.setProcessing(J,!1),jt(J,!Ee),te(n,200,{ok:!0,id:Le}),!0}let fe=b.match(new RegExp(`^${Me(t)}/cards/([^/]+)/chats/subscribe-sse$`));if(f==="POST"&&fe){await B();let J=decodeURIComponent(fe[1]),K=await Pe(o),ce=typeof K?.clientId=="string"?K.clientId.trim():"";return ce?Xr(ce,J)?(te(n,200,{ok:!0,clientId:ce,cardId:J,subscribed:!0}),!0):(te(n,404,{error:`SSE client not connected: ${ce}`}),!0):(te(n,400,{error:"clientId is required"}),!0)}let pe=b.match(new RegExp(`^${Me(t)}/cards/([^/]+)/chats/unsubscribe-sse$`));if(f==="POST"&&pe){await B();let J=decodeURIComponent(pe[1]),K=await Pe(o),ce=typeof K?.clientId=="string"?K.clientId.trim():"";return ce?Zr(ce,J)?(te(n,200,{ok:!0,clientId:ce,cardId:J,subscribed:!1}),!0):(te(n,404,{error:`SSE client not connected: ${ce}`}),!0):(te(n,400,{error:"clientId is required"}),!0)}let Se=b.match(new RegExp(`^${Me(t)}/watch-channel/([^/]+)/(subscribe|unsubscribe)-sse$`));if(f==="POST"&&Se){await B();let J=decodeURIComponent(Se[1]),K=Se[2]==="subscribe",ce=await Pe(o),ge=typeof ce?.clientId=="string"?ce.clientId.trim():"";return ge?(ut(n,ge,J,{},K),!0):(te(n,400,{error:"clientId is required"}),!0)}let tt=b.match(new RegExp(`^${Me(t)}/cards/([^/]+)/watch-channel/([^/]+)/(subscribe|unsubscribe)-sse$`));if(f==="POST"&&tt){await B();let J=decodeURIComponent(tt[1]),K=decodeURIComponent(tt[2]),ce=tt[3]==="subscribe",ge=await Pe(o),Ce=typeof ge?.clientId=="string"?ge.clientId.trim():"";return Ce?(ut(n,Ce,K,{cardId:J},ce),!0):(te(n,400,{error:"clientId is required"}),!0)}let Ft=b.match(new RegExp(`^${Me(t)}/cards/([^/]+)/files$`));if(f==="POST"&&Ft){await B();let J=decodeURIComponent(Ft[1]),K=String(h.searchParams.get("inChat")||"").toLowerCase()==="true",ce=String(h.searchParams.get("turn-id")||""),ge=o.headers["x-file-name"],Ce=String(o.headers["content-type"]||"application/octet-stream"),Te=Array.isArray(ge)?ge[0]:ge,Ee=Te?decodeURIComponent(String(Te)):"upload.bin",Le=await D(o);return te(n,200,it(J,Ee,Ce,Le,{inChat:K,turnId:ce})),!0}let lt=b.match(new RegExp(`^${Me(t)}/cards/([^/]+)/files/(\\d+)$`));if(f==="GET"&<){let J=decodeURIComponent(lt[1]),K=parseInt(lt[2],10),ce=h.searchParams.get("sn");return Ct(n,J,K,ce),!0}return !1}catch(F){let U=F?.statusCode||500;return te(n,U,{error:String(F?.message||F)}),true}}return {get apiBasePath(){return t},get corsHeaders(){return r},handleRuntimeApi:tn,buildPublishedRuntimePayload:he,clearChatRecords:Ke,reportSourceFetched(o,n){let d=R[0];return d?d.board.sourceDataFetched({params:{token:o,ref:n}}):{status:"fail",error:"no board context"}},reportSourceFetchFailure(o,n){let d=R[0];return d?d.board.sourceDataFetchFailure({params:{token:o,reason:n}}):{status:"fail",error:"no board context"}},get cardStore(){return R[0]?.cardStore??{set(){return {status:"fail",error:"no board context"}}}}}}function ns(e){let t=String(e.apiBasePath||"/api/boards").replace(/\/$/,""),r={...Hr,...e.corsHeaders||{}},s=e.serverMetaStore,a=e.boardRuntimeFactory,i=new Map,c="boards-config.json";function u(){let x=s.getText(c);if(!x)return {boards:[{id:"default",label:"Default Board"}]};try{return JSON.parse(x)}catch{return {boards:[{id:"default",label:"Default Board"}]}}}function m(x){s.putText(c,JSON.stringify(x,null,2));}function O(x){let L=String(x||"").replace(/[^a-zA-Z0-9_-]/g,"_").replace(/^_+|_+$/g,"");return L.length>0&&L.length<=64?L:null}function $(x){if(i.has(x))return i.get(x);let H=u().boards.find(M=>M.id===x)||{},I=a(x,H);return i.set(x,I),I}function k(x,L,H){let I=JSON.stringify(H),M=typeof Buffer<"u"?Buffer.byteLength(I):new TextEncoder().encode(I).length;x.writeHead(L,{...r,"Content-Type":"application/json; charset=utf-8","Content-Length":M}),x.end(I);}async function v(x,L,H){let I=x.method||"GET",M=H.pathname;if(I==="GET"&&M===t)return k(L,200,{ok:true,boards:u().boards}),true;if(I==="POST"&&M===t){let R=[];for await(let _ of x)R.push(_);let C=typeof Buffer<"u"?Buffer.concat(R).toString("utf-8").trim():new TextDecoder().decode(Wn(R)).trim(),y={};try{y=C?JSON.parse(C):{};}catch{y={};}let l=O(y.id);if(!l)return k(L,400,{error:"board id must be 1-64 alphanumeric/dash/underscore characters"}),true;let p=u();if(p.boards.some(_=>_.id===l))return k(L,409,{error:`Board "${l}" is already registered`}),true;let S=typeof y.label=="string"&&y.label.trim()?y.label.trim():l,A={id:l,label:S};for(let[_,j]of Object.entries(y))_==="id"||_==="label"||j!=null&&(A[_]=j);return p.boards.push(A),m(p),k(L,200,{ok:true,board:A}),true}return false}async function T(x,L,H){let M=H.pathname.match(new RegExp(`^${Me(t)}/([^/]+)(/|$)`));if(!M)return false;let R=O(decodeURIComponent(M[1]));return R?u().boards.some(l=>l.id===R)?!!await $(R).handleRuntimeApi(x,L,H):(k(L,404,{error:`Board "${R}" not registered. POST ${t} with {id} to register it first.`}),true):(k(L,400,{error:"Invalid board id"}),true)}async function w(x,L,H){return !!(await v(x,L,H)||await T(x,L,H))}function N(x){if(!u().boards.some(H=>H.id===x))throw Object.assign(new Error(`Board "${x}" not registered`),{statusCode:404});return {service:$(x)}}return {get apiBasePath(){return t},get corsHeaders(){return r},handleApi:w,requireBoardService:N}}function Me(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Wn(e){let t=e.reduce((a,i)=>a+i.length,0),r=new Uint8Array(t),s=0;for(let a of e)r.set(a,s),s+=a.length;return r}export{ns as createMultiBoardServerRuntime,rs as createSingleBoardServerRuntime};//# sourceMappingURL=index.js.map
|
|
8
8
|
//# sourceMappingURL=index.js.map
|